Friday, April 29, 2011

how to get stronly typed local resource file ?

i really love the idea of it as i can create a folder for my user control, and make sub folder images, css, and put local resource file, so the whole thing is contained in one folder, and that makes it really efficient for me (management wise). but the bugger is you cant get intellisence like global resource, so is it possible in any way ?

From stackoverflow
  • AFAIK: ASP.NET and Visual Studio in their standard configuration can only do this for global resources.

strict aliasing

in C, what exactly are the performance benefits that come with observing strict aliasing?

From stackoverflow
  • Basically the compile can optimize more aggressively with strict aliasing... see this article for more detail: http://www.cellperformance.com/mike_acton/2006/06/understanding_strict_aliasing.html

  • There is a page that describes aliasing very thoroughly here.

    There are also some SO topics here and here.

    To summarize, the compiler cannot assume the value of data when two pointers of different types are accessing the same location (i.e. it must read the value every time and therefore cannot make optimizations).

    This only occurs when strict aliasing is not being enforced. Strict aliasing options:

    • gcc: -fstrict-aliasing [default] and -fno-strict-aliasing
    • msvc: Strict aliasing is off by default. (If somebody knows how to turn it on, please say so.)


    Example

    Copy-paste this code into main.c:

    void f(unsigned u)
    {
        unsigned short* const bad = (unsigned short*)&u;
    } 
    
    int main(void)
    {
        f(5);
    
        return 0;
    }
    

    Then compile the code with these options:

    gcc main.c -Wall -O2

    And you will get:

    main.c:3: warning: dereferencing type-punned pointer will break strict-aliasing rules

    Disable aliasing with:

    gcc main.c -fno-strict-aliasing -Wall -O2

    And the warning goes away. (Or just take out -Wall but...don't compile without it)

    Try as I might I could not get MSVC to give me a warning.

    j_random_hacker : +1, but please make it clear that the compiler cannot make that assumption when strict aliasing is *not* observed.
    j_random_hacker : Perfect! :) Unfortunate that MSVC++ doesn't seem to have an option for strict aliasing. It does have __restrict and __declspec(restrict) though, which can be used in individual cases.
    tialaramex : Looks like a typo “-fno-strict-aliasing [default] and -fno-strict-aliasing” I'm guessing the default is actually -fstrict-aliasing (at least in modern GCC) rather than -fno-strict-aliasing, but in any case one of the two GCC options listed should be -fstrict-aliasing, and right now they both say -fno-strict-aliasing.
    GMan : Ha, nice catch, I'm surprised nobody saw that until now.

How can I direct log4j output so that different log levels go to different appenders?

Is it possible to have "debug" and "info" output written to the console while the "info" output is only written to some log file? For example, given this logging:

LOG.debug(fileContent);
LOG.info(fileLength);

What does a corresponding log4j.xml look like?

From stackoverflow
  • That is definitely possible. The configuration would look something like this (not checked for syntactic correctness):

    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <appender name="console" class="org.apache.log4j.ConsoleAppender">
            ...
        </appender>
    
        <appender name="otherAppender"
                  class="org.apache.log4j.FileAppender FileAppender">
            ...
        </appender>
    
        <logger name="com.mycompany.mypackage.MyClass">
            <level        value="info"/>
            <appender-ref ref="otherAppender" />
        </logger>
    
        <root>
            <priority     value="debug" />
            <appender-ref ref="console" />
        </root>
    </log4j:configuration>
    

    All debug and info messages go to the console appender. Info messages go to otherAppender.

    Eddie : +1, I would have answered this but you beat me to it.
    Eddie : I made some small edits to your answer. hope this is OK.
    Ronald Wildenberg : That's ok :) Thanks!
  • Go to this page for some examples.

    It's as simple as adding two different appenders to your program, one appender for each type of logging you want to do.

  • With the configuration from Eddie I can only get the "info" output for MyClass. But what I would like to have is that the "info" output of MyClass goes to a file AND the "debug" output of MyClass goes to console.

  • Do as rwwilden suggested but remove this part

    <logger name="com.mycompany.mypackage.MyClass">

    <level value="info"/>

    <appender-ref ref="otherAppender" />

    </logger>

    Add <param name="Threshold" value="INFO"/> under the otherAppender.

  • Ok, I've got it now:

    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <appender name="console" class="org.apache.log4j.ConsoleAppender">
            ...
        </appender>
    
        <appender name="otherAppender"
                  class="org.apache.log4j.FileAppender FileAppender">
           <param name="Threshold" value="INFO"/>
            ...
        </appender>
    
        <root>
            <priority     value="debug" />
            <appender-ref ref="console" />
            <appender-ref ref="otherAppender" />
        </root>
    </log4j:configuration>
    

    Thanks for your help!

uses of sessions & cookies?

what is use of sessions & cookies in servlets?

From stackoverflow

ASP.Net Media Suite - Review

Does anyone have a review of ASP.Net Media Suite located on

http://www.aspnetmedia.com/

The tool seems pretty nice, but i've never heard of the company. I'm hesitant to purchase and install something from an unknown source.

Can anyone vouch for the product?

From stackoverflow
  • well, i have sent many emails, and never got an answer, if you ask me you are better with many other alternatives, like there is an a amazing flash control i use http://www.flash-control.net/

    it does everything to implement flash like XHTML valid inclusion, Option to install flash if not available, Flash Vars, etc...

    then you can choose of millions of flash mp3 players, video players on net which use XML, then simply you create the XML in code and hook any special Flashvars with this control and you have a great media player. here is a nice site i always got to for such stuff

    www.flashden.net.

    hope this helps.

How do I apply a shell command to many files in nested (and poorly escaped) subdirectories?

Hi! I'm trying to do something like the following:

for file in `find . *.foo`
do
somecommand $file
done

