Sunday, March 20, 2011

two-way list comparison in C# unit test

In my C# unit tests, I often query for a list of rows based on a list of IDs. I then want to ensure that 1) for all the IDs, there was at least one row found that has that ID and 2) for all the returned rows, each row has an ID that is in the list of IDs to find. Here is how I usually ensure that:

    id => results.Any(result => result[primaryKey].Equals(id))
), "Not all IDs were found in returned results");

    result => ids.Any(id => result[primaryKey].Equals(id))
), "Returned results had unexpected IDs");

I think the use of Any and All is convenient for such checks, but I wanted to see if anyone thinks this is less readable than it could be, or if there is perhaps a nicer way of doing two-way checks like this. I'm using MSTest in Visual Studio 2008 Team System for unit testing. This perhaps should be community wiki if it's too subjective.

Edit: I'm now using a solution based on Aviad P.'s suggestion, and also the fact that the following test passes:

string[] ids1 = { "a", "b", "c" };
string[] ids2 = { "b", "c", "d", "e" };
string[] ids3 = { "c", "a", "b" };
From stackoverflow
  • IMO, not as readable as it could be. Create and document a method which returns true / false. Then call Assert.IsTrue(methodWithDescriptiveNameWhichReturnsTrueOrfalse(), "reason for failure");

    Mark Seemann : +1 This is essentially the *Custom Assertion* xUnit Test Pattern, although you might as well make it a void method and move the assertion into the method.
  • You might choose to use the Except operator:

    var resultIds = results.Select(x => x[primaryKey]);
    Assert.IsTrue(resultIds.Except(ids).Count() == 0,
     "Returned results had unexpected IDs");
    Assert.IsTrue(ids.Except(resultIds).Count() == 0,
     "Not all IDs were found in returned results");
    Sarah Vessels : This looks good, and I like how I would write `x[primaryKey]` only once. However, I think it should be `Count() == 0`, considering how `Except` is described.
    Aviad P. : Actually, you need to keep the >0, but swap the messages around. Modified my answer.
    Sarah Vessels : Why would you need `>0`? I expect there to be no difference between the list of result IDs retrieved and the list of IDs that I queried. Intellisense describes `Except` as producing the "set difference of two sequences".
    Aviad P. : Of course, you're right. My mistake, answer modified.
    Mark Seemann : A better alternative to `Count() == 0` is `Any()`.
    Aviad P. : Don't you mean !Any() ?
    Sarah Vessels : Instead of doing `Count() == 0` or `Any()`, I ended up using `Assert.AreEqual` with `Count()` and `0`.
  • NUnit has the CollectionAssert family of assertions which help readability.

How can anonymous users exchange presence information with valid users on Jabber (Ejabberd)


I am working on a social network that should allow members to chat with visitors on the site. The concept is simple.

  1. Users who have registered signup get their own account with rosters
  2. When a visitor comes to the home page of the social network, he can see some of the online members of the community
  3. Now he should be able to initiate a chat with them, by clicking on their name.

I have already got members to chat with their roster mates. My question is, how can I get an anonymous user to chat with a member and exchange presence info with him?

I have successfully managed to create anonymous accounts, members accounts and even send messages from an anonymous user to other members. But I cant get presence information from anonymous-user to member or vice versa?

BTW, the chat is JS based.

From stackoverflow
  • You're trying to break the XMPP model. Presence is an opt-in permission based system. You ask me if you can see my presence, I say yes. Generally my client will then automatically ask you if I can see your presence, and your client says yes. That's what the roster is -- yes's and no's to presence subscription requests.

    You can make chat rooms (MUC, multi user chat) that are anonymous, as well as do presence in them. It's not a roster, though. It's the closest to what you're describing without going into crazy-land with pubsub, and I don't know if you could even bend that tool far enough to have anonymous roster entries.

    Adil : Hi A.R . After a bit of research it seems to me MUC is the only sane way to go. Whats 'pusub', and where can i find more about it? Thnx for your reply.
    A. R. Diederich : Pubsub is short for "publish-subscribe". You use it to do things like offer data to people (geo location, music playing) and they subscribe to it. The XEP (XMPP Enhancement Proposal) is at In some areas a pubsub server is a PASS server -- publish and subscribe server, but that's getting off topic. Hmm, I may have been thinking of privacy lists, not pubsub. The XEP for pricay lists is found at You can use privacy lists to be "invisible" to some users, for example.
    Adil : Hi A.R. I looked into pubsub and its a bit more than i have time for (10th Jan!) . I think i'll be going with MUC and private rooms for my requirement. Do you have any suggestions that will help me do this faster. Any gotchas i should look out for? Thx, and i'll tick your answer.
    A. R. Diederich : No, nothing else to look for. Pubsub is a big XEP and I don't know if it'd work for you. I don't know if MUC will, either, but it's the closest thing there is to what you asked for.

How to get the action argument of a wp-login.php request?

I am trying to integrate my custom user system with Wordpress, and I have recently asked a question on how to redirect requests to wp-login.php to my own login/registration page, but as I was working on the pluggable functions, I realized that requests to wp-login.php can either be for login, registration, or log out.

This is set in the action argument that's made in the request. What I am trying to figure out is how to get this action argument, so I can redirect the request to my custom pages. Is there any way of doing this?

Thank you in advance.

