Wednesday, April 6, 2011

Inheriting ThreadStatic values to implement dynamic scoping in C#/.NET in multithreaded context

Is there a way to make newly-spawned threads inherit the values of ThreadStatic state (or something like it) on their parent threads? I would like to use this (or something like it) to implement "dynamically scoped" special variables that contain operation/task context information to use for tracking/logging, etc. Is this a reasonable approach, and can it be made to work?

From stackoverflow
  • You can't "inherit" values. However, the new ThreadLocal<T> class for .NET 4 allows you to provide a Func<T> in the constructor, which can initialize the thread based on the parent's state. This would provide a reasonable workaround.

    Max Strini : Thanks, this is certainly interesting. But how would I allow the child to access the parent's state?
    Reed Copsey : You could use a lambda in the parent that provides access to the variable(s) in question that are required to initalize the ThreadLocal. This uses a form of lazy initialization, so on first use, you'd get the current parent's state.
    Max Strini : this didn't do what I needed at the time for some reason I've forgotten, but it was nice to know about this anyway.

Does the Jquery validation plugin require a form tag?

I want to validate some asp.net textboxes with the jQuery Validation plugin found at http://docs.jquery.com/Plugins/Validation, but it appears that the elements must be between a form tag. If I have just a couple elements, I would hardly call that a form, so I would rather not have them wrapped inside a form element. Is there a way around this? Also, if I have two buttons on the form, a cancel and a submit button and I want the form only to validate when the submit button is clicked, but not the cancel button, how is this accomplished?

From stackoverflow
  • The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form.

    You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

    For example, using a class to identify the correct submit button:

    
    $(document).ready(function() {
      var form = $("form");
    
      form.validate({
        onsubmit: false,
      });
    
      //Validate form only if validation submit button is clicked
      //Allows cancel submit buttons to function properly
      $('.validate', form).click(function() {
        if (form.valid()) {
          form.submit();
        }
        else {
          form.validate().form();
        }
      });
    
    });
    
  • I have just a couple elements, I would hardly call that a form, so I would rather not have them wrapped inside a form element.

    If the elements are not within a form tag, then it is not a valid HTML document, so behavior within script might get wonky depending on how the browser deals with the malformed HTML.

    Most browsers will create a form implicitly, but now you have no control over the form's behavior. The defaults are usually be a post action form targeted at the requested page's URL.

    The problem is, you probably have no idea what selector to use in the JQuery to get a reference to the form... but I suppose $(form) would do the trick.

    validate when the submit button is clicked, but not the cancel button

    The plug-in intercepts and runs on the submit event of a form. Generally cancel buttons are html input elements with the type attribute set to "reset":

    <input type="reset" value="cancel" />
    

    A reset type button will not cause the form to submit, and this will not trigger the validation.

    If you use another button type, make sure the onclick even returns false. This cancels the form's submit action but still allows you to run javasctipt of your own when the button is clicked.

    Xaisoft : I am using an asp:Button for the Cancel and Submit.
    Xaisoft : I actually figured out the second part. I set the UseSubmitBehavior property to false for the cancel button and it made it a regular input type=button instead of a type=submit and that solved the issue. I decided to use the LiveValidation script. It works pretty well. Thanks for the help.

Write a cmd line script to parse an xml file

What would be the best solution to check (from the command line with a script), if a certain xml file contains this line:

<endpoint uri="endpoint.php" class="flex.messaging.endpoints.AMFEndpoint"/>

or this line

<!-- <endpoint uri="endpoint.php" class="flex.messaging.endpoints.AMFEndpoint"/> -->

and stop execution if the second one (commented out) is found?

Thx, martin