But the command isn't working because $file is very odd. Because my directory tree has crappy file names (including spaces), I need to escape the find command. But none of the obvious escapes seem to work: -ls gives me the space-delimited filename fragments -fprint doesn't do any better.

I also tried: for file in "find . *.foo -ls"; do echo $file; done - but that gives all of the responses from find in one long line.

Any hints? I'm happy for any workaround, but am frustrated that I can't figure this out.

Thanks, Alex

(Hi Matt!)

From stackoverflow
  • Instead of relying on the shell to do that work, rely on find to do it:

    find . -name "*.foo" -exec somecommand "{}" \;
    

    Then the file name will be properly escaped, and never interpreted by the shell.

    dfa : for GNU find, -exec somecommand {} + is better
  • xargs is your friend. You will also want to investigate the -0 (zero) option with it. find (with -print0) will help to produce the list. The Wikipedia page has some good examples.

    Another useful reason to use xargs, is that if you have many files (dozens or more), xargs will split them up into individual calls to whatever xargs is then called upon to run (in the first wikipedia example, rm)

    Steve Jessop : "xargs will split them up into individual calls". Or if this isn't desirable, as happens in rare cases, then use "-n1 -r" to get the same behaviour as the for loop. -r is a GNU extension, -n is POSIX.
    Alister Bulman : +1 for the tip, onebyone
    lhunath : -1 because xargs is broken unless used with the -0 option and using the -0 option with find is pretty silly seeing as find itself has a -exec {} + predicate that does exactly the same thing.
    Alister Bulman : '-0 |xargs' is easier to remember than escaping the call to '-exec {}' however, which can get complicated.
  • find . -name '*.foo' -print0 | xargs -0 -n 1 somecommand
    

    It does get messy if you need to run a number of shell commands on each item, though.

    Steve Jessop : Actually, you need -r (and hence GNU find or similar) to exactly emulate the for loop. xargs will otherwise execute the command with no arguments if the input is 0-length.
    lhunath : or you could use find's -exec {} + to avoid the convolution: find . -name '*.foo' -exec somecommand {} \;
  • find . -name '*.foo' -print0 | xargs -0 sh -c 'for F in "${@}"; do ...; done' "${0}"
    
  • You have plenty of answers that explain well how to do it; but for the sake of completion I'll repeat and add to it:

    xargs is only ever useful for interactive use (when you know all your filenames are plain - no spaces or quotes) or when used with the -0 option. Otherwise, it'll break everything.

    find is a very useful tool; put using it to pipe filenames into xargs (even with -0) is rather convoluted as find can do it all itself with either -exec command {} \; or -exec command {} + depending on what you want:

    find /path -name 'pattern' -exec somecommand {} \;
    find /path -name 'pattern' -exec somecommand {} +
    

    The former runs somecommand with one argument for each file recursively in /path that matches pattern.

    The latter runs somecommand with as many arguments as fit on the command line at once for files recursively in /path that match pattern.

    Which one to use depends on somecommand. If it can take multiple filename arguments (like rm, grep, etc.) then the latter option is faster (since you run somecommand far less often). If somecommand takes only one argument then you need the former solution. So look at somecommand's man page.

    More on find: http://mywiki.wooledge.org/UsingFind

    In bash, for is a statement that iterates over arguments. If you do something like this:

    for foo in "$bar"
    

    you're giving for one argument to iterate over (note the quotes!). If you do something like this:

    for foo in $bar
    

    you're asking bash to take the contents of bar and tear it apart wherever there are spaces, tabs or newlines (technically, whatever characters are in IFS) and use the pieces of that operation as arguments to for. That is NOT filenames. Assuming that the result of a tearing long string that contains filenames apart wherever there is whitespace yields in a pile of filenames is just wrong. As you have just noticed.

    The answer is: Don't use for, it's obviously the wrong tool. The above find commands all assume that somecommand is an executable in PATH. If it's a bash statement, you'll need this construct instead (iterates over find's output, like you tried, but safely):

    while read -r -d ''; do
        somebashstatement "$REPLY"
    done < <(find /path -name 'pattern' -print0)
    

    This uses a while-read loop that reads parts of the string find outputs until it reaches a NULL byte (which is what -print0 uses to separate the filenames). Since NULL bytes can't be part of filenames (unlike spaces, tabs and newlines) this is a safe operation.

    If you don't need somebashstatement to be part of your script (eg. it doesn't change the script environment by keeping a counter or setting a variable or some such) then you can still use find's -exec to run your bash statement:

    find /path -name 'pattern' -exec bash -c 'somebashstatement "$1"' -- {} \;
    find /path -name 'pattern' -exec bash -c 'for file; do somebashstatement "$file"; done' -- {} +
    

    Here, the -exec executes a bash command with three or more arguments.

    1. The bash statement to execute.
    2. A --. bash will put this in $0, you can put anything you like here, really.
    3. Your filename or filenames (depending on whether you used {} \; or {} + respectively). The filename(s) end(s) up in $1 (and $2, $3, ... if there's more than one, of course).

    The bash statement in the first find command here runs somebashstatement with the filename as argument.

    The bash statement in the second find command here runs a for(!) loop that iterates over each positional parameter (that's what the reduced for syntax - for foo; do - does) and runs a somebashstatement with the filename as argument. The difference here between the very first find statement I showed with -exec {} + is that we run only one bash process for lots of filenames but still one somebashstatement for each of those filenames.

    All this is also well explained in the UsingFind page linked above.

  • I had to do something similar some time ago, renaming files to allow them to live in Win32 environments:

    #!/bin/bash
    IFS=$'\n'
    function RecurseDirs
    {
    for f in "$@"
    do
      newf=echo "${f}" | sed -e 's/[\\/:\*\?#"\|<>]/_/g'
      if [ ${newf} != ${f} ]; then
        echo "${f}" "${newf}"
        mv "${f}" "${newf}"
        f="${newf}"
      fi
      if [[ -d "${f}" ]]; then
        cd "${f}"
        RecurseDirs $(ls -1 ".")
      fi
    done
    cd ..
    }
    RecurseDirs .
    

    This is probably a little simplistic, doesn't avoid name collisions, and I'm sure it could be done better -- but this does remove the need to use basename on the find results (in my case) before performing my sed replacement.

    I might ask, what are you doing to the found files, exactly?

2nd call to Device.Reset in DirectX throws an InvalidCallException

I've been working on a DirectX application in C#, and I noticed that when I lock the workstation, the DirectX "Device" becomes lost. After looking up the information about what to do upon when a device is lost (and when a DeviceLostException is thrown by Device.Present), I re-wrote the code to reset the Device. This simply meant that I made a call to Device.Reset.

Calling Device.Reset recovered the Device. No problem. But when I lost the device a second time (for example, when the computer was locked, went to sleep, or activated a screen-saver), an exception was thrown by Device.Reset.

The exception was InvalidCallException, which (according to the documentation) means something went wrong with the call. So I assumed it was a problem with the arguments to the function. So instead of passing the same copy of PresentParams that I used to create the Device, I created a new instance of PresentParams (at first using the copy constructor, and later by re-creating without it) and passed that to Device.Reset.

Doesn't work. Device.Reset still dies with the InvalidCallException. Oh, and the message of the exception? "Error in application." Not helpful.

Can you point me in the direction of either a solution, or some documentation about how to get more debug information out of DirectX?

From stackoverflow
  • OK, I know how silly is seems to answer my own question, but I figured someone else might need this, eh?

    The answer is: there were too many calls to the Dispose method of the VertexBuffers in the scene. The reason being that the internal Device reset-handlers were calling the Dispose method. And why was that happening? Because I had neglected to read the .NET DirectX SDK documentation regarding the Pool Enumeration, and was allocating the VertexBuffers using Pool.Default instead of Pool.Managed.

    So obviously, after a few thousand badly done allocate-and-release cycles, something went wrong.

    Oh, and how did I discover this? I attached a listener to VertexBuffer.Dispose which incremented a counter that I displayed on-screen. Imagine my suprise when I noticed this counter kept growing as I resized the window!

  • Thanks a lot for the answer :) It really helped me and saved hours of my time. Thanks again

    scraimer : I'm glad I could help! :-)

Prepending and animating text loaded via AJAX with jQuery.

Old hand with Prototype, new to jQuery, and writing a simple app to get a feel for the framework (and because I want to use it). I've got an HTML fragment that I load via AJAX, and I want to stick this at the top of a div, with a slide-in transition animation.

This bit works, and does the prepending bit:

// Get the HTML fragment and stick it at the top of the containing div.
$.post("/create_new_thing", function(data) {
    $('#container_div').prepend(data);
});

What I'd like to do, and can't figure out, is animate the newly added HTML fragment with a show() effect.

Any suggestions?

From stackoverflow
  • Try something like this...

    $('#div').load('file.html').fadeIn("slow");
    

    The load function is better suited to your needs, as it's main purpose is to load HTML from a remote file and inject it into the DOM.

    Using the "post" function is better for loading a remote page using a POST request (posting data via a form and returning dynamic data based on your post request).

    See below...

    $.post("file.php", { name: "superuntitled", time: "2am" },
    function(data){
      $('#div').fadeIn("slow").append(data);
    });
    

    jQuery has no support yet for "PUT" requests. So if you really need to use a put request, I can recommend extending the jQuery functionality with a custom function that adds support for "PUT". That said, there are some work arounds! See here for more details! ... http://homework.nwsnet.de/news/9132_put-and-delete-with-jquery

    Don Werve : I'll give this a go, but I can see cases where I'll want to do this via a POST request -- I just didn't put any parameters in my example because I want to keep it simple. Thanks, though!
    Don Werve : Whoops, not POST, PUT.
    superUntitled : i am not sure what "PUT" is?
    moff : @superUntitled: you may read about the put request over at w3c: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6
    superUntitled : jQuery has no support yet for "PUT" requests. So if you really need to use a put request, I can recommend extending the jQuery functionality with a custom function that adds support for "PUT". See here for more details! http://homework.nwsnet.de/news/9132_put-and-delete-with-jquery

How do I write Ax ( P(x) and Q(x) ) in Coq?

I'm trying out Coq, but I'm not completely sure what I'm doing. Is:

Theorem new_theorem : forall x, P:Prop /\ Q:Prop

Equivalent to:

Ax ( P(x) and Q(x) )

(where A is supposed to be the universal quantifier).

Edit: I think they are.

From stackoverflow
  • Are you having problems with the syntax?

    $ coqtop
    Welcome to Coq 8.1pl3 (Dec. 2007)
    
    Coq < Section Test.
    
    Coq < Variable X:Set.
    X is assumed
    
    Coq < Variables P Q:X -> Prop.
    P is assumed
    Q is assumed
    
    Coq < Theorem forall_test: forall x:X, P(x) /\ Q(x).
    1 subgoal
    
      X : Set
      P : X -> Prop
      Q : X -> Prop
      ============================
       forall x : X, P x /\ Q x
    
    forall_test <
    
  • Well, to answer your question:

    Section test.
    
      Variable A : Type.           (* assume some universe A *)
      Variable P Q : A -> Prop.    (* and two predicates over A, P and Q *)
    
      Goal forall x, P x /\ Q x.   (* Ax, ( P(x) and Q(x) ) *)
    
    End test.
    

WYMeditor won't reflect contents into textarea value

I started deploying WYMeditor across all the content types on a site, and its looking good. Now I got to see how it works saving and viewing, but its not submitting anything and I have no idea why.

I've looked at this from several angles. I would even take a monkeypatch at this point, if I can learn how to grab the data myself I can stick it into the field at submission time. That or the real reason its not working by itself would be great. Anyone with an idea?

<li><label for="id_comment">comment on this article:</label> <textarea id="id_comment" rows="10" cols="40" name="comment"></textarea> 
<script type="text/javascript"> 
    $(document).ready(function(){

    jQuery("#id_comment").wymeditor({
      "toolsItems":[
         {
            "name":"Bold",
            "css":"wym_tools_strong",
            "title":"Strong"
         },
         {
            "name":"Italic",
            "css":"wym_tools_emphasis",
            "title":"Emphasis"
         },
         {
            "name":"InsertOrderedList",
            "css":"wym_tools_ordered_list",
            "title":"Ordered_List"
         },
         {
            "name":"InsertUnorderedList",
            "css":"wym_tools_unordered_list",
            "title":"Unordered_List"
         },
         {
            "name":"Indent",
            "css":"wym_tools_indent",
            "title":"Indent"
         },
         {
            "name":"Outdent",
            "css":"wym_tools_outdent",
            "title":"Outdent"
         },
         {
            "name":"Undo",
            "css":"wym_tools_undo",
            "title":"Undo"
         },
         {
            "name":"Redo",
            "css":"wym_tools_redo",
            "title":"Redo"
         },
         {
            "name":"CreateLink",
            "css":"wym_tools_link",
            "title":"Link"
         },
         {
            "name":"Unlink",
            "css":"wym_tools_unlink",
            "title":"Unlink"
         },
         {
            "name":"Paste",
            "css":"wym_tools_paste",
            "title":"Paste_From_Word"
         }
      ],
      "logoHtml":"",
      "updateEvent":"blur",
      "stylesheet":"/static/yui/tiny_mce.css",
      "skin":"twopanels",
      "classesHtml":"",
      "updateSelector":"textarea"
      });

    });
</script></li>
From stackoverflow
  • I had the same problem, and noticed from looking at example 1 in the wymexamples directory provided from their site that Wymeditor uses special element classes (CSS classes) to indicate the parts of the page which need to have extra behaviour added to them.

    In particular, the submit button has a class of wymupdate, and I think this causes a pre-submit handler to be associated with the control.

    Once I'd added the wymupdate class to the submit button in my source, then the textarea field was filled out with the HTML before the submission took place and it showed up server-side in the correct POST variable.

    I include below the relevant bits from the example source which make it work...

    <script type="text/javascript">
    jQuery(function() {
        jQuery('.wymeditor').wymeditor();
    });
    </script>
    

    ...

    <form method="post" action="">
    <textarea class="wymeditor">&lt;p&gt;Hello, World!&lt;/p&gt;</textarea>
    <input type="submit" class="wymupdate" />
    </form>
    

    ...although the wymupdate class association seems to be automagic, the wymeditor class association is triggered explicitly as shown in the <script>, and then this must cause it to look for things of class wymupdate.

    ironfroggy : Unfortunately this isn't the problem I was having. It was not an issue of the original textarea getting the right content when I submit (it does), but that when I enable the html-editing mode, which then shows both the raw-html textarea and WYMeditor's rich text editing field, editing one does not change the other.
    Alexey Zakharov : That's right, WYMeditor doesn't reflect changes back to textarea without wymupdate class.

Creating a PHP Webservice with binary-encoded parameters?

Hi,

I'm trying to build a PHP webservice for an iPhone project I'm developing. I need to be able to send an image (picture) to the webservice, where I'll then store this in a database. I also need to write a service that will, of course, return this data when requested.

I'm not sure where to start though. I've 'googled' for how I can build such a webservice but can find no good example of how this can be done. Does anyone have a code example or a url to a tutorial that might help?

Regards,

Jamie.

From stackoverflow
  • I don't know about the iPhone end of things, but the XML Schema Definition provides support for Base64 encoded data (and Hex encoded data) that will allow you to transport the image info over the Soap protocol.

  • What you need to do is create a form processing script on your webserver, that will receive a "POST" from the iphone client. A simple example of doing this is available at http://www.w3schools.com/PHP/php_file_upload.asp using purely PHP.

    However because you have the iphone as the client you might want to use the NSMutableURLRequest object to "POST" the image to the script that you have already setup on the server. You don't specify where the image is coming from, but you probably want to read this:

    http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/

  • As fret says, you need to build an HTTP POST request with the image data in a POST form.

    I highly recommend All Seeing eye's ASIHTTPRequest framework for building the form. Specifically you want to use the ASIFormDataRequest class. You can retrieve the binary information from a UIImage using (for example) NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality); and add this to the ASHFormDataRequest by sending an instance a -(void)setData:(NSData *)data forKey:(NSString *)key message

  • Wondeful - thanks guys. The zcentric.com tutorial was superb; helped me along my way tremendously.

    Regards,

    Jamie.

How do sites like Hubspot track inbound links?

Are all these types of sites just illegally scraping Google or another search engine?
As far as I can tell ther is no 'legal' way to get this data for a commercial site.. The Yahoo! api ( http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html ) is only for noncommercial use, Yahoo! Boss does not allow automated queries etc.
Any ideas?

From stackoverflow
  • For example, if you wanted to find all the links to Google's homepage, search for

    link:http://www.google.com
    

    So if you want to find all the inbound links, you can simply traverse your website's tree, and for each item it finds, build a URL. Then query Google for:

    link:URL
    

    And you'll get a collection of all the links that Google has from other websites into your website.

    As for the legality of such harvesting, I'm sure it's not-exactly-legal to make a profit from it, but that's never stopped anyone before, has it?

    (So I wouldn't bother wondering whether they did it or not. Just assume they do.)

How to reference ADO RecordSet object in C#?

I am using a COM DLL, a function call which returns an ADO RecordSet object and want to refer to it in my C# application.

Have added the reference, put the msado15,interop.adodb dll in the bin directory and debug directory, added assembly key in web.config but still get the following error:

The type 'ADODB.Recordset' is defined in an assembly that is not referenced. You must add a reference to assembly 'ADODB, Version=7.0.3300.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a'.

Any ideas on what is the right way to do this?

Edit:Which assembly do I add to GAC? Where can i find the ADODB.dll?

Added the reference to c:\program files\microsoft.net\primary interop assemlies\adodb.dll and got it working finally

From stackoverflow
  • The assembly should be in GAC as the name suggests (the name has publickeytoken in it).

    EDIT: The interop assembly for which the error is raised should be in GAC. OR remove the reference from your project and add the reference to the dll from the bin dir.

  • Try changing your reference to ADODB.dll in your project to 'Copy Local' true.

C++ Random Seed, Global Objects, and SDL_Threads

In my program, I have an object the global cpp file, that takes an integer as an argument.

//In global header
extern Object example;

//In global cpp file
Object example( (rand() % 6) );

I want a random number to be generated to the object's argument, but the seed does not reach the global variable, as the seed created in another cpp file, which is called later in the main.

My main problem is the random seed does not reach argument of the object in global.cpp, but I also put there for a specific reason, which involves threads.

My main question is: Can a random seed reach a global variable? if yes, please tell me how

(ALSO if yes, the next question is irrelevant)

But if it's not possible, this question regards to threads and the where to create the object. The object class calls a function in run thread, and calls a different function on another thread, such as the following:

//Thread A

int thread(void *data)
{
   example.showimage();

   return 0;
}

//ThreadB
int thread(void *data(
{
   example.moveimage();

   return 0;
}

I want this kind of functionality between the 2 threads, but is there a way to achieve this without creating the object in globals?

From stackoverflow
  • It sounds like you're using an approach that relys on order of initialization of statics (globals). You cannot depend on that order across compilation units (i.e. in different files). Statics in the same compilation unit are initialized in the order they are declared.

    For solutions, you might consider this:

    How do I prevent the "static initialization order fiasco"?

  • The best way to do this would be to use the singleton pattern (note that this example is NOT threadsafe):

    //in a header
    class RandomSeed
    {
    public:
        static RandomSeed& instance()
        {
            static RandomSeed the_instance;
            return the_instance;
        }
        int value() const {return value_;}
    private:
        RandomSeed() {/*initialization code*/}
        RandomSeed(const RandomSeed& rs); // disallowed
        RandomSeed& operator=(const RandomSeed& rs); // disallowed
        int value_;
    };
    
    // in your file
    #include "random_seed.h"
    srand(RandomSeed::instance().value());
    

    To implement thread safety, either use a double-lock or some other locking mechanism. Another option would be to look at Boost.call_once to initialize the data for you.

  • You are facing a static initialization problem. The easiest way out is implemeting a Singleton so that you can control the initialization process. As you are using multithreaded code, the Singleton will have to be thread-safe (consider the double check locking) pattern for creation, and probably a mutex and a condition to avoid race conditions. Check your threading library documentation for documentation on this part. The general pseudo code would be:

    // image_control would be 'example' in your two last snippets
    // painter
    image image_control::obtain_picture()
    {
       mutex.acquire();
       while ( ! image_already_created ) 
          image_creation_condition.wait(); // wait for image creation
       image res = the_image;
       image_already_created = false; // already consumed
       image_consumption_condition.signal(); // wake up producer is waiting
       mutex.release();
       return res;
    }
    // image creator
    void image_control::create_picture( image new_image )
    {
       mutex.acquire();
       while ( image_already_created ) 
          image_consumption_condition.wait(); // wait for image to be consumed
       the_image = new_image;
       image_already_created = true;
       image_creation_condition.signal(); // wake up consumer if it is waiting
       mutex.release();
    }
    

    Your threading library probably has better constructs (RAII for mutex acquisition and release()) but the idea is that you have a single point where the two threads wait for the other to complete their tasks so that there is no thread condition.

asp.net mvc url routing - sub folder name

Hi there

I would like to create a url just like followings :

http://localhost/news/announcement/index http://localhost/news/health/index http://localhost/news/policy/index

announcement, health, policy are controller

so I make a new url route map like this :

routes.MapRoute( "News", "news/{controller}/{action}/{id}", new { controller = "Announcement", action = "Index", id = "" } );

It works fine but, following two urls show same page :

http://localhost/news/announcement/index http://localhost/announcement/index

I would like to prevent second url.

What shoud I do?

Thanks Kwon

From stackoverflow
  • If you have still have the default route set up, you'll need to remove it or add a route constraint so that it doesn't match your news path.

    Remove this:

    routes.MapRoute( "Default",
                     "{controller}/{action}/{id}",
                     new { controller = "Home", action = "Index", id = "" } );
    

    Or add a constraint:

    routes.MapRoute( "Default",
                     "{controller}/{action}/{id}",
                     new { controller = "Home", action = "Index", id = "" },
                     new { controller = "(Home|Other)" } );
    

    The constraint will allow the default route to match only controllers Home and Other, but not Announcment, Health, or Policy (or anything else for that matter).

    Graphain : So what's happening is the first URL is matching on your custom route but the second URL is matching on the default route.
    tvanfosson : @Graphain -- that's my suspicion, but it's hard to know without seeing the entire code.
    tvanfosson : @kwon -- 'Other' was just an example of another controller since I don't know what your controllers are named. If you have no other controllers than the ones in "news", then you really don't need the "default" route at all.
  • If there is any default route mapping then move it to the end of your mappings. If that doesn't help then you can try Url Routing Debugger.

  • Logically speaking second url should not work. Because news is your application name which is hosted in IIS and i guess you might have put that in Default website. So if you are accessing the application URL will be always

    http://localhost/news/controller/action

    and if you give this

    http://localhost/controller/action, it doesnt know which application to look.

    i suggest you to create a virtual directory 'news' if you have not created one and then publish everything there. Also make sure you have not published your application files in Inetpub\wwwroot\ directory.

    Am waiting for your reply to continue.

  • I mean "sub folder", not "application" or "virtual directory" I think tvanfosson's answer, especially by constraint is enough for my question. But, I am still wondering that what "new { controller = "(Home|Other)" " means. I am sorry I am a just new commer in asp.net mvc.

Emacs: getting readable keyboard-macros

When using insert-kbd-macro to save a named keyboard-macro I get "unreadable" lisp-code like

(fset 'ppsql
   (lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ([134217788 134217765 44 return 44 17 10 return 33 134217765 102 102 backspace 114 111 109 return 17 10 102 111 109 backspace backspace 114 111 return 33] 0 "%d")) arg)))

I'd rather have something like the following:

(fset 'move-line-down
      [?\C-a ?\C-k delete down ?\C-y return up])

IIRC I used the same method to record, name, and insert both kbd-macros: F3, F4, name-last-kbd-macro.

Is it possible to get the first macro in a readable format?

From stackoverflow
  • I've never seen the first form. The second form is what I'm used to. Did you try re-recording the first macro to see what happens if you're sure you record, then name, then insert?

    The other thing to try is "C-X (", which invokes kmacro-start-macro and "C-X )" kmacro-end-macro, rather than F3/F4,which are doing something extraneous about keeping a counter. Maybe the simpler keyboard macro command will work more straightforwardly.

  • The keyboard macro functionality in Emacs stands of two modes: macros and kmacros. The former returns the macro in a way you like—the symbol form—, the latter provides the lambda form. So that, if you call name-last-kbd-macro you get a symbol form, if you call kmacro-name-last-macro, you get a lambda form.

  • Thanks for that!

    So the naming of the macro determines the format when inserting?

    I've conducted some more experiments and noticed that M-x insert-kbd-macro RET RET would give me the "symbol-form".

    Whereas M-x insert-kbd-macro RET pp2sql RET gives the "labmda-form" (after naming with name-last-kbd-macro).

    Now I realize that I've all the way used name-last-kbd-macro in my earlier experiments...?

    Török Gábor : When you check the function definition of `kmacro-name-last-macro` (`C-h f kmacro-name-last-macro`), you will see in the last line that it calls `kmacro-lambda-form` on the macro--that's why you get the lambda form. (Next time better edit your question then post a new answer.)

Database Indexes

How would you explain to some one how indexes improve the performance of the database when used judiciously ? I am looking for a good, clear explanation since it's too complex out there in the books.

From stackoverflow
  • I would use the classic explanation:

    An index provides an orderly and speedy method to traverse a data set.

    The classic example is the phone book - it is INDEXED by name alphabetically - this speeds up your access as you can get directly to the name you want to find using the indexing method.

    The database is really no different - you are not having to scan the entire table for your employee with EmployeeId = 123. You are simply scanning the index, stored in a known order, which ends up performing much better.

    RobS : The phone book analogy is quite often used to explain the role of indexes
    Jeff Olson : We are nearing the point in time where a phone book analogy is just going to be received by a blank stare.
  • http://www.brentozar.com/archive/2006/04/sql-server-training-for-developers-primary-keys-indexes/

    marc_s : Excellent article by the SQL mastermind behind SO :-)
  • A database index helps the database lookup records quickly in a database table, a lot like an index helps you look up information in a book quickly. I think the key is to index the right data, so that the database can quickly lookup the data that makes the most sense. With the book example, you wouldn't index every single word, you would just index key words that a user is most likely going to want to lookup.

  • If the key word in your question is "Judiciously" then it is important to mention that where the benefit of an index is speedy queries, the trade-offs are speed and size.

    Just like in the phone book, it takes a bit of extra time to maintain the index, and also a bit of space for the index itself. Whenever a record is added to or removed from the database some time has to be spent to update the index.

    So going overkill with indexes on a database with a high rate of inserts etc might not be considered judicious use. However, thoughtfully using indexes to help speed up queries can be a massive benefit to performance.

  • Stephane Faroult, SQL Indexing in 9 Minutes and a Half [YouTube video].

  • When searching for data, if the fields used to search on are indexed, you get a direct reference to the data(or range of data, but leave that out for the non-technical talk).

    If they are not indexed, then it has to search the whole table doing the comparison for a match.

  • Bear with me, this will take awhile :-).

    Think of a simple address book where you just add records on the end as new friends or colleagues arrive (the next entry would go at 5):

    1. Bob Smith, 7 Station St, Wotahole, NJ
    2. Greg Jones, 3 Railway Pde, Boot Hill, KA
    3. Allan Brown, 27 Carriage Court, Washington, DC (home)
    4. Allan Brown, 1066 Hastings Street, Washington, DC (work)
    5.
    

    Now you need to find someone's address. No trouble, I hear you say, just scan the list looking for the name, then read off the address.

    Now, what if you're so stunningly popular that you have 1,024 friends like me (I'm such a geek, I only allocate friends in powers of two - I actually have 2,024 but 1,000 of them are being held in limbo unitl I can get another 24 together :-).

    In order to find a particular friend, you'd have to scan, on average, 512 entries (half of those in use). That's quite tedious. The worst case is scanning all 1,024 of them to find the last person you added.

    Now let's add that index. Every time you add a new friend/colleague (or delete them if they cause you too much trouble), you update this index which stores just the name in sorted order along with the line number of the full entry (the index pages in your address book are magic and auto-sort everything you write in them).

    The index for out mini-list above would be:

    1. Allan Brown, 3
    2. Allan Brown, 4
    3. Greg Jones, 2
    4. Bob Smith, 1
    

    The names and line numbers take up less space than the full entries but the most important aspect is this.

    In order to find an entry, you only have to scan, worst case, 10 entries (log21024). First, you check index number 512. If the name you're looking for is greater than that, you only have to look at entries 513-1024. If it's less, you're now only interested in entries 1-511. In either case, you've immediately cut down your search space by half.

    With the original method, you can only discard the one you check since you don't have the ordering information available to you.

    So the size of the search space goes like this (I've actually used powers of two for the indexed method but it's slightly better than that):

    +-----------+----------------+------------+
    | Iteration | Indexed method | Old method |
    +-----------+----------------+------------+
    |    0      |   1024         |    1024    |
    |    1      |    512         |    1023    |
    |    2      |    256         |    1022    |
    |    3      |    128         |    1021    |
    |    4      |     64         |    1020    |
    |    5      |     32         |    1019    |
    |    6      |     16         |    1018    |
    |    7      |      8         |    1017    |
    |    8      |      4         |    1016    |
    |    9      |      2         |    1015    |
    |   10      |      1         |    1014    |
    +-----------+----------------+------------+
    

    Once you've found the index, extract the line number from it and, because you know you've got 16 entries per page, entry number 275 (for example) is on page 18, line 4. You can go straight there without further searching.

    So, at the cost of a little more storage space and some time maintaining the index, you've greatly increased the speed of your searches. And that's what indexes do in databases as well.