From stackoverflow
  • Well, I've just had a massive D'oh moment.

    The request is something like: wp-login.php?action=logout

    To get the action, I simply need to $_GET['action'] or $_REQUEST['action']. I can't believe it just didn't come to me (I guess because it was Wordpress, I kept thinking there was a special way to do it, and didn't even think of getting it as I normally would).

    nickohrn : Exactly correct.

exchange axis of an "ezplot"

how can i change the horizontal and vertical axis of an ezplot of a symbolic equation?

for example an implicit equation of lambda & beta. how MATLAB can understand what i want to be for x axis and what for y axis??

From stackoverflow
  • You can use a function handle, and flip the order (x,y) vs (y,x):

    figure(1), ezplot( @(x,y) sqrt(x.^2 + y.^2 - 1), [-2 2 -4 4] )
    figure(2), ezplot( @(y,x) sqrt(x.^2 + y.^2 - 1), [-2 2 -4 4] )

    Let me give you another easier solution. Just plot your your function the usual way, then use:

    view([90 -90])

    to rotate the axes (x-axis becomes y-axis and vice versa)

  • but i have a main expression of beta not a function and is so long. because it is made of some parameters that they themselves are made of some expressions too. how can i convert it to a function? i mean, can i use the name of the main expression to make a function?

    for example if: n1,n2,m,a=const. u=sqrt(n2-beta^2); w=sqrt(beta^2-n1); a=tan(u)/w+tanh(w)/u; b=tanh(u)/w; f=(a+b)*cos(a*u+m*pi)+a-b*sin(a*u+m*pi); is the main expression.

    Amro : your function boils down to being a function of one variable *beta*, and you can write it as one expression if you want. Also I don't see a mention of *lambda* from your original question..
    Amro : tell you what, why dont you post the actual MATLAB code that you currently use to plot the function?
    gnovice : Also, *edit your question* and add the additional information instead of posting a new answer. You should also delete this answer, since it isn't an actual "answer".
    Alireza : suppose that "a" is an expression of lambda. if i want to convert "f" to a function(using it in an algorithm to find zeros, later), how can i do that without writing net explicit form?

android finish() method doesnt clear app from memory


I have an activity and I call the finish() method and the activity is not cleared from memory.

After calling finish() , I see that the method onDestroy() is executed successfully (and I clear all my variables and stuff in there).

Should it be cleared from memory or its how android works? As I understand the LifeCycle of the Activity is finished.

And if it keeps the app in memory so it runs faster the 2nd time the user uses it, what kind of objects can I leave in memory to reuse? If I understand correctly, I am suppose to clear everything on onDestroy.



From stackoverflow
  • Once onDestroy() gets called, your activity is doomed. Period.

    That being said, the process (and hence address space) allocated to your application might still be in use by another part of your application -- another activity or service. It's also possible that your process is empty and the OS just hasn't gotten around to reclaiming it yet; it's not instant.

    See the Process Lifecycle document for more information:

    Regardless, if your activity is relaunched, it will have to go through the entire startup sequence again, starting with onCreate(). Do not assume that anything can implicitly be reused.

    Daniel Benedykt : I believe this is not totally true. I don't believe the Activity is doom, because there are ways to leak memory and then the Activity will live forever.
    Trevor Johns : Even if an activity leaks memory, when the OS kills the process the memory will be reclaimed. Just like when you terminate a process on a desktop OS.
  • Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed. Don't worry about it :)

    Mathias Lin : Does this also apply for "subactivities", means if it's not the last activity open in my app? Say: if I open activity B from activity A, then B.finish(), would Android eventually keep B in memory and would I eventually also still see B in my hprof dump (in case Android didn't need to reclaim memory for elsewhere)?
  • According to this presentation from Google I/O 2008:

    Finish should also cause the process to be killed, but I wrote a quick application to test this and on Android 1.5 it does not.

    As Romain said (who incidentally is a UI Toolkit engineer for Android), your process will just sit there doing nothing anyways, so it is nothing to worry about.

  • Try using


Data manipulation with R: Restructuring Data

I have a dataset that looks like this:

a <- data.frame(rep(1,5),1:5,1:5)
b <- data.frame(rep(2,5),1:5,1:5)
colnames(a) <- c(1,2,3)
colnames(b) <- c(1,2,3)
c <- rbind(a,b)

   1 2 3
1  1 1 1
2  1 2 2
3  1 3 3
4  1 4 4
5  1 5 5
6  2 1 1
7  2 2 2
8  2 3 3
9  2 4 4
10 2 5 5

but I want it to be restructured to this:

    2_1 2_2 3_1 3_2
   1  1   1   1   1
   2  2   2   2   2 
   3  3   3   3   4
   4  4   4   4   4 
   5  5   5   5   5
From stackoverflow
  • a <- data.frame(rep(1,5),1:5,1:5)
    b <- data.frame(rep(2,5),1:5,1:5)
    colnames(b) <- colnames(a) <- paste("a", c(1,2,3), sep='')
    d <- rbind(a,b)
    recast(d, a2 ~ a1, measure.var="a3")

    I changed your example slightly, since it had numbers as variable names. This is not recommended because it permits the following nonsense:

     "1" <- 3
    [1] 1
    [1] "1"
    [1] 3

    Need I say more?

    Brandon Bertelsen : Why is it not recommended to have numbers as variable names?
    Shane : Eduardo is right. R doesn't allow you to store a variable starting with a number. Try this: 1b <- 1; b1 <- 1. If you ever attached your dataset, you could run into trouble.
    Brandon Bertelsen : Thanks for the explanation! Much appreciated