From stackoverflow
  • Single line or across multiple lines? If the former, you can use grep.

    Update: There seem to be some XML aware variants like xgrep, xmltwig and xmlstarlet.

    Maxim Veksler : +1 for xmlstarlet
  • assuming pattern occurs at single line

    #!/bin/bash
    awk '
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/ && /<!--/{
        exit
    }
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/{
        # to execute external script inside awk, uncomment below
        #cmd = "myscript.sh"
        #system(cmd)
    } 
    ' file
    

    OR you can return a code back to shell

    #!/bin/bash
    var=$(awk '
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/ && /<!--/{
        print 1
    }
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/{
        print 0
    } 
    ' file)
    [ "$var" -eq 1 ] && exit
    [ "$var" -eq 0 ] && ./myscript.sh
    
    Noufal Ibrahim : These are not totally reliable. A node called
    ghostdog74 : its OP's sample, not mine. If there is possibility of "s" in endpoint, then matching it exactly will do.
    martin : this looks good! It is sufficient how it is checked. I am trying to execute a script in the second case... just putting a command in there does not work for me e.g. (./doSomething.sh) do I need to use exec()?

what is the latest version of WinForms? And how does this relate the version of .NET?

What is the latest version of WinForms? And how does this relate the version of .NET?

For example in VS2008 with .NET 3.5 is there Windows Forms 3.5 under the bonnet?

From stackoverflow
  • I don't believe there's a separate version number for Windows Forms. Why would there be?

    Greg : I just wasn't sure as a newbie - I'm looking for a good book (ideally available in PDF) for Windows Forms programming in VS2008 with .NET 3.5. All I seem to be able to see so far is "windows forms 2.0" type books...
    Paul Sasik : 2.0 will be fine for forms programming for you. Little has changed there. The biggies are LINQ, WCF, WPF... ah. There you go. WPF. Windows Presentation Foundation. That's the "new" forms engine. You might want to take a look at that before diving into the "older" forms technology.
  • Windows Forms is just a subset of the Framework Class Library and yes, the current version is 3.5.

    WPF Update

    A new presentation technology has been added to .Net since 2.0 called WPF (Windows Presentation Foundation) It is the newer way to create .Net UIs and which is also used by Silverlight.

    WPF described on Wikipedia

    Greg : ok - so I should really look for a programming Windows Forms 3.5 text then...thanks
    Paul Sasik : Copied from below: 2.0 will be fine for forms programming for you. Little has changed there. The biggies are LINQ, WCF, WPF... ah. There you go. WPF. Windows Presentation Foundation. That's the "new" forms engine. You might want to take a look at that before diving into the "older" forms technology.
    Ash : Microsoft call it the 'Framework' Class Library. 'Foundation' can be confused with WPF etc.
    Paul Sasik : @Ash: Thanks... post midnight brain mush mixed with years of MFC coding...
    TrueWill : Note that you do want .NET 3.5 SP1.
  • .Net provide a bouquet of different technologies to do your job. Winforms is a technology that lets you create desktop applications, and so does WPF. ASP.net allows you to create web applications and WPF is for creating workflow foundation programming etc. etc.

  • On my PC with .NET 3.5 SP1 installed, System.Windows.Forms is version: 1.0.5000.0 in the Global assembly cache. The actual file version (and Product version) of 'System.Windows.Forms.dll' is 1.1.4322.2032.

    It is unrelated to the overall .NET version, there is no Windows Forms 3.5 although Microsoft would say there is, ie Windows Presentation Foundation (WPF).

    If you need to build classic Windows desktop applications you would use Windows Forms.

    If you need to build more modern looking desktop applications that support text flow layouts, richer formatting and styling and graphical animation then Windows Presentation Foundation is the better choice.

How to exclude specific fields from a Rails XML output

I am working on a RoR project which outputs XML to RESTful requests. The problem is it includes the "updated-at" and "created-at" fields in the output.

I have tried using:

:exclude -> [ :created_at, :updated_at ] 

and

:exclude -> [ 'created-at', 'updated-at' ]

but the output still renders them. How do I exclude them from the rendering without these?

From stackoverflow
  • The option you want is called :except, not :exclude. For example:

    obj.to_xml(:except => [ :created_at, :updated_at ])
    

    For more info, see the Rails API docs for this method.

    Ash : This worked perfectly. What's more, I has discovered that it applies the `:except` to the entire xml, including any `:include`'s. Cool. Exactly what I needed.

Django/Python: How do you start a new process in Python?

After a customer uploads an image I want to re-size an image to 8 different sizes and then send them up to S3 and save them to the file system. Obviously this could take a long time (seconds) and I would want to do it in a "multithreaded" way (I quote that because I don't care if it's actually multithreaded or if it's some other functionality). My understanding is that because of the GIL in Python you cannot successfully use multithreading for things like this because it uses the same process and therefore works exactly the same as if you did it in your code's normal flow (vs multithreading). Is there some other, better way of opening a new process in Python for this sort of task?

From stackoverflow
  • If you want to call an external process, use the subprocess module.

    If on the other hand you want to side-step the GIL and spin of some Python task, use the multiprocessing module. It provides an interface very much like the threading package's but utilizes subprocesses so you are not bound by the constraints of the GIL.

    orokusaki : What would be the reason for using subprocess (ie, what would be an external process)?
    jkp : @orokusaki: say you want to process some file with some external utility, EG, you are processing video and you want ffmpeg to transcode it for you: in this case you'd use the subprocess module to fire up ffmpeg, pipe your input data to it and read it's output to get the processed data. If what you want is to run some long-running Python routine without being affected by the GIL however, the multiprocessing package is what you want.

Redirecting Wordpress's Login/Register page to a custom login/registration page

I have a website, with a user system. I want to integrate wordpress's user system into that website's, but I still want to use the website's register/login pages. I don't want anybody to be able to login or register using Wordpress's login or registration forms. Instead, when they're try to access the login/registration pages in Wordpress, I want those pages to redirect them to my own login/registration pages.

Is there any way of doing this? I've tried Google, but all I could find was redirection AFTER the user logs in or registers, which is not what I want.

Thank you in advance.

From stackoverflow
  • You might be able to latch onto the login_head hook and issue a redirect there.

  • add_action('init','possibly_redirect');
    
    function possibly_redirect(){
     global $pagenow;
     if( 'wp-login.php' == $pagenow ) {
      wp_redirect('http://google.com/');
      exit();
     }
    }
    
    Bruno De Barros : This worked for me, thank you :)
    this. __curious_geek : Where shall I register add_action call? where do I call this ? excuse me for I'm a .Net developer.
    nickohrn : You have two options. Either throw the above code in a plugin or create a functions.php in your themes' folder and add the above.

How to remove JQuery Dialogs from the DOM

I have run into a situation where I need to manually remove old dialogs before creating new ones. In another thread, the following method was suggested:

$('.ui-dialog').empty().remove();

And I think this would work, but I do have other dialogs that I do not want to remove from the DOM, and I think this method would get rid of all of them. Inspecting the page with Firebug shows that once JQuery creates a dialog out of the html you provide, it gives it standard wrapper divs, all with the same classes. These are:

ui-dialog ui-widget ui-widget-content ui-corner-all  ui-draggable

So they're pretty generic, and it's hard to find a unique characteristic about the outer wrapper classes that need to go. I'm trying to find a way to only remove the dialogs that I want to remove, and leave the others. Any ideas?

From stackoverflow
  • Create an array on DOM ready and add references to the desired dialogs as you display them. Then, when you wish to remove them, pass the array to jQuery and call remove()

  • Why don't you add a custom class to dialogs that are closed. So when you close a dialog, call:

    thisDialog.addClass("olddialog");
    

    Then you can simply remove them all using:

    $(".olddialog").remove();
    
    BAHDev : I'm not sure what I would add a custom class to. Remember I need to remove the outer wrapper JQuery gives it (not any html I've written), and everything underneath. So if you're suggesting I add a class to the div I originally used to create the dialog, that would just add a class to the html underneath the wrapper. Then when I try to remove it, it would just remove what's underneath the wrapper. I need a way of selecting only the outer wrappers I want. Whether that means selecting them and adding a class or just selecting them and removing them, the problem is still the same. Thanks though.
    Philippe Leybaert : Then you can use has(): $(".ui-dialog:has(.olddialog)").remove();
  • The proper way is $('#yourdialog').dialog('destroy').remove(); presuming your dialog has a proper ID.

    BAHDev : @CalebD, thanks for this response, and I have tried it. But for whatever reason, this is not removing the dialogs that jQuery is creating. I assumed it had something to do with me trying to do a remove() on the original selector instead of on the outer wrappers that JQuery has assigned.
    CalebD : The .dialog('destroy') call should remove all of the wrappers and restore the element to its initial state and then .remove() kicks it out of the DOM. How are you creating the dialogs?
  • EDIT:

    From other comments you made ive gleaned you want to preserve the content but doesnt dialog.destroy just return it to pre-init state ie. minus dynamic outer markup?

    you could give them a unique 'dialogClass' when you create them and reference them that way or you could provide a callback that ads an id - or add the id before you dialog the element.

    Although, personally i only ever use one dialog per page/view and just reset the content as needed.

  • SELF-ANSWER:

    So based on Philippe's answer to my original question I took the following approach, which worked:

    When creating the dialog, usually you're creating it based on an ID, and once JQuery creates the dialog, that html (with the ID) is still underneath the wrappers. To make sure I was removing the correct dialog, I used JQuery's has, like this:

    $('.ui-dialog:has(#' + $myDialogDiv.attr('id') + ')').empty().remove();
    

    This first empties the wrapper's contents, then removes it from the DOM.

    Thanks to Philippe for the ideas.

  • I know this topic is old, but I recently ran into the same situation. For my case, I dynamically create dialogs and use .load(). jQuery really does wacky stuff with the DOM and was causing me significant troubles. There was unnecessary "crap" left in the DOM after closing, and sometimes, removing the dialog. I could not remove the "div" that it was inside of because I actually use the contents of the div to maintain some state information. I came up with the following code and tested it in a limited fashion to verify it worked. It does seem to remove all of the unnecessary baggage that jQuery was leaving behind. I even tested it opening several windows and monitored the state of the DOM during the process to ensure each dialogs' state was maintained correctly. I'll post the entire code here (with the exception of the loaded dialog which was nothing more than a div with some code in it.

        <html>
            <head>
                <link href="css/redmond/jquery-ui-1.8.1.custom.css" type="text/css" rel="stylesheet" media="screen" />
                <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
                <script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
    
                <script type="text/javascript">
                    $(document).ready (function () {
                        $("#openDialog").click (function () {
                            $("<div></div>")
                                .load ("loadDialogTest.php")
                                .appendTo ($("#containingDiv"))
                                .dialog ({
                                autoOpen: 'false',
                                title: 'Test This!',
                                close: function () {
                                    $(this).dialog ('destroy').remove ();
                                }
                            }).dialog ('open');
                        });
                    });
                </script>
            </head>
    
            <body>
                <a href="#" id="openDialog">Open it</a>
    
                <div id="containingDiv">
                </div>
            </body>
    
        </html>
    

Doctrine to Propel snippet

I am using the Propel ORM with SF (1.4). I am writing a class, and I need to rewrite a query Doctrine query into Propel:

  $q = Doctrine_Core::getTable('sfGuardRememberKey')->createQuery('r')
        ->innerJoin('r.sfGuardUser u')
        ->where('r.remember_key = ?', $cookie);

  if ($q->count()){ // Do Something }

can anyone help with the conversion?

From stackoverflow
  • Try it and fix column names:

    $c = new Criteria;
    $c->addJoin(sfGuardRememberKeyPeer::USER_ID, sfGuardUserPeer::ID, Criteria:INNER_JOIN);
    $c->add(sfGuardRememberKeyPeer::REMEMBER_KEY, $cookie);
    $result = sfGuardRememberKeyPeer::doSelect($c);
    if(count($result)) // do something
    
    Stick it to THE MAN : Fixed a simple, single typo - then it worked like a charm. tx!

Reporting unit test results.

I am writing a paper for a scientific conference. Just to be thorough, in that paper I said I made unit tests for the components in the system among all the other tests (system testing, usability etc) I made.

In the results section, for the unit tests I simply said that all the tests passed. I submitted the draft to my adviser and now he's telling me that I need to give a more detailed summary of the unit tests I made.

I have never heard of writing a result summary for unit testing. Is there such a thing?

From stackoverflow
  • Here are some additional metrics you could consider reporting:

    • The number of unit tests
    • Code coverage

    In addition to that, you may choose to describe which unit testing framework you used, and whether you used a particular methodology (Test-Driven Development or Test-After).

  • A detailed summary of the unit tests could include a measure of code coverage perhaps, or a chart showing where you have achieved code coverage. But even this is not particularly valuable. This is part of the problem with unit tests - it's easy to add a unit test to add additional code coverage without really adding to the confidence you have in your code.

    If you have some specific tests that, for example, test that known input/output combinations worked, or that test the handling of certain edge or exception cases, then you can document those. If you used test-driven development, where the test comes from the problem and its analysis rather than from the code in a "retrofitted" manner, then say that as well.

    By all means put some simple metrics in there, but you always have to take these with a pinch of salt...

    Jeune : It's okay if it doesn't add any confidence to the code, it's just for the paper anyway. What's code coverage?
    David M : Code coverage is a measurement of what proportion of your code has been exercised by a unit test, normally expressed as a percentage. There are tools to measure this depending on the technology you are using (e.g. NCover, Clover, Emma)
  • On most runners, the minimal output will also show the number of tests run (how can you tell it found any tests?).

    Other features one might see are:

    • how many tests were skipped (on frameworks that support it)
    • code coverage
    • execution time (how long did the tests take)
    • the actual names of the unit tests or their descriptions.
  • If the unit tests are unit tests a la jUnit, then could tweak your framework to display the name of the tests (names of TestCase methods) and the assertion messages, if any to generate a raw description of the unit tests. I had to do that once to satisfy the request of a QA guy.

    Perhaps he believed the unit tests were executed manually, and just asked details about them, does the paper make it clear the unit tests are automatic ?

    Jeune : Yes I mentioned that the tests were automated but I doubt if he knows what that means. IMO, He wouldn't know the first thing about unit-testing. Just really trying to comply with his requirements.

How to get Group node in Alfresco 3.1's Java-Backed Webscript

With Javascript Webscript, I can get a group node with the following code:

var group = People.getGroup(groupname);

What would be the Java-backed equivalent of this code?

So far I can only get a set of all group names, but I would like to be able to iterate through the set and get the actual group node.

//Gets all groups, but only as a set of groupnames
Set<String> groups = new HashSet<String>();
groups.addAll(authorityService.getAllAuthorities(AuthorityType.GROUP));
for (String groupname : groups) {
  //jscript equivalent - var group = People.getGroup(groupname);
}
From stackoverflow
  • You can use the org.alfresco.repo.security.authority.AuthorityDAO getAuthorityNodeRefOrNull method to get a group node by the name.

    Unfortunately the AuthorityDAO doesn't provide a method to get all group node, but if you look at the code of it's implementation org.alfresco.repo.security.authority.AuthorityDAOImpl you'll be able to easily copy the code that does it, it's not very complex.

    Snowright : Thanks for the reply. Unfortunately I was pressed for time and ended up using the javascript webscript equivalent for this particular component. If I have some time, I probably will try it out in java again. As a beginner, its hard to find my way around the api sometimes due to the lackluster documentation. Thanks for pointing me in the right direction!
    Hugo Palma : That's true, it's not easy to find this kind of stuff in the Alfresco API. What i usually do is search on the Alfresco source code for what i want. That's how i found about the AuthorityDAO.

Session object using ServletContext

Is there any way to get an object which will be there throughout the session from ServletContext object??

From stackoverflow
  • No, it's not possible to get the session from the ServletContext.The point of the ServletContext is to get application scope attributes rather than session scope.

Can you tell me why this generates time limit exceeded in spoj(Prime Number Generator)

#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;    

bool prime[1000000500];
void generate(long long end)
{
    memset(prime,true,sizeof(prime));
    prime[0]=false;
    prime[1]=false;

        for(long long i=0;i<=sqrt(end);i++)
        {
         if(prime[i]==true)
         {
             for(long long y=i*i;y<=end;y+=i)
             {
                 prime[y]=false;
             }
         }
        }
}

int main()
{
    int n;
    long long b,e;
    scanf("%d",&n);
    while(n--)
    {
        cin>>b>>e;
        generate(e);
        for(int i=b;i<e;i++)
        {
            if(prime[i])
                printf("%d\n",i);
        }
    }
    return 0;
}

That's my code for spoj prime generator.
Altought it generates the same output as another accepted code ..

From stackoverflow
  • Because it took too long.

  • You need to make it faster - for test cases such as the range 999900000-1000000000, Eratosthene's sieve algorithm is too slow. There are other alternatives you could try and will yield better results.

    PS. Of course I won't tell you which these are. Do your homework. :P

    magiix : Well i didn't post thsi question until i am so desperate about it ... so if you know how i can optimize it ? Please tell.
    Michael Foukarakis : There are a number of primality tests that can be adapted for your purpose (see Miller-Rabin, Agrawal & Biswas, Bernstein in "Proving primality in essentially quartic random time") as well as other approaches in prime number generation (Sieve of Atkin). I'm sure there are others as well, as it's a relatively 'hot' research topic.
    nakedfanatic : Eratosthene's sieve algorithm is not too slow. A modified version that operates only on the test range and not on the entire range from 0 to 1000000000 will do fine.
    Michael Foukarakis : @nakedfanatic: You mean, a segmented Eratosthene's sieve is not too slow. It's not the same with the traditional sieve algorithm, and it certainly isn't as easy to implement. I was going to avoid mentioning it, but w/e. :)
    nakedfanatic : @Michael Foukarakis, True, I leaned heavily on Python's extended slice notation. I expect it would be more painful to implement in C++.
  • An easy trick to make it faster is to lift out sqrt from the for loop:

    double sqrtOfEnd = sqrt(end);
    for(long long i=0; i<=sqrtOfEnd; i++)
    {
      ...
    

    You don't need to recalculate the square root on every loop.
    As pointed out by others this might not be enough and you might have to concider other methods of finding primes.

  • Since you need to output primes from a number of sequences, may-be keep around the results from previous sievings and only continue to fill in the rest of the table as needed?

    nakedfanatic : That's a lot of numbers to store. Calculating the primes isn't a problem, but storing them might be.
  • You don't need to sieve every number up to the end number. That's just silly. Only operate on the range between beginning and end numbers. (A partial sieve)

    I've solved this problem in Python and that was the way I finally managed to do it. I also started by calculating all of the primes up to the square root of the potential maximum, 1000000000. This is only 31623 so it doesn't take long.

    From this list use those numbers up to the square root of the current case maximum to sieve the current case.

is there a way to view the source of a module from within the python console?

if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source?

From stackoverflow
  • Maybe

    print open('mymodule.py').read()
    

    ?

    See file.read().

    Kugel : this dumps the content of any file.
  • Some of the methods of inspect module are well-suited for this purpose:

    import module
    import inspect
    src = inspect.getsource(module)
    
  • Using IPython, you can do this:

    In [1]: import pyparsing
    In [2]: pyparsing.Word??
    

    ...and the source will be displayed, if possible. I guess this must use inspect under the hood, but the added convenience of ? / ?? is fantastic.

    Alok : Yeah, I use `?` and `??` all the time in IPython myself.

Core Data and NSTableView show content as title

I'm working on a menubar note-taking app with Simplenote syncing support, and it's been using a separate title and content for each note. It shows the title in an NSTableView and the content in an NSTextView, but now I would like for it to show the content as the title in the table view like in Simplenote. My problem is that I would like for it to show the title only up until it reaches a newline, but I don't know how to do it.

From stackoverflow
  • Simplest way is to break apart the string using -componentsSeparatedByString: and pass in \n which will return an array with the components broken apart. Then grab the zeroth element from the array.

    Marcus S. Zarra : Note that you are not going to be able to do this in IB so I would suggest writing a convenience method in the `NSManagedObject` subclass to handle this and return the zeroth element. It will make your table bindings **much** easier.
    ausgat : So, I have to subclass NSManagedObject? I'm still pretty new to Core Data, bindings, etc.
    ausgat : Nevermind, I got everything working. Thanks. :)

How to programmatically set JAX-WS 2.1 JMS client timeout in WebSphere 7?

I'm converting a JAX-RPC client and service to JAX-WS, and am trying to figure out how to set the client timeout programmatically. This will be a JAX-WS 2.1 client running in WebSphere 7. In JAX-RPC, there was a property I could set on the SOAPBindingStub to set the timeout.

In the JAX-WS code, I've tried setting several properties as follows, with no luck:

PolicyFinderService policyFinderService = new PolicyFinderService();
PolicyFinder policyFinder = policyFinderService.getPolicyFinderSOAPPort();
((BindingProvider)policyFinder).getRequestContext().put(com.ibm.wsspi.websvcs.Constants.REQUEST_TIMEOUT_PROPERTY, 1);
((BindingProvider)policyFinder).getRequestContext().put(com.ibm.wsspi.websvcs.Constants.WRITE_TIMEOUT_PROPERTY, 1);
((BindingProvider)policyFinder).getRequestContext().put(com.ibm.wsspi.webservices.Constants.READ_TIMEOUT_PROPERTY, 1);
((BindingProvider)policyFinder).getRequestContext().put(com.ibm.wsspi.webservices.Constants.RESPONSE_TIMEOUT_PROPERTY, 1);
((BindingProvider)policyFinder).getRequestContext().put(com.ibm.wsspi.webservices.Constants.WRITE_TIMEOUT_PROPERTY, 1);

None of these have any effect when I make a call and the service isn't running, it just hangs for the default timeout value (I think 5 minutes) before timing out.

Has anyone found a way to programatically set this timeout value in WebSphere 7?

From stackoverflow
  • its possible you might need to

    ((BindingProvider)policyFinder).getRequestContext().put(
      com.ibm.wsspi.webservices.Constants.CONNECTION_TIMEOUT_PROPERTY, 2000);
    

    it might do that before the write...possibly

    perhaps this also?

    reqCtx.put(JAXWSProperties.CONNECT_TIMEOUT, 10); 
    reqCtx.put(BindingProviderProperties.REQUEST_TIMEOUT, 10);
    

    possibly REQUEST_TIMEOUT_PROPERTY may actually be in milliseconds, so maybe a low val of 1 gets rounded somehow to 0 (infinite) later on... maybe try 2000?

    Kaleb Brasee : Thanks, I'll give those both a try.
    Kaleb Brasee : It was the com.ibm.wsspi.webservices.Constants.CONNECTION_TIMEOUT_PROPERTY! The current configuration is having trouble making the connection, so it never even gets to the other timeouts -- hence the connection timeout is needed. Only thing is, it's in seconds, not milliseconds (I used a value of 10). But still, this is exactly what I was looking for. Thanks!

How do I compute the capacity of a hard disk?

I have a worked example of how to compute the capacity of a hard disk, could anyone explain where the BOLD figures came out of?

RPM: 7200

no of sectors: 400

no of platters: 6

no of heads: 12

cylinders: 17000

avg seek time: 10millisecs

time to move between adj cylinders: 1millisec

the first line of the answer given to me is:

12 x 17 x 4 x 512 x 10^5

I just want to know where the parts in bold came from.The 512 I dont know. The 10 is from the seek time but its power 5?

From stackoverflow
  • The answer is

    heads x cylinder x sectors x 512 (typical size of one sector in bytes)
    

    so this is

    12 x 17000 x 400 x 512
    

    which is the same as

    12 x 17 x 1000 x 4 x 100 x 512
    

    and

    100 = 10^2
    1000 = 10^3
    10^2 x 10^3 = 10^5
    

    As you want the capacity, you don't need any times here.

    A reference for the 512 bytes can be found at Wikipedia, for example (and it also has a similar example with the same formula a bit below).

    BlueRaja - Danny Pflughoeft : beat me to it :)
    schnaader : Was pretty lucky that I saw the question almost as it appeared - I'll wait a bit on the next one so you can take it ;)
    Andrew : +1 with caveat, I think heads should really be the platters x 2 - although normally you would expect 1 head per side of a platter it isn't guarenteed.
    schnaader : See the Wikpedia link: "Naturally, a platter has 2 sides and thus 2 surfaces on which data could be manipulated; usually there are 2 heads per platter--one on each side, but not always." So I guess we can assume that and as the number of heads is given, I chose to use that one.
    schnaader : But of course you're right that it's still an assumption, as well as the sector size of 512 bytes which will perhaps change to 4096 bytes in the near future.

can spring support multi applications sharing membership?

Does the spring framework support multi applications sharing a common user base?

e.g. 2 separate web applications somehow hook into a single database to get user related information (username, password, and maybe even roles)

The idea is this, something similiar to asp.net membership

it works like this, you can have 10 websites, all pulling their membership API from the same datasource. Security (roles) and site mappings are all peformed via this membership API.

Usually what happens is you release a application. Then you release another application, and then your clients ask if you can merge the users etc. The asp.net membership solves this problem from the get-go.

update

I am not asking for single-sign on in the sense that you can go to any website by just logging in once. But rather you have the same login credentials that can be used on all sites.

From stackoverflow
  • A single database can be accessed by multiple applications, including Spring applications. Just provide access to this database to each applications, typically through a datasource (and yes, a Java application can use several datasources).

    [EDIT] The intent of the OP is actually not clear. According to some comments, it seems that the question might be about SSO. In that case, I'd suggest to have a look at Spring Security, or a CAS implementation like JA-SIG CAS, or Spring Security with CAS.

    PS: I don't mean to be rude but you should learn How To Ask Questions The Smart Way. For example here, you should expose your goal instead of asking for a specific solution (see Describe the goal, not the step). First, readers can't guess what you don't tell them and it is very frustrating (even if I'm happy to help). Second, you'll get much better answers (and avoid frustration on both sides). Seriously, read that paper, it's really worth it.

    delfuego : +1000 for the recommendation to learn how to ask questions. mrblah has been asking nearly (or more than) 20 questions a day, usually without sufficient information for someone to know what he's asking, and rarely follows up with clarification -- I'm totally unclear why people continue to play along with his game.
    mrblah : @pascal thanks for the suggestion, and for @delfuego http://j.mp/1QGRZO
    delfuego : @mrblah, as you'll read in Pascal's link about asking questions, I'm not looking to be your friend, I'm looking for you to respect the time of people here by doing some work on your own before asking questions, and then by doing us the favor of asking questions in a way where people know what you're asking, know what you've tried, and know what your actual question is. It's not really all that hard, and it's certainly the better way to get help when you need it.
  • Yes ... sort of. Take a look at SpringSecurity.

    I say "sort of" because Spring currently does not offer an off-the-shelf solution to the problem of user account management. You have the choice of hooking into an existing solution (e.g. LDAP) or rolling your own "user details service" and tools for account management.

    Also, SpringSecurity doesn't yet (AFAIK) have a true "single-sign-on" solution.

    But certainly, once you have implemented a SpringSecurity based solution to authentication / access control, it should be easy to apply it across multiple websites, with a unified user account-base ... or not.

    EDIT in response to comments, when I say that SpringSecurity + LDAP is not an off-the-shelf solution to user account management, I mean that it is not something (like the OP) can simply add to his Spring-based webapps and deploy in Tomcat / whatever. Instead, he would have to

    1. research how LDAP works,
    2. select and LDAP implementation,
    3. install an LDAP implementation,
    4. configure and tailor LDAP as required,
    5. integrate with SpringSecurity,
    6. figure out to implement extensions to his web-apps so that remote users can self register, change their passwords, change their profiles, etcetera.

    To my mind SpringSecurity + LDAP is a good solution if you already have a corporate LDAP setup (or if you have extensive LDAP expertise), but it is not a good match to the OP's requirement for a simple solution.

    delfuego : I'm confused -- why is Spring Security's support of LDAP **not** an off-the-shelf solution to user account management? That being said, the question is a lot more basic than this; the OP seems to be asking whether or not two Java applications can use the same database, which is sort of baffling.
    mrblah : delfeugo, no that is not what I am asking. I was hoping spring has something similiar to the asp.net membership. multiple apps can share the same userbase, have different roles setup for each site, etc.
    delfuego : And as I asked above, I'm still unclear what you're looking for -- single sign-on? authentication backed by a single set of users? I really, really think you need to spend time with Pascal's "How To Ask Questions The Smart Way" link -- this whole thing is a muddled mess.
    Stephen C : @delfuego - I assume you are talking to the OP in your last comment.
  • Sure you can. Look at Terracota with Spring. It allows the use of distributed cache. i.e. you can write to a hashmap and it gets transparently replicated to a hashmap on another instance of JVM(i.e. application).

    http://www.springsource.org/node/279

    also google "cluster spring".

    You can put anything into a data structure: user info, roles, etc. It also you give you a nice little clustering solution where you can easily load balance sessions between multiple instances of an application.