How to generate random password, or temporary URL, for resetting password in Zend Framework?

I have a basic authentication process that uses Zend_Auth_Adapter_DbTable. I have login and logout actions on my Authentication Controller. Now I want to create a function to reset forgotten passwords by automatically generating a password, saving the new password, and sending them an email with the newly generated password.

What would be the best process to go about doing this? How should I generate a new password? Does the Zend Framework have anything that would make this easier?

I have also heard about sending an email with a link to a short term page that lets them set a new password. How might this be done with the Zend Framework?

From stackoverflow
  • Zend Framework does not have a password-generating class. Here's an article on how to use the PEAR module Text_Password to generate a password: http://blogs.techrepublic.com.com/howdoi/?p=118

    However, it's not a good security practice to send the password in a plain email. Instead, you should reset their account so they can temporarily log in without giving a password (given an expiring URL you send them in the email), and once they log in, require them to update their own password to something they know. Then store the salted hash of their password.


    Here's some suggestion off the top of my head for doing this in Zend Framework:

    • Define a table AccountReset with fields: reset_id (GUID primary key), account_id (reference to Accounts.account_id), and expiration (timestamp).
    • Implement an action called AccountController::resetAction(), i.e. in the same controller you use for creating accounts, logging in, changing passwords, etc.
    • When a user chooses to reset his account, insert a new row in an AccountReset table with a new GUID, a reference to the user's account, and an expiration 30 minutes or so in the future.
    • Send an email to the address on file for that user, including an URL he should click on: "https.../account/reset/reset_id/<GUID>" (if you're clever with routing rules, you can shorten that URL, but keep the GUID in it).
    • When AccountController::resetAction() receives the request, it looks up its reset_id param in the AccountReset table. If that GUID exists and the expiration time has not passed, present the user with a form to change his password (without requiring he is authenticated and logged in).
    • If resetAction() receives a request with no GUID, or the GUID doesn't exist in the database, or that row has passed its expiration, then this action may instead present the user with a button to initiate a new reset request, and send an email with a new GUID. Remember to make this button a POST request!

    Because the GUID is communicated only in email to the address for that user, no one else can gain access to change the password. Even if the user's email gets intercepted, there's only a limited time the GUID would grant that access.

    If you want to be even more cautious, you could make note of the client IP address in the AccountReset table, and require the password be changed from a client with the same IP address, within that 30 minute window.

    This is only off-the-cuff, and I haven't implemented it or evaluated it for proper security. If you are responsible for implementing security, it's your duty to read up on security issues. A well-regarded resource for PHP security is http://phpsecurity.org/.

    Andrew : Awesome response! That's very helpful. Thank you!
    Andrew : My only other question would be... would I need to generate a random number for the GUID? Thus bringing me back to my original question of how to go about doing that? Also, how should I go about enforcing that the GUID is unique in the database?
    Bill Karwin : Generate UUID in PHP with the uniqid() function: http://php.net/uniqid
    Bill Karwin : Enforce uniqueness by making it the primary key. You always have to handle duplicate key exceptions on INSERT, if you aren't using auto-increment PK. If you get a duplicate, generate another GUID (or UUID) and try again.
    Andrew : Thanks! Didn't know that function existed. =]
    zidane : Really nice walk through thx

Copy constructor initialization lists

I know that if you leave a member out of an initialization list in a no-arg constructor, the default constructor of that member will be called.

Do copy constructors likewise call the copy constructor of the members, or do they also call the default constructor?

class myClass {
  private:
    someClass a;
    someOtherClass b;
  public:
    myClass() : a(DEFAULT_A) {} //implied is b()
    myClass(const myClass& mc) : a(mc.a) {} //implied is b(mc.b)??? or is it b()?
}
From stackoverflow
  • Yes. Ctors are ctors.

    John Dibling : +1, you beat me by 2 seconds. :)
    rstevens : -1: What does "Yes" mean as an answer to a question containing an "or"?
    GMan : rstevens, the question was edited shortly after Charlie answered. Charlie answered the original question perfectly. That said, I have edited my answer below and I think it is good enough :)
  • Basically to expand Charlie's answer:

    When you enter the body of a class constructor, every member of that class has to have been constructed. So when you hit {, you are guaranteed that all your members have been constructed.

    And this means by calling their default constructor, unless of course you explicitly call another one.


    Information / Edit

    You didn't mark your edit, but I think it was the clarification on if it calls b's copy-constructor if not specified. The answer is no, it does do the default constructor, if a manual copy constructor is defined at all.

    Here is a small program you can copy-paste somewhere and mess around with:

    #include <iostream>
    
    class Foo
    {
    public:
        Foo(void)
        {
         std::cout << "In Foo::Foo()" << std::endl;
        }
    
        Foo(const Foo& rhs)
        {
         std::cout << "In Foo::Foo(const Foo&)" << std::endl;
        }
    };
    
    class Bar
    {
    public:
        Bar(void)
        {
         std::cout << "In Bar::Bar()" << std::endl;
        }
    
        Bar(const Bar& rhs)
        {
         std::cout << "In Bar::Bar(const Bar&)" << std::endl;
        }
    };
    
    class Baz
    {
    public:
        Foo foo;
        Bar bar;
    
        Baz(void)
        {
         std::cout << "In Baz::Baz()" << std::endl;
        }
    
        Baz(const Baz& rhs)
        {
         std::cout << "In Baz::Baz(const Baz&)" << std::endl;
        }
    };
    
    int main(void)
    {
        Baz baz1;
        Baz baz2(baz1);
    
        return 0;
    }
    

    This as-is (defined copy-constructor) prints this:

    In Foo::Foo()
    In Bar::Bar()
    In Baz::Baz()
    In Foo::Foo()
    In Bar::Bar()
    In Baz::Baz(const Baz&)
    

    So left as is, it calls default on both.


    By commenting out the explicit copy constructor, like:

    /*
    Baz(const Baz& rhs)
    {
     std::cout << "In Baz::Baz(const Baz&)" << std::endl;
    }
    */
    

    The output will become this:

    In Foo::Foo()
    In Bar::Bar()
    In Baz::Baz()
    In Foo::Foo(const Foo&)
    In Bar::Bar(const Bar&)
    

    That is, it calls the copy-constructor on both. So as you can see, once you explicitly declare a copy-constructor you are responsible for the copying of all class members; otherwise they will be default constructed.


    To finish up, only explicitly call foo's copy-constructor, like:

    Baz(const Baz& rhs) :
    foo(rhs.foo)
    {
     std::cout << "In Baz::Baz(const Baz&)" << std::endl;
    }
    

    And you will get this:

    In Foo::Foo()
    In Bar::Bar()
    In Baz::Baz()
    In Foo::Foo(const Foo&)
    In Bar::Bar()
    In Baz::Baz(const Baz&)
    

    So it will still only default-construct your members.


    Conclusion

    When explicitly defining a copy-constructor, the compiler will no longer automatically copy any members for you.

  • For any member variable having a default constructor that default constructor is invoked if you have not explicitly added any other constructor call for that member variable into the initialization list.

  • When the compiler provides the default cctor, what do you think the compiler does for the member variables? It copy constructs it.

    In the same vein, if the cctor is user-defined, and if one leaves out some members, those members cannot be left uninitialized. Class invariants are established during construction and have to be constantly maintained. So, the compiler does that for you.

    j_random_hacker : -1 sorry. A compiler-provided default copy ctor *will* copy each member using that member's own copy ctor (which is a bitwise copy in the case of primitive types).
    Abhay : Yes, but i am saying the same thing! *Default Initilalizes* means copying via the member cctor.
    j_random_hacker : I see what you're saying, but in fact the term "default initialises" has a specific, well-defined meaning in the C++ standard, which is to initialise an object with the type's default value (well, it's slightly more complicated but anyway...) So your description is a bit misleading.
    j_random_hacker : @Abhay: If you change the phrase "default initialises" to "copy-constructs", I'll drop my -1.
  • There is nothing magical about a copy constructor, other than that the compiler will add it in if needed. But in how it actually runs, there is nothing special - if you don't explicitly say "use such and such a constructor", it'll use the default.

  • Not in VC9. Not sure about the others.

    // compiled as: cl /EHsc contest.cpp
    //
    //    Output was:
    //    Child1()
    //    -----
    //    Child1()
    //    Child2()
    //    Parent()
    //    -----
    //    Child1(Child1&)
    //    Child2()
    //    Parent(Parent&)
    
    #include <cstdio>
    
    class Child1 {
        int x;
    public:
        static Child1 DEFAULT;
    
        Child1(){
         x = 0;
         printf("Child1()\n");
        }
    
        Child1(Child1 &other){
         x = other.x;
         printf("Child1(Child1&)\n");
        }
    };
    
    Child1 Child1::DEFAULT;
    
    class Child2 {
        int x;
    public:
        Child2(){
         x = 0;
         printf("Child2()\n");
        }
    
        Child2(Child2 &other){
         x = other.x;
         printf("Child2(Child2&)\n");
        }
    };
    
    class Parent {
        int x;
        Child1 c1;
        Child2 c2;
    
    public:
        Parent(){
         printf("Parent()\n");
        }
    
        Parent(Parent &other) : c1(Child1::DEFAULT) {
         printf("Parent(Parent&)\n");
        }
    };
    
    int main(){
        printf("-----\n");
        Parent p1;
        printf("-----\n");
        Parent p2(p1);
    
        return 0;
    }
    
    Darren Clark : And the stdout was?
  • For details see: http://stackoverflow.com/questions/563221/is-there-an-implicit-default-constructor-in-c/563320#563320

    Short:

    • Compiler Generated "Default Constructor": uses the default constructor of each member.
    • Compiler Generated "Copy Constructor": uses the copy constructor of each member.
    • Compiler Generated "Assignment Operator": uses the assignment operator of each member.