InjectableFilterAttribute never hits the Filter

On my base controller I have placed the Logger attribute. This LoggerAttribute looks like this:

public class LoggerAttribute: InjectableFilterAttribute
    public override Type FilterType
        get { return typeof (LoggerActionFilter); }

The ctor on this loggerattribute gets hit, but the FilterType getter not.

The relevant part of the filter itself looks like this:

public class LoggerActionFilter: IActionFilter
    private readonly ILoggerService logger;

    public LoggerActionFilter (ILoggerService logger)
        this.logger = logger;
    <IActionFilter Implementeation>

The filter's ctor never gets hit either.

For the wiring of my services and instantiation of servicelocator check here
The registration of the ILoggerService can be found here

What am I missing?

From stackoverflow
  • This ought to work automatically provided that the correct ControllerFactory is configured for the application.

    As far as I can tell, this must be an instance of TurbineControllerFactory or a derived class. The TurbineControllerFactory sets up the TurbineActionInvoker which is responsible for locating the correct filters.

    Note that if you register a custom IControllerFactory with your DI Container (Service Locator in Turbine terminology), this IControllerFactory type will be used instead, and if this doesn't derive from TurbineControllerFactory, it will not assign an instance of TurbineActionInvoker to the created Controller - which again means that your InjectableFilterAttribute is never invoked.

    The intended way to configure a Turbine application is to define a custom application class that derives from TurbineApplication.

    As an example, here's the entire contents of a Turbine-configured Global.asax:

    <%@ Application Codebehind="Global.asax.cs" Inherits="MyApplication" Language="C#" %>

    However, note that there isn't any Global.asax.cs.

    The MyApplication class must derive from TurbineApplication and correctly configure the DI Container. Here's one way to do it:

    public class MyApplication : TurbineApplication
        static MyApplication()
            ServiceLocatorManager.SetLocatorProvider(() => new WindsorServiceLocator());

    Obviously, you can replace the WindsorServiceLocator with another DI Container if you use a different one.

    borisCallens : I'm not sure I'm understanding this correctly. You say there is no global.asax.cs, yet you say the Myapplication code should exist. What I did in my app is have a MyMVCApplication: TurbineApplication and have that code in my global.asax.cs. Is that correct?
    borisCallens : Please also note that it's only the attributes that have problems. Controls and other classes work just fine.
    Mark Seemann : AFAICT, it doesn't matter in which file you define your MyMVCApplication class. What matters is that it derives from TurbineApplication. You don't have to have it in global.asax.cs, but you can if you'd like. Based on what I know about Turbine it makes sense that only the attributes are affected if the TurbineActionInvoker isn't wired up correctly.
    borisCallens : You can find the code for my TurbinApplication here (also updated OP):
    Mark Seemann : Your MvcApplication looks okay, but have you specified the correct Inherits attribute value in Global.asax as described above? It would have to say Inherits="MvcApplication".
    borisCallens : It was correct by default as I've merely taken the default structure and replaced the implementation of th MvcApplication class in global.asax.cs
    Mark Seemann : Can you step into the code via the debugger and check whether an appropriate Controller has an instance of TurbineActionInvoker assigned?
    borisCallens : Yep, it's an instance of MvcTurbine.Web.Controllers.TurbineActionInvoker
    Mark Seemann : I suspect that the problem could be because the ILogger service isn't registered - at least, it isn't registered in your container setup. I think you need to register it either while setting up the container in global asax, or as an IServiceRegistration as demonstrated in the FilterInjection sample.
    borisCallens : The logger is working in non-attributes, so I think the registration is ok. I'll add the logging registration to OP as reference.
    borisCallens : Also: thanks for sticking with my question through these days. Although I don't want to mark this as answer (you can't change the answer on a bountied question after end of bounty), I would like to see the reward go to you. Any idea how can be worked out?
    Mark Seemann : I must admit that an explanation and solution currently eludes me. Sanity check: Does the FilterInjection sample work in your environment? Further troubleshooting: In the debugger, can you verify whehter IActionFilter is registered in the Container?
    Mark Seemann : One further idea: What happens if you put the attribute on a concrete Controller instead of on a base Controller?
    borisCallens : The sample runs as expected. To be sure I switcherood the turbine binaries used in my app with the one from the sample. I also tried putting the attribute on a concrete class. I'm not sure how to verify the registration of IActionFilter. As mentioned in OP, the LoggerAttribute: InjectableFilterAttribute gets constructed, but the FilterType getter doesn't get hit for some reason. For now I've just put a static ref in the LoggerAttribute class and made it implement IActionFilter directly. It does the job, but works against all the work I did to make everything injectable.
    Mark Seemann : That the Attribute's constructor is hit doesn't tell you anything, because that happens as part of the type's static initialization. IIRC, all attribute constructors are invoked when the type is initialized.
    Mark Seemann : Can you try to add the Turbine source projects to your application instead of referencing the binaries? This will allow you to easily step into the Turbine code and see if everything gets wired correctly. TurbineActionInvoke.GetFilters is the interesting method there... Be aware that this registration only happens once per AppDomain, so you may have to shut down Cassini or IIS before you step into the code. `registeredFilters.ActionFilters` ought to contain your LoggerActionFilter, but it probably doesn't...
    borisCallens : Linking in was the very first thing I tried, but I ran in some new troubles as you can read here:
    Mark Seemann : I'm more or less out of ideas... It sounds like something in your setup is sick. Can you reproduce the issue on a different machine?
    borisCallens : Don't know, I can't try at this moment. I will try when my home rig is up and running again. Thanks for your collaboration. I got the feeling that it's not something in this part of the code, so I'm going to leave it as is for now. As the definition of the accepted answer is the answer that the author of the question thinks was the most helpful, I think this answer should get the rep :)
    Mark Seemann : Thanks a lot - sorry I couldn't be of more help.
  • Hi Boris,

    I have a couple of questions for you:

    • Which version of MVC are you using? v1 or v2? if v2 is it the RC or beta2?
    • Have you seen the Filter Injection sample?
    borisCallens : The projects I'm referring to use MVC v1. I also had a look at the injection sample and basically mimicked the code used there, but to no avail. I tried linking in the source code so I could follow why it isn't working out, but I had some difficulties there too as you can follow in this question:
    Javier Lozano : is your project a sample project or is it work related? I wouldn't mind taking a look at it. Perhaps we can skype it and see what's wrong. Then post the answer back to this question. Thoughts?
    borisCallens : Well, I would love to, but it's a work related project. My boss is frantic about the non-disclosure module and seeing how these are my last weeks at this firm I don't want to do anything retarded ;) Once the 3.5 turbine libs for mvc2 hit the air, I will add a similar logging attribute to my pet project too though. You can find said project at
    borisCallens : That would be for anonymous
    borisCallens : Added the logging attrib, but as currently the mvcTurbine libs aren't working with MVC2 it's not compilable.