serializing a datatable for later reuse

Hi everyone,

I have a populated DataTable I'd like to serialize to a file for later use. I've been looking over the options involved with this and wondered if someone could point me in the right direction.

What I'll be creating are two methods-- one for writing the datatable to a file, and another for creating a new datatable using the file as input. Does it make sense to use the WriteXML() and Load() methods to do this, and if so, which flag(s) are ones to focus on? Thanks for the guidance.

I'm using .Net 2.0 if that helps.

From stackoverflow
  • You might use the basic technique of serializing your database into CSV files with headers. Some database management systems support easy loading of data from such files. And in case your dbms doesn't it wouldn't be too difficult to write some code that'd do this for you. Does that answer your question?

    In my opinion the disadvantage of xml is that it contains possibly more meta-data than actual data. In case of csv files meta-data is not repeated.

  • I would go for the read/write xml methods. We use that pretty extensively. It's quick, it's easy, it's built into the framework.

  • Is the datatable an object in memory? If so, you could simply go with Serialize and Deserialize Methods. They are relatively quickly and you can persist the result anywhere you want.

    John Saunders : Which `Serialize` and `Deserialize` methods are you referring to?
    Wagner Silveira : You can use the methods within System.Xml.Serialization.XmlSerializer class. I'm at a client now, but when I have some time, I will try to get the examples I have. They are quite simple to use.
    larryq : Hi, Yes, the DataTable is in memory. I'd be interested in seeing you code snippet, as right now I'm using ReadXml() and WriteXml(). Thanks!
  • I think Silveira comment mean use of binary serialization. And its right that it very fast compare to XML which serialization is very slow compare to binary specially for large amount of data. Also it take a lot less space on disk compare to XML.

        public static void Serialize(DataSet ds, Stream stream) {
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(stream, ds);
        }
    
        public static DataSet Deserialize(Stream stream) {
            BinaryFormatter serializer = new BinaryFormatter();
            return (DataSet)serializer.Deserialize(stream);
        } 
    
    affan : One of shortfall in using binary serialization is that the binary serialization contain assembly qualified name of type been serialized so if System.Data.dll changes you will unable to read the data from binary file. But since DataSet and other classes in name space is part of framework and not like to change therefore i donot see any problem in this case.
    Wagner Silveira : I usually had only to serialize small amounts of data, so XMLSerializer was fine. But the bottom line here is that we all seem to agree that Serialization is a good way forward. The right formatter (XML, Binary, DataContract), can be chosen depending on other requirements (e.g. if you only have to read the data within your app, and don't need to export it to other environment, Binary seems the perfect choice).
    larryq : Thanks for the tip, Affan

How to create an empty file at the command line?

How to create an empty file at the DOS/Windows command-line?

I tried:

copy nul > file.txt

but it always displays that a file was copied.

Is there any other method in the standard cmd?

It should be a method that does not require the touch command from Cygwin or any other nonstandard commands. The command needs to run from a script so keystrokes cannot be used.

From stackoverflow
  • echo "" > filename
    

    I believe this works on Windows/DOS, but my last hands-on experience with either is quite a while ago. I do know for a fact that it works on basically any POSIX compliant OS.

    Kris : Apperantly, VonC's answer is better than mine, so please upvote that instead.
    Grendler : Unfortunately: echo "" displays double quotes and they are written to the file when stream is redirected to it. The same happens with just: echo > filename because it writes ECHO is off/on to the file as well.
    Kris : maybe you could put "@echo off" on the line before creating the file to circumvent that?
  • I'm using curly { } brackets for enter and Ctrl+Z keyboard

    copy con SomeFile.txt {enter}

    {Ctrl+Z} {enter}

    Grendler : I precised the question that the command will run from script so unfortunately any keyboard interaction does not work. Thank you anyway.
  • echo.>filename
    

    (echo "" would actually put "" in the file! And echo without the '.' would put "Command ECHO activated" in the file...)

    Note: the resulting file is not empty but includes a return line sequence: 2 bytes.


    This discussion points to a true batch solution for a real empty file:

     <nul (set/p z=) >filename
    
     dir filename
     11/09/2009  19:45                 0 filename
     1 file(s)                         0 bytes
    

    The "<nul" pipes a nul response to the set/p command, which will cause the variable used to remain unchanged. As usual with set/p, the string to the right of the equal sign is displayed as a prompt with no CRLF.

    Since here the "string to the right of the equal sign" is empty... the result is an empty file.


    The difference with cd. > filename (which is mentioned in Patrick Cuff's answer and does also produce a 0-byte-length file) is that this "bit of redirection" (the <nul... trick) can be used to echo lines without any CR:

    <nul (set/p z=hello) >out.txt
    <nul (set/p z= world!) >>out.txt
    dir out.txt
    

    The dir command should indicate the file size as 12 bytes: "hello world!".

    Agent_9191 : you'd actually want `echo.>filename` because it will include the space as well as the newline character.
    Greg Hewgill : Using the `rem` command avoids creating a file with an empty line in it.
    VonC : @Agent_9191: true, I have updated my answer. @Greg: not sure what you mean: `rem>filename` produces the same result (2 bytes)
    Greg Hewgill : I recall the `rem` trick worked in the past (maybe only DOS?), but apparently not today!
    Grendler : @VonC filename trick works exactly as I needed. Thanks :-)
    Noufal Ibrahim : +1 but one can see why scripting with DOS is not popular. :)
    Joey : Noufal Ibrahim: don't let this fool you; just see the next answer which has a much easier and equally working solution. What's done here is partially wrong in the first case (not empty but contains a line break) and way overcomplicated in the second one.
  • You can write your own touch.

    //touch.cpp
    #include <fstream>
    #include <iostream>
    
    int main(int argc, char ** argv;)
    {
      if(argc !=2)
      {
        std::cerr << "Must supply a filename as argument" << endl;
        return 1;
      }
      std::ofstream foo(argv[1]);
      foo.close();
      return 0;
    }
    
  • Reading comments on my post, I have to admit I didn't read the question right.

    On the Windows command-line, one way would be to use fsutil:

    fsutil file createnew <filename> <size>
    

    An example:

    fsutil file createnew myEmptyFile.txt 0
    

    Below is for *nix command-line.

    touch filename
    

    This command changes your modified date of a file or creates it if file is not found.

    qid : Unfortunately, the question specifically states, "Without the touch command from Cygwin."
    Greg Hewgill : There exist non-Cygwin implementations of the touch command: http://unxutils.sourceforge.net/ is good.
    Frank Farmer : In *nix, I'm personally partial to a simple `> filename`, which can also be used to truncate an existing file.
    Joey : `fsutil` needs administrative privileges. That's a bit much to ask for simply creating an empty file ...
  • If you really want a totally empty file, without any output to stdout, you can cheat a little:

    copy nul file.txt > nul
    

    Just redirect stdout to nul, and the output from copy disappears.

    Grendler : It fails if the file.txt exists.
    wallyk : Failing if the file exists is good behavior as I understand the question.
    Joey : +1. It's amazing how the accepted answer is something half-wrong and half convoluted while the obviously correct one gets nearly no credit. To add to this: `type nul>file` would be another way.
  • Here's another way:

    cd. > filename
    
    VonC : It seems to work as well. +1
  • You could also use

    echo. 2>foo

    The debug output for echo. will almost definitely be empty :)

    HTH, -Craig