bourne shell single-quote, doublequote & backquote question

Hi all,


   if [ "`echo $desc $status | awk -F"," '{print $3}' | awk -F" " '{print $1}' | sed '/^$/d'`" != "OK" ]; then
        echo "howdy dody"

echo $desc $status | awk -F"," '{print $3}' | awk -F" " '{print $1}' | sed '/^$/d'

First if-condition won't run, im guessing it's because of improper quotation, but i can't figure it out.

Thanks in advance for any help.

From stackoverflow
  • If you're using Bash, I'd recommend $(...) instead of back-quotes. What error messages do you get? My guess is that the -F"," option to awk is not being quoted properly. Trying inserting \ to escape the quotation marks.

    Anders : Sorry, can't use $(...) very very old shell. MMm, good suggestion, gonna try that.
    ghostdog74 : can't use $()?? then why the bash tag?
    Anders : Changed the topic.
    Anders : Was simply a matter of escaping. Thanks for the help.
    JesperE : Update the tags as well, please.
    Anders : Done, thanks for the help.
  • At first glance, you might want to try escaping some of the double quotes:

       if [ "`echo $desc $status | awk -F"," '{print $3}' | awk -F" " '{print $1}' | sed '/^$/d'`" != "OK" ]; then
            echo "howdy dody"


       if [ "`echo $desc $status | awk -F\",\" '{print $3}' | awk -F\" \" '{print $1}' | sed '/^$/d'`" != "OK" ]; then
            echo "howdy doody"
    Anders : Thanks for the help.
  • You can also use single quotes around the argument to the -F option as you have around other arguments:

    if [ "`echo $desc $status | awk -F',' '{print $3}' | awk -F' ' '{print $1}' | sed '/^$/d'`" != "OK" ]; then
  • Escaping the double quotes is certainly a good idea, but it looks like the $3 and the $1 are intended to be interpreted by awk. They are being interpreted by your shell instead. You probably want to escape the '$'s. (It is possible that you have meaningful values for $1 and $3 in the shell, but not likely.)

    Dennis Williamson : No, they're in single quotes so they don't need escaping.

Built with optimizations enabled or without debug information

I'm currently trying to find out why my InjectableAttributes never get to the filter part.
Therefor I linked in the source project directly so I could easily put breakpoints etc.
When I build however I get the following message:

The following module was built either with optimizations enabled or without debug information: 
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\[a bunch of randomly named directories]\assembly\[more random names]\MvcTurbine.Web.DLL]

To debug this module, change its project build configuration to Debug mode. To suppress this message, disable the 'Warn if no user code on launch' debugger option.

I checked the project's properties. It's configuration is set to "Active(Debug)" and the "Optimize code" check box is unchecked.

I checked again if I didn't by accident include the file rather then the project, but the references seem correct.
Just to be sure I also removed all existing bins so that all libraries are definitely rebuild somewhere, but to no avail.

In the advanced Build window the Debug output is set to Full and all options are identical to projects that are building debug info.
The config manager shows that the project is being built and has the exact same settings as all the other options.

In the Debug->Windows-Modules window the symbol status for the turbine library is PDB file does not match image I removed all corresponding pdb files on my entire system to make sure it gets re-generated, but to no avail.
To make sure I also searched for the dll on my entire system and removed them. Nothing.

What can be preventing VS from creating debug information?

From stackoverflow
  • It sounds like you've referenced the MvcTurbine.Web.DLL file rather than the MvcTurbine project. Try removing the reference and re-adding it as a project reference.

    Update Are you sure the DLL isn't coming from the GAC? Do Debug->Windows->Modules when the app is running and check the Path column.

    borisCallens : Because I started doubting myself I checked again, but no I did reference the project, not the file. I'll update the OP to clarify.
    Craig Stuntz : OK, I have added a new guess. :)
    borisCallens : I didn't know about this window :) +1! The libraries are not in the gack (for the path see the error message I updated in OP. They are optimized = no, but the Symbol status is PDB does not match image. Any idea where to go from here? I'll start with deleting pdb files for this module wherever I can find it :P
    borisCallens : *gac. I keep doing this...
    borisCallens : Does it matter that the User Code = No for this library?
    Craig Stuntz : It does if you have debugging non-user code disabled, which is the default.
    Craig Stuntz : The symbols are probably coming from your symbol cache. The filename won't match the assembly, but you can see it in the Modules window.
    borisCallens : I checked the module window for the pdb file path and removed it (complete with the entire directory it was in). I also checked the debug symbol info for all the paths that were checked if I could find any more of the pdb files. Still the same. What makes the UserCode flag be none? Should I change the value of the flag somehow or enable debug non-user code somewhere (I imagine the latter option will become bothersome for all other libraries)
    borisCallens : Just something I noted now: The mvcTurbine libs are signed. Does that change anything at all?
    borisCallens : It's not the signing. another project that's using the same signing file does generate correct debugging info. Sadly it's not that project I'm interested in.
    Craig Stuntz : Start with enable debug non-user code because it's easy to try. It's in debugging options.
    borisCallens : Yes, thought so too, but it doesn't seem to change anything.
  • Check that debug info is being generated for the project. You can do this by opening the Build tab on the Project Properties page and clicking the "Advanced..." button. Check the "Debug Info" setting. See this MSDN article for an explanation of what each option means.

    If that doesn't solve it, check that the MvcTurbine project is actually being built (Build -> Configuration Manager).

    borisCallens : The debug info output is "full". I cross checked it with other libraries that are writing debug info and it matches. In the Config mngr tie mvcTurbine projects are on Debug Any CPU and checked, just like all the others.

Is RubyAMF production ready?

Am considering using it for a project. It keeps getting recommended to me. I am wondering if anyone has had any success and can comment?

From stackoverflow
  • According to the website it is production ready. I have never used it, I cannot comment.

    It cites JukeFly as a site that uses RubyAMF.

  • I used RubyAMF in production before and it worked great but I abandoned it for webORB for rails because RubyAMF has not been supported or updated since 2008. You are doing the right thing by choosing AMF as your transfer protocol. Take a look at the performance gains on James Ward's blog it is substantial.

    NJ : Thanks! Very helpful. I am looking into webORB now.
  • I'm looking to this now and to me I find the opposite of joker's answer to be true, webORB (2006) is dated and all but dead, and rubyAMF seems to have much recent activity. That said the most promising framework for rails/flex I have found is RestfulX.

Performance comparison between IronRuby and IronPython

We're aiming to implement a scripting mechanism, using DLR's Microsoft.Scripting and hosting assembly.

Now, someone knows about any performance difference between IronRuby 1.0 and IronPython 2.6?

To my understanding they have different compilers, but IronPython seems more mature and tested, but if anyone has documentation or knowledge on this issue, that would be appreciated.

From stackoverflow
  • IronPython has had more time to focus on performance improvements, but IronRuby has made significant performance improvements as of late. However, we rarely pin IronRuby up against IronPython. While people may comment here that one or the other is faster, and certain special cases/examples may even be uses to prove this, there is no exhaustive comparison available today.

    Kel : Okay thanks, sounds like something I should consider doing in my spare time. I suppose the difference should not actually be that big, since they are both sitting on top of DLR and CLR, which does some optimizations on the backend.

svn: '.' is not a working copy

Hi All, Iam getting the below error when iam trying to execute a batch file

ROBOCOPY "C:\test" "C:\test\Source" "*" /E  /NP /V /R:3 /XD "bin" "obj" /XF "*.pj" > %log%
svn add * --force %SVNOPTIONS% >>%log%
svn commit -m "Checking in Files" %SVNOPTIONS% >>%log%
svn info -r head >%REVISION_COMMIT%

Please let me know how to resolve this

svn: '.' is not a working copy
svn: Can't open file '.svn\entries': The system cannot find the path specified.
svn: 'C:\test' is not a working copy
svn: '.' is not a working copy
From stackoverflow
  • Did you checkout the files from SVN into your TEST folder?

    soni : Yes i have done that.
    soni : Again i wanted copy the contents of source to svn working path and if any new files and changed files should be added to svn repo. But Robocopy is working fine, but iam getting this error.
  • The reason is that "*" doesn't evaluate to hidden files and folders. That means your .svn directories containing the administrative area of the working copy aren't copied.

    Skipping the "*" alltogether should work:

    ROBOCOPY "C:\test" "C:\test\Source" /E  /NP /V /R:3 /XD "bin" "obj" /XF "*.pj" > %log%

    Edit: This assumes test is a working copy, and test\Source isn't. I'm not sure what your current situation is.

  • The error is clear: Your current path is not C:\test\Source but c:\test, (svn: 'C:\test' is not a working copy) Thus, you either add pushd C:\temp\Source to your script or you change it to svn add C:\temp\Source* --force %SVNOPTIONS% >>%log% svn commit C:\temp\Source -m "Checking in Files" %SVNOPTIONS% >>%log%

    Note, if C:\temp\Source is not a working copy, i.e it does not refer to any location at svn repository, then you have to prepare it first: Given you would like to add your files to svn://svnserver/trunk/Source folder, you have to run missing following command: svn checkout svn://svnserver/trunk/Source C:\temp\Source

Making Table Row Clicks Fire Hyperlinks in jQuery

I have a table of 5 rows and 3 columns. The first column has a hyperlink in it with a target=_new. I want things such that when I click any column in the same row, it fires that hyperlink and a new window opens up via the target=_new. Is this possible in Javascript or jQuery? I found I was able to access the href, at least, by doing this:

$('#search-results TD').click(function() {
  var s = $(this).siblings(':first-child').contents().attr('href');

Note that simply adding hyperlinks on the other table columns besides col 1 is not desirable because I want a click in that row (even not on top of the hyperlink) to fire that hyperlink.

Note also that might be disabled in some browsers, but target=_new gets right on through.

From stackoverflow
  • You should be okay with, because you're calling it in direct response to a click by the user (make sure you're calling it from the event handler or a function called by the event handler, not after a setTimeout or some such). That's usually an exception. You could call the click function on the link's element, but that's not guaranteed to work cross-browser.

    Other than that, I can't think of another way to do it other than the ones you've said are out.

    Volomike : Hey, you're right. This is surprising because I thought would be disabled. Here's my code:$(this).siblings(':first-child').contents('a').attr('href'));
    T.J. Crowder : Yeah, browsers are somewhat sophisticated with their pop-up blocking now. Pop-ups in direct response to a user's action are usually okay...

Constructing a python set from a numpy matrix

I'm trying to execute the following

>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'

How can I easily and efficiently create a set from a numpy array?

From stackoverflow
  • The immutable counterpart to an array is the tuple, hence, try convert the array of arrays into an array of tuples:

    >> from numpy import *
    >> x = array([[3,2,3],[4,4,4]])
    >> x_hashable = map(tuple, x)
    >> y = set(x_hashable)
    set([(3, 2, 3), (4, 4, 4)])
  • If you want a set of the elements:

    >> y = set(e for r in x
                 for e in r)
    set([2, 3, 4])

    For a set of the rows:

    >> y = set(tuple(r) for r in x)
    set([(3, 2, 3), (4, 4, 4)])
  • If you want a set of the elements, here is another, probably faster way:

    y = set(x.flatten())

    PS: after performing comparisons between x.flat, x.flatten(), and x.ravel() on a 10x100 array, I found out that they all perform at the same speed. For a 3x3 array, the fastest version is the iterator version:

    y = set(x.flat)

    which I would recommend because it is the less memory expensive version (it scales up well with the size of the array).

    : Good suggestion! You could also use set(x.ravel()), which does the same thing but creates a copy only if needed. Or, better, use set(x.flat). x.flat is an iterator over the elements of the flattened array, but does not waste time actually flattening the array
    EOL : @musicinmybrain: very good points! Thank you!

How can I count number of logical conditions used in if,elseif or while in Perl?

hi all... i have a while,if,elseif statements in a file with multipe conditions inside it... it is a C language...the format is mentioned below is standard for all the multiple conditions.So no worries about the indendation.The only problem is to check how many conditions are there and list as per output format that i have described.... eg if my C file have a code...

      condition1 &&
      condition2 ||

i want to count how many conditions are there inside the while and my output should be
of like this...

  1    condition1 &&
  2    condition2 ||
  3    condition3

i have written the code and it works fine for simple one.. my code....

open(A,"e:\\a\\a.txt")or die;
       if($a[$line]=~/(.*)[\&&\||]/g){print"$count $a[$line]";$count++;}  
       elsif($a[$line]=~/\(.*\)[\&&\||]/g){print"$count $a[$line]";$count++;}  
 last if($a[$line]=~/\{/g);

but for complicated conditions like

         condition1 &&
         condition2 &&
        ) ||
          condition4 ||
          condition5 &&


am getting the output like

       1  condition1 &&
       2  condition2 &&
       3 ) ||
       4  condition4 ||
       5  condition5 &&

which is not desired.... my intension is to count all the conditions regarding however complicated it is..... please help me...

desired output may be

while( ( 1 condition1 && 2 condition2 && 3 condition3 ) || ( 4 condition4 || 5 condition5 && 6 condition6 ) ) since it has used 6 conditions inside... hence forth for any cases.

From stackoverflow
  • What language is this? Are full parsers available for this language? If so, I suggest you use them. If not, I think you'll have a hard time solving this problem reliably. Your approach relies on the specific way the programmer formatted his code.

    Right when you solved your problem for your example, somebody will throw the following at you:

            ( condition1 && condition2)
              && condition3            )
            ( condition4 || condition5
              && condition6            )

    If you insist on writing your own mock-up parser, then I would suggest the following:

    • Do not parse line-wise. Feel free to read line-wise. But don't parse each line separately.
    • Extract the contents of the matching set of parenthesis after the while. The clue here is "matching". Run "perldoc -q matching" and have a look at the first Perl FAQ entry coming up about parsing matching/nesting parenthesis.
    • When you have the code contained in the parenthesis, try to extract the number of operands to the logical operators by splitting on the logical ops.
    • Despair if the operands (conditionX) may contain strings which contain, for example "&&".

    Tools you may find useful in order of sophistication:

    • perldoc -q nesting as mentioned above
    • The Text::Balanced module (Available out of the box with any perl version >= 5.8)
    • The Parse::Yapp and Parse::RecDescent parser generator modules from CPAN. Yapp is underdocumented, but doesn't suffer from some pathological problems P::RD suffers from.
    • Parse::Eyapp presumably combines the good points of both of the above modules.
    lokesh : the format i have send is standard all the multiple conditions will be of same standard so no worries about the indendation.The only problem is to check how many conditions are there and list as per above output format that i have described earlier.
  • I hope you can learn something from this.

    use 5.010;
    use Text::Balanced qw(extract_bracketed);
    my $logical_keywords = join '|', qw(while if);
    my $logical_operators = join '|', map {quotemeta} qw(|| &&);
    my $code = do { local $/; <DATA>; }; # slurp the whole thing into a scalar
    for my $chunk (split /$logical_keywords \s+/msx, $code) {
        # a chunk is the (...)... part after an »if« or »while«
        # until the next »if« or »while«
        next unless $chunk =~ /\A [(]/msx;
        # discard preceding junk
        my $balanced_parentheses = extract_bracketed($chunk, '()');
        # only the (...) part after an »if« or »while«
        my @conditions = split /(?<=$logical_operators)/msx, $balanced_parentheses;
        say scalar(@conditions). " conditions were found. And here's the enumerated code block.";
        my $index = 0;
        for my $condition (@conditions) {
            my ($pre, $post) = $condition =~ /( (?: [(] | \s )* ) (.*)/msx;
            print "$pre $index $post";
        say; # force a new line
    # start of the source code.
          condition1 &&
          condition2 ||
    # some other code
             condition1 &&
             condition2 &&
            ) ||
              condition4 ||
              condition5 &&
    (some (nested (nonsense))) || (
    if (
        condition1 &&
        ) ||
        ) ||
        condition4 &&
        ((these parentheses do not count) &&
            neither does this.


    3 conditions were found. And here's the enumerated code block.
           1 condition1 &&
           2 condition2 ||
           3 condition3
    6 conditions were found. And here's the enumerated code block.
              1 condition1 &&
              2 condition2 &&
              3 condition3
            ) ||
               4 condition4 ||
               5 condition5 &&
               6 condition6
    5 conditions were found. And here's the enumerated code block.
         1 condition1 &&
         2 condition2
        ) ||
         3 condition3
        ) ||
         4 condition4 &&
         5 condition5
    lokesh : am using perl v5.8.6... will it work in that case????.. i have seen text balanced has been installed by default.
    daxim : No, obviously it won't. Why didn't you just try it instead of asking? It can be easily backported to old Perl. Go accept one of the answers you received.
    lokesh : hi i works great but logically while ( (condition1) && (condition2) || (condition3) ) { statements; } if we have a statements it prints in different manner.. can you help me out..
  • For this I think I'd go with something like PPI, which often does a good enough job of parsing Perl source, and certainly is going to do a better job of most people starting from scratch.

    You might also look at Devel::Cover, which includes such information in its report as part of its conditional coverage metric.

Creating Stream DATABASE in a remote server

Whith the assistance of a very good fellow from this forum (Mr. DJHnz) i solve my first issue regarding the creation of a stream database Now i'm facing another issue I'm giving you the code:

USE [master]
/****** Object:  StoredProcedure [dbo].[sp_AddStreamDB]    Script Date: 12/21/2009 09:55:47 ******/
ALTER PROCEDURE [dbo].[sp_AddStreamDB](
    -- Add the parameters for the stored procedure here
    @DPath varchar(MAX),
    @DBName varchar(50),
    @Qchar varchar(1) = "'"
) AS
-- Insert statements for procedure here 
    @ErrMsg nvarchar(4000),
    @DBName1 varchar(50),
    @DBName2 varchar(50),
    @DBNamefs varchar(50),
    @DBNamelog varchar(50),
    @FileGroupN varchar(100),
    @DATName varchar(MAX),
    @LOGName varchar(MAX),
    @FSName varchar(MAX),
    @CreateSdb nvarchar(MAX),
    @Statement nvarchar(MAX)
    SET @DBName1 = (@DBName + '1')
    SET @DBName2 = (@DBName + '2')
    SET @DBNamefs = (@DBName + 'fs')
    SET @DBNamelog = (@DBName + 'log')
    SET @FileGroupN = (@DBname + 'StreamGroup')
    SET @DATName = (@Qchar + @DPath + @DBName +'_dat.mdf' + @Qchar)
    SET @LOGName = (@Qchar + @DPath + @DBName +'_log.ldf' + @Qchar)
    SET @FSName =  (@Qchar + @DPath + @DBName + '_fs' + @Qchar)
SET @CreateSdb =('CREATE DATABASE ' + @DBName + ' ON PRIMARY (NAME = ' + @DBName1 + ', FILENAME = ' + @DATName + '), FILEGROUP ' + @FileGroupN + ' CONTAINS FILESTREAM (NAME = ' + @DBNamefs + ', FILENAME = ' + @FSName + ') LOG ON (NAME = ' + @DBNamelog + ', FILENAME = ' + @LOGName + ')')
    SET @Statement = '   '

EXEC master.sys.sp_executesql @CreateSdb, @Statement

RAISERROR (@ErrMsg,1,1)

So far to point everything works fine until the remote server tries to create the neccessary files for the stream DB

then he gives the following error:

Unable to open the physical file "C:\sqlDATA\RemoteDB_fs". Operating system error -2147024891: "0x80070005(Access is denied.)".

The name of the drive C:\ lies on the remote machine (a machine near to me in the same network with Windows server 2003; later i will run the program for my ISP machine) the subfolder sqlDATA\ is already there i have created manually as it should be. In my local machine the all package works fine and the DATA BASE created fine but the issue starts when i use remote server.


Why i receive this ERROR?

From stackoverflow
  • The SQL Server service account does not have rights on C:\SQLData

    Lefteris Gkinis : The account is the 'sa' and this account has all the rights also i have another account 'Administrator' and i'm using it and gives me the same error But now i'm thinging please give me few seconds to try the account DOMAIN\Administrator
    gbn : Only the domain account running the SQL Server service matters. "sa" will not have file system rights, nor will any other login via SQL Server. It's separate to internal SQL Server permissions
    Lefteris Gkinis : Sorry for my delay, I use the account of build in Administrator with ServerRole DiskAdmin and dbcreator and securityadmin and serveradmin but nothing i receive the same error: Unable to open the physical file "C:\sqlDATA\RemoteDB_fs". Operating system error -2147024891: "0x80070005(Access is denied.)". ==
    Lefteris Gkinis : The 'sa' account is not diskadmin server role
    Lefteris Gkinis : and i can't do it
    gbn : "sa" is every role. Like I said, it's the service account permissions that matter. Not the login used to connect to SQL Server
  • As @gbn explained and also:

    • C:\sqlDATA directory must exist.
    • The \RemoteDB_fs sub-directory for file-stream must not exist.
    Lefteris Gkinis : Yes that is right the C:\sqlDATA\ exists and the RemoteDB_fs not exist i know that because it is elementary for stream Data Base creation but i receive the same error and with other sql accounts where i have create

Meta Refresh: Count starts after page load or before?

<meta HTTP-EQUIV="REFRESH" content="0; url=">

Does the count start from full page load or as soon as the page is loading.

Having tested it, it looks to me it starts counting after full page load?

I appreciate a confirm before I continue with this solution. I didn't like Javascripts timeout.

Will this play nicely with IE6?

From stackoverflow
  • I think after page load too, and Yes, its working well with IE6.

    but best way is the redirecting with 301, 302 URL redirection from server, Meta Refresh is kind of deprecated one, still working though.

    T.J. Crowder : `refresh` has a different purpose than a 301 or 302; it allows presenting a page and then refreshing it (or replacing it) *after an interval*. (But good to point the author at 301 and 302 in case they're more appropriate for what he's doign.)
  • I expect it's implementation-dependent when this happens (although that doesn't mean all implementations don't do much the same thing; one would have to test). The HTML5 spec doesn't address when the countdown begins.

    But how much does it really matter? The time is in seconds, and we're all shooting for sub-second page load times anyway, right? ;-)

    IE6 respects the refresh header, yes (including as a meta tag).

    Andrzej Doyle : More importantly - we're all shooting for post-1990s, non-deprecated techniques, so are using one of the many proper alternatives instead of meta-refresh tags, right? ;-)
    T.J. Crowder : @Andrzej: :-) I didn't realize (tsk!) it was deprecated until Daniel's comment above; and I find it odd that they don't mention that in the HTML5 spec, I wonder if that deprecation is outdated. I'm not seeing a non-JavaScript alternative for certain use cases; in the absense of one, it seems inappropriate to deprecate an existing mechanism. They may have gotten feedback on that.
    Daniel Vassallo : @TJ Crowder: It looks like W3C may have deprecated the deprecation for meta-refresh in HTML5 :)
    T.J. Crowder : @Daniel: LOL! (....15....)

APC vs pecl uploadprogress

In the Status Report page in drupal, i usually find this message (on fresh installation):

Your server is capable of displaying file upload progress, but does not have the required libraries. It is recommended to install the PECL uploadprogress library (preferred) or to install APC.

But i never understood why its preferred the PECL uploadprogress library over APC, and that's my question today.

Is pecl uploadprogress faster, take less system resources, or is more easy to install/configure/use then APC?

Anyone have ideas about why it is preferred over APC? (googlin around for APC vs pecl uploadprogress doesnt return nothin usefull)

From stackoverflow
  • There is an interesting information in the second comment of this blog-post : Upload Progress Meter - Common issues and some answers : (quoting) :

    The main difference is: this extension uses the filesystem as temporary storage, APC uses shared memory. And if you'd like to use another Bytecodecache than APC or do not want to install APC for any reason, this one provides that functionality, too.

    (Both the blog-post and that comment are from Christian Stocker, one of the two authors of the pecl::uploadprogress extension ; so I guess he knows what he's talking about ^^ )

    DaNieL : Ok, but why using the filesystem instead of shared memory is better? Im not a system expert, but this sounds like uploadprogress is slower (doesnt it use a swap-like system?) Or am i totally wrong? (i admit that i dont know exactly what im talking about ;)
    Pascal MARTIN : Considering you have a few GB of RAM (shared memory), and several dozens (if not hundreds) of GB on your disks, I suppose it's "better" to not eat too much RAM with temporary files. OK, RAM might be faster... but considering those files are being uploaded, which means (slow) network connection, the difference in speed between RAM and disk will be negligible, when compared to the time taken to do the upload -- else, you wouldn't need a progress indicator ;-)
    DaNieL : Thanks, really nice explanation!!
    Pascal MARTIN : You're welcome :-)
  • Try to organize your uploads via flash. is the best solution. File will be uploaded by flash, and flash will take care about progress monitoring and it doesn't depend on server side. It also allows to select multiple files in "Browse file" window.

    Pecl module is little hacky. APC gives more stable solution. But in 99% swfupload solves problem better.

    DaNieL : I hate using flash for this silly things that can be easly (and better, imho) done without flash. Flash is needed for other kind of issue, i'll use it for file uploads just when i'll really need the multiple file selection (that i admit is really convenient)