Thursday, April 7, 2011

Seeing strange behavior on IE6 - I'm clueless

I use the following to implant a script into random websites: (added by webmasters just before /body )

<script type="text/javascript">
var xHost = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + xHost + "domain/script.js.php?u="+encodeURIComponent(window.location.host)+"' type='text/javascript'%3E%3C/script%3E"));
</script>

It is an extension of the way google analytics works. I have it installed on a specific website in which the html above it is not perfectly formed.

It works great on all browsers besides IE6. On IE6 the script never runs. Unless I run fiddler2 in which case it runs perfectly.

Question: How can I make it run on IE6. Any idea why it behaves well when fiddler is in the way and not so well when fiddler isn't?

Notes: I have no control over the web sites that have already integrated this code. When I copied the website page code to my server and run it from there it did run OK.

From stackoverflow
  • Have you tried putting the script tag in the end of the document just before the finishing body element? Usually that's were you put the Google Analytics-code.

    Nir : yes. thats where it is
  • How do you know its not running? Does sticking a simple

    alert('hello!');
    

    in the script tag run?

    what about above/below the other js code?

    Whats "invalid" about the html on the page with problems?

    Nir : I have no control over the script above. it is already attached at a customer site. I don't want to get the customer involved
  • Ah, I see you're using https here. When fiddler gets in the middle of your code when running https, fiddler uses its OWN certificate to talk to your browser. Maybe your copy of IE6 trusts Fiddler's certificate, but for some reason does not trust the certificate of the site you're referencing?

  • It turns out an add on named activationmanager.dll was causing the problem. Its a spyware. (IE6 is on my 5.5 years old boy computer). Thanks for the help!

    Ovesh : select your answer as the accepted answer
    Nir : SO makes me wait 48 hours before selecting my own answer.

jQuery UI put items into other containers

I search a good way to put <li> entrys into other <ul> container. The clue is, that when the <li> element is dropped into it's origin <ul> it should be reverted to it's origin place. I do not want them to be sortable. When it is droppen on an other list, it should be added to that <ul>.

I am using the sortable plugin with the "connectWith:" option, but it does not work how I want.

Do you have some ideas, how it could work? Or whitch plugin is better for that idea.

From stackoverflow
  • You might need to maintain some metadata about original positioning using attrs on your li or the jquery .data() method and then resort the list "manually" when the drop event fires:

    $('.selector').droppable({
       drop: function(event, ui) { ... }
    });
    
  • Couldn't you just use the draggable and droppable utilities instead of the sortable?

Setting a timeout on ifstream in C++?

Hi!

We're trying to read data from 2 usb mice connected to a linux box (this data is used for odometry/localization on a robot). So we need to continuously read from each mouse how much it moved. The problem is that when a mouse is not moving, it doesn't send any data, so the file stream from which we get the data blocks execution and therefore the program can't do the odometry calculations (which involve time measurement for speed).

Is there a way to set a timeout on the input stream (we're using ifstream in C++ and read from /dev/input/mouse), so that we're able to know when the mouse doesn't move, instead of waiting for an event to be received? Or do we need to mess up with threads (arggh...)? Any other suggestions are welcome!

Thanks in advance!

From stackoverflow
  • No, there is no such method. You'll have to wait for an event, or create a custom Timer class and wait for a timeout to repoll, or use threads.

  • What you're looking for would be an asynchronous way to read from ifstream, like socket communication. The only thing that could help would be the readsome function, perhaps it returns if no data is available, but I doubt this helps.

    Using threads would be the best way to handle this.

  • Clearly, the right way to go here is to use blocking calls to retrieve data from both mice. Use threads to synchronize the whole thing. I believe there is a pretty simple way to do that.

    Use one thread for each blocking input call. When receiving data from either one, add a corresponding item in a thread-safe queue. That's all these threads should be used for.

    Use one thread to deal with received data. It will essentially be a blocking call to "pop" the first available item in the queue. Now you can do whatever you want to do when receiving data from one mouse !

  • A common way to read from multiple file descriptors in linux is to use select(). I suggest starting with the manpage. The basic system flow is as follows:

    1) Initialize devices
    2) Obtain list of device file descriptors
    3) Setup the time out
    4) Call select with file descriptors and timeout as parameters - it will block until there is data on one of the file descriptors or the time out is reached
    5) Determine why select returned and act accordingly (i.e. call read() on the file descriptor that has data). You may need to internally buffer the result of read until an entire data gram is obtained.
    6) loop back to 4.

    This can become your programs main loop. If you already have a different main loop you, can run the above without looping, but your will need to insure that the function is called frequently enough such that you do not lose data on the serial ports. You should also insure that your update rate (i.e. 1/timeout) is fast enough for your primary task.

    Select can operate on any file descriptor such network sockets and anything else that exposes an interface through a file descriptor.

    Adam Rosenfield : +1, select() is the way to go since it avoids the headaches caused by multithreading.
  • Take a look at the boost Asio library. This might help you deal with the threading suggested by schnaeder.

How does Google determine to send the Virus page?

When I was a Windows user, I received many times the Virus page in Google. I thought things change in Mac. I received today my first Virus page in Google. I am flabbergasted. The experience raises a question:

How can Google know that there is a virus? How does such a "virus" act? How does it determine to send the Virus page?

From stackoverflow
  • I believe Google shows their "virus page" if either you, or in rare cases your ISP, perform far more queries than normal over a certain period of time. I once wrote a little test app to perform certain keyword searches, and after a few thousand searches (within minutes) I began to receive the message. Luckily it went away after a few days.

  • From the official Google blog:

    We maintain a list of such sites through both manual and automated methods. We work with a non-profit called StopBadware.org to come up with criteria for maintaining this list, and to provide simple processes for webmasters to remove their site from the list.

    Assuming you mean the "This website may harm your computer"-warning.

    Cerebrus : Right... that is an assumption all right, since the OP's "virus page" assertion is far from clear. Good answer, in any case. +1
  • Please note that it's not necessarily a 'virus page'. Google also shows that warning if a site is involved with phishing (a fake PayPal or bank login page, for example). It's merely a warning that the contents of the site may be misleading or dangerous.

    Having a Mac protects you against almost all viruses in the wild today, but you will still receive that message from Google on bad sites - they display it to everyone, even if you can't get infected.

    Masi : I did only a search from Firefox. I did not entered any site. Perhaps, the odd event has something to with the servers of Scroogle.org.
  • Simon's answer is generally right.

    You can get some more information about methods in Google security blog, e.g.: http://googleonlinesecurity.blogspot.com/2008/02/all-your-iframe-are-point-to-us.html

How to split-output sounds to speaker and earphone?

OS: win xp
motherboard: ASUS A8N-E (with sound card built-in)
I have a speaker and an earphone.
When using mp3 player and media player at the same time, all of the sounds will output to all sound output devices(speaker and earphone).

Is it possible to let the mp3 only output in speaker while the media player only output in earphone?

From stackoverflow
  • No, not without a second sound card

  • Which operating system?

    If you're running Windows and your PC has an HDAudio solution, then the speakers and headphones may appear as two separate output devices (it depends - for instance, on my laptop the headphones and speakers appear as the same output device and there's an electrical switch that switches between the two when the headphones are plugged in).

    If the headphones and speakers appear as separate audio devices, then hopefully your media player has configuration options that allow you to select the output device it uses.

    If you're running an AC'97 audio solution (and I suspect you are because your audio solution appears to support hardware loopback), you are likely to be out of luck - it all depends on how the manufacturer of your audio solution wired it up.

    If you're running Windows 7, if you launch the audio Playback controls control panel (mmsys.cpl), select "Properties" for the device the where the MP3 player is plugged in and navigate to the "Listen" tab, you can ask Windows to play the contents of any input onto any output device.

How to solve TPTP Monitor error ( IWAT0435E ) in Eclipse, on Debian-based Linux?

After installing Test & Performance Tools Platform in Eclipse Ganymede on, whenever I tried to profile a Java application, I was confronted by the launch configuration dialogue which contained an error along the lines of:

Error IWAT0435E could not connect to host

How is this problem fixed?

From stackoverflow
  • After searching for a while I found the solution in a couple of blogs, so thanks to Pablo and Shimi. These contain a more detailed background if you're interested.

    The problem related to something called the Agent Controller being linked to an old version of libstdc++. To solve it you can run the following two commands:

    wget mirrors.kernel.org/ubuntu/pool/universe/g/gcc-2.95/libstdc++2.10-glibc2.2_2.95.4-24_i386.deb
    sudo dpkg --install libstdc++2.10-glibc2.2_2.95.4-24_i386.deb
    

    Though your mileage may vary depending on distro version etc.

    You should then be able to profile successfully in Eclipse, I found that I didn't even need to restart Eclipse.

  • Problem: you need to have libstdc++-libc6.2-2.so.3 installed. To solve this problem on openSUSE install package "compat".

  • Use the following if you're using Ubuntu 9.10 Karmic Koala 64 bit

    wget http://mirrors.kernel.org/ubuntu/pool/universe/g/gcc-3.3/libstdc++5_3.3.6-17ubuntu1_amd64.deb
    sudo dpkg -i libstdc++5_3.3.6-17ubuntu1_amd64.deb
    

    Launch eclipse and viola...you're in business :)

    joelpet : Worked fine even on Ubuntu 10.04 Lucid Lynx 64-bit with TPTP-4.6.2 on Eclipse from repositories.

Powershell's Invoke-Expression missing param

I thought that I had the latest CTP of Powershell 2 but when I try the command: invoke-expression –computername Server01 –command 'get-process powershell'

I get an error message: A parameter cannot be found that matches parameter name 'computername'.

So the question is: How can I tell which version of PowerShell I have installed? And what the latest version is?

From stackoverflow
  • $host.version.tostring() will return the version number.

    RTM of v1 is 1.0.0.0

    Couldn't honestly tell you what the latest version of the previews are because I haven't had a chance to play yet.

    HTH

  • Thanks - just ran that and got 2.0

    Just found the CTP and see that it was published on 11/5/2007 so I now know that I have the latest.

    It's a mystery to me why that param is not recognized.

  • The latest CTP is CTP2 released on 05/02/08 and can be found here. Remoting requires WinRM to be installed on both the calling machine and the target machine. Included in the CTP is a script to configure WS-Management called Configure-WSMan.ps1.

    This command should get you the version number of PowerShell that you have installed. Get-Command "$PSHome\powershell.exe" | Format-List FileVersionInfo V1.0 is 6.0.5430.0 CTP2 is 6.1.6585.1

    I don't have the version number for the first CTP on hand, but I can find it if you really need it.

  • I'm guessing that this is a change to the cmdlet made during the configuration process Configure-Wsman.ps1. I don't have an environment setup to test right now, but I'm guessing something went wrong with the configuration. I can verify that on XP the parameter is not available (duh). I'd assume that you will find the same on Vista/08 without the configuration completed.

  • The problem is that from CTP 1 to CTP2, they switched up the Invoke stuff, all the remoting stuff is done through Invoke-Command now, and Invoke-Expression is solely for turning a string into a script ;)

    P.S.: If you're on v2 you can run $PSVersionTable to see a list of versions including the CLR and Build versions.

  • From last night's build (which means you might have this in CTP3 but if not, you'll get it in the next public drop):

    [4120:0]PS> $psversiontable
    Name                           Value
    ----                           -----
    CLRVersion                     2.0.50727.3521
    BuildVersion                   6.1.7047.0
    PSVersion                      2.0
    WSManStackVersion              2.0
    PSCompatibleVersions           {1.0, 2.0}
    SerializationVersion           1.1.0.1
    PSRemotingProtocolVersion      2.0
    

    Experiment! Enjoy! Engage!

    Jeffrey Snover [MSFT] Windows Management Partner Architect

  • If the $PSVersionTable variable doesn't exist, then you are running V1.

    If it exists, then the version will be available as $PSVersionTable.PSVersion.

    function Get-PSVersion {
    if (test-path variable:psversiontable) {$psversiontable.psversion} else {[version]"1.0.0.0"}
    }

Where to get a Database of Spanish <-> English Translations?

Hi! for a program I am writing I would need a dictionary between Spanish and English words. I googled a while, but I could not find any database freely available. Does anybody know where or how to get such a database (preferably a simple CSV or XML file)?

So far my best idea to create such a dictionary is to create a little program that looks up an English word on Wikipedia, and uses the language links to extract the correct translation. But I don't want to want to make a million requests to Wikipedia just to generate this database...

I don't need anything fancy, just a mapping from one word to one or possibly multiple translations for this word. Just like a regular dictionary.

From stackoverflow
  • Do you need to translate on the fly at runtime, or is this a one-time translation of labels and messages for a UI?

    I'd say that runtime translation will be remarkably difficult, because you'll need more than a dictionary of words. Natural language processing is difficult in any language. Most languages need to know something about context to translate smoothly.

    If it's a one-time translation of UI elements, I've had good luck using Google Translate to go from Japanese to English.

    martinus : I just want to translate word-for-word, like in a vocabulary trainer, so there is no complicated logic involved. Just a map should be sufficient.
    ceejayoz : How are you planning to deal with words that have many meanings?
  • Ask around on the Omega Wiki, formerly known as the Ultimate Wiktionary or Wiktionary Z. They collect translations from all languages into all languages, and their data is available in a relational database.

  • To answer your question, I don't have a database like that, sorry.

    The problem with natural languages is that they are very context dependent, so the same word in English can mean many things in French. Take the English verb 'to know'. This can be translated into French as either 'savoir' (to know a fact), or connaitre (to know a person, or a town).

    I'd be very interested to know if there exists such a database, but I doubt if it exists.

    Sites like http://www.reverso.net hedge their bets by showing both results.

Django and Sqlite Concurrency issue

I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following code is causing an OperationalError: 'database is locked' I'd be grateful.

views.py

def screening(request, ovramt=None):
errors = []
if request.method == "POST":
    form = ScreeningForm(request.POST)
    if form.is_valid():
       print "Woo valid!!"
    return HttpResponse()

else: # GET            
    if ovramt is None:
        o = Ovramt.objects.select_related(depth=1).latest("date_completed")
        print "found?"
        print o.id
    else:
        try:
            o = Ovramt.objects.select_related(depth=1).get(id=ovramt)
        except:
            errors.append("OVRAMT NOT FOUND") 


    if o.residents.count() <= 0:
        o.add_active_residents()
    residents = list(o.residents)

models.py

def add_active_residents(self):
    ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
    for r in ssa_res:
        self.residents.add(r.resident) # Fails Here
    self.save()

The add_active_residents method works fine, until it is called from the views module. Is there an open connection to the database open in the view which prevents writing from the model? Does someone have an explanation why this code will error?

From stackoverflow
  • In the following method function

    def add_active_residents(self):
        ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
        for r in ssa_res:
            self.residents.add(r.resident) # Fails Here
        self.save()
    

    Why is there a select_related? You only really need the FK's of ssa_res items. Why do additional queries for related items?

    Josh Smeaton : SSA_Resident is the Many2Many table between SSA and Resident, which contains resident and ssa objects. I'm assuming that these objects need to be returned in order to add them to the many2many relationship of Ovramt_Resident.
    S.Lott : "I'm assuming..." that's my point. Try taking it out. See what happens.
    Matthew Christensen : I'm with S. Lott. Take out the select_related calls, and see if it still locks.
    Josh Smeaton : The issue stopped happening after I manually added and saved the result on the command line, and wrote some new code. I'm going to assume this is correct however, but I'll do some more testing later.
  • Sounds like you are actually running a multithreaded application, despite what you say. I am a bit clueless about Django, but I would assume that even though it might be single-threaded, whatever debugging server, or production server you run your application in won't be "inherently single threaded".

  • Are you using Python 2.6?

    If so, this is (apparently) a known issue that can be mitigated by adding:

    DATABASE_OPTIONS = {'timeout': 30}
    

    to your settings.py

    See http://code.djangoproject.com/ticket/9409

    Josh Smeaton : I tried that solution and it didn't work. I was hoping that someone would be able to identify, in my code, what might be causing the issue
  • My understanding is that only write operations will result in a db-locked condition. http://www.sqlite.org/lockingv3.html

    It's hard to say what the problem is without knowing how django is handling sqlite internally.

    Speaking from using sqlite with standard cgi, I've noticed that in some cases it can take a 'long' time to release the lock. You may want to increase the timeout value mentioned by Matthew Christensen.

Creating new Iterator from the results of another Iterator

Hi,

I'm trying to get my head around using Iterators effectively in PHP 5, and without a lot of decent examples on the net, it's proving to be a little difficult.

I'm trying to loop over a directory, and read all the (php) files within to search for defined classes. What I then want to do is have an associative array returned with the class names as keys, the the file paths as the values.

By using a RecursiveDirectoryIterator(), I can recurse through directories. By passing this into a RecursiveIteratorIterator, I can retrieve the contents of the directory as a single dimensional iterator. By then using a filter on this, I can filter out all the directories, and non-php files which will just leave me the files I want to consider.

What I now want to do is be able to pass this iterator into another iterator (not sure which would be suitable), such that when it loops over each entry, it could retrieve an array which it needs to combine into a master array.

It's a little complicated to explain, so here's a code example:

// $php_files now represents an array of SplFileInfo objects representing files under $dir that match our criteria
$php_files = new PhpFileFilter(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)));

class ClassDetector extends FilterIterator {
    public function accept() {
        $file = $this->current(); // get the current item, which will be an SplFileInfo object

        // Match all the classes contained within this file
        if (preg_match($regex, $file->getContents(), $match)) {
            // Return an assoc array of all the classes matched, the class name as key and the filepath as value
            return array(
                'class1' => $file->getFilename(),
                'class2' => $file->getFilename(),
                'class3' => $file->getFilename(),
            );
        }
    }
}

foreach (new ClassDetector($php_files) as $class => $file) {
    print "{$class} => {$file}\n";
}

// Expected output:
// class1 => /foo.php
// class2 => /foo.php
// class3 => /foo.php
// class4 => /bar.php
// class5 => /bar.php
// ... etc ...

As you can see from this example, I'm kind of hijacking the accept() method for FilterIterator, which is completely incorrect usage I know - but I use it only as an example to demonstrate how I just want the one function to be called, and for it to return an array which is merged into a master array.

At the moment I'm thinking I'm going to have to use one of the RecursionIterators, since this appears to be what they do, but I'm not fond of the idea of using two different methods (hasChildren() and getChildren()) to achieve the goal.

In short, I'm trying to identify which Iterator I can use (or extend) to get it to pass over a single-dimensional array(?) of objects, and get it to combine the resulting array into a master one and return that.

I realise that there are several other ways around this, ala something like:

$master = array();
foreach($php_files as $file) {
    if (preg_match($regex, $file->getContents(), $match)) {
        // create $match_results
        $master = array_merge($master, $match_results);
    }
}

but this defeats the purpose of using Iterators, and it's not very elegant either as a solution.

Anyway, I hope I've explained that well enough. Thanks for reading this far, and for your answers in advance :)

From stackoverflow
  • I once did something similar. The source is right here and I believe is easily understandable. If you have any problem with it please let me know.

    The main idea is to extend SplFileInfo and then use RecursiveIteratorIterator::setInfoClass($className); in order to obtain information about the source code. A Filter for parsing only PHP files could be nice though I decided back then to filter them by extension in the main loop.

  • Right, I managed to get my head around it eventually. I had to use a Recursive iterator because the input iterator is essentially generating child results, and I extended IteratorIterator which already had the functionality to loop over an Iterator.

    Anyways, here's a code example, just in case this helps anyone else. This assumes you've passed in an array of SplFileInfo objects (which are the result of a DirectoryIterator anyway).

    class
        ClassMatcher
    extends
        IteratorIterator
    implements
        RecursiveIterator
    {
    
        protected $matches;
    
        public function hasChildren() {
            return preg_match_all(
                '#class (\w+)\b#ism',
                file_get_contents($this->current()->getPathname()),
                $this->matches
            );
        }
    
        public function getChildren() {
            $classes = $this->matches[1];
    
            return new RecursiveArrayIterator(
                array_combine(
                    $classes,                                                       // class name as key
                    array_fill(0, count($classes), $this->current()->getPathname()) // file path as value
                )
            );
        }
    }
    

Handling fpu exception on windows

I would like to handle fpu exception on windows, something like:

#include <math.h>
#include <fenv.h>
#include <stdio.h>

int main()
{
    double b = 0;
    int raised;
    feclearexcept (FE_ALL_EXCEPT);
    b /= 0;
    raised = fetestexcept (FE_OVERFLOW | FE_INVALID);
    if (raised & FE_OVERFLOW) { printf("over\n");}
    if (raised & FE_INVALID)  { printf("invalid\n");}

    return 0;
}

But on windows. I tried reading the MSDN, but the document is not clear at all. I want to do this with Visual Studio compilers, on both x86 and amd64 archs.

I am not interested in translating the exception in C++ - actually, I am not even interested in the FPU exception, only in knowing the FPU state after some computation, like the example above.

== edit ==

Ok, it looks like it is actually much simpler: using _clearfp is enough:

#include <math.h>
#include <float.h>
#include <stdio.h>

int main()
{
    double b = 0;
    int raised;
    raised = _clearfp();
    b /= 0;
    raised = _clearfp();
    if (raised & SW_INVALID)  { printf("invalid\n");}

    return 0;
}

Much better than dealing with exceptions, SEH and other non portable stuff :)

From stackoverflow
  • These functions are mandated by the standard, so you should have no problem in porting. What exact error are you hitting?

    David Cournapeau : It does not even compile - AFAIK, MS compilers do not have fenv.h, but have their own mechanism.
    dirkgently : For VS you'd have to rely on the pragma arul mentioned.
  • If it's Visual Studio, try putting in this line:

    #pragma   float_control (except, on)
    

    More about this here and here.

    EDIT:

    If you want to do this in plain C, you'll need to take a look at the structured exception handling (SEH).

    David Cournapeau : The two links are extremely unclear, unfortunately; I don't understand what float_control is supposed to do: translate the error into C++ exception ? I would like a pure C solution.
  • You can use _statusfp2() to retrieve the floating point status. Beware that 32-bit uses both FPU and SSE instructions. Some sample code:

    #include "stdafx.h"
    #include <float.h>
    #include <math.h>
    #include <assert.h>
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
      unsigned x86;
      unsigned sse;
      // Test zero-divide
      double d = 0;
      double v = 1 / d;
      _statusfp2(&x86, &sse);
      assert(x86 & _EM_ZERODIVIDE);
      // Test overflow
      v = pow(10, 310.0);
      _statusfp2(&x86, &sse);
      assert(sse & _EM_OVERFLOW);
      return 0;
    }
    
    David Cournapeau : thanks, this is exactly what I was looking for.

RewriteRule, Proxy directive [P] - Is it possible to make request use actual proxy host?

Hello Everybody

Does anyone know whether it is possible to make rewrite rules which use the proxying [P] directive, as shown below, to behave like ProxyPass used in conjunction with ProxyPreserveHost Off.

In other words I want the server on mydomain.net to see a request for mydomain.net not mydomain.com.

RewriteCond  %{HTTP_HOST} ^mydomain.com$  [NC]
RewriteRule ^/(.*)$  http://mydomain.net/app1/$1 [P,L]


Thanks and best regards,

From stackoverflow
  • Since [P] actually uses mod_proxy, I'd try setting ProxyPreserveHost off and seeing if that does it.

    leftbrainlogic : Hi! I'm using this inside a .htaccess file (shared hosting account) so I can't use server level configuaration options. Thanks
    chaos : Ah. Then no, you can't do it.

Library or Code Snippet for AutoComplete in Text Control based on the previous user entered values

I'm looking for a library for Autocomplete support in text controls which remembers all previous entries of the user and provide auto-complete support for it.

For example for "recent files" I use http://www.genghisgroup.com/ and it works great. Do you know something like that for this purpose?

UPDATE : This is a .NET Winforms application and I'm using normal Text Control.

From stackoverflow
  • Download the source code and look at recent files. No doubt it is storing to some form of persistant store (database, file, etc) and using that information to fill in the list. You just dupe the functionality and make it for a TextBox that is focused on words instead of files.

    I have not looked at the Genghis source, but I am sure it is easy enough to run through the control you use that has similar functionality and dupe it. When you do this, contact the Genghis group and offer it as a submission. That is how we support open source.

  • Built into a .NET TextBox is AutoComplete functionality. First you set the AutoCompleteMode property (Suggest, Append, etc.), and then you choose the AutoCompleteSource. Your choices for that are:

    FileSystem HistoryList RecentlyUsedList AllUrl AllSystemSources FileSystemDirectories CustomSource None ListItems

    In your case, you'd use CustomSource, and then populate the AutoCompleteCustomSource Collection that's a property on the TextBox. I would suggest to have a simple SqlCe database, to where you can store the values the user has entered in the past, and then when the app loads, retrieve those values, and populate the AutoCompleteCustomSource.

    A quick code sample:

    private void button1_Click(object sender, EventArgs e)
    {
        this.textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
        this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
    
        string[] items = GetListForCustomSource();
        this.textBox1.AutoCompleteCustomSource.AddRange(items);
    
    }
    
    private string[] GetListForCustomSource()
    {
        var result = new List<string>();
    
        foreach(var value in Enum.GetNames(typeof(DayOfWeek)))
        {
            result.Add(value);
        }
    
        return result.ToArray();
    }
    

    I jsut used DayOfWeek as an example, but you can query a database in that method, and return the results.

    dr. evil : I'll give it a try. What about storing them in "Application Settings"? That should do for the last 20 entry or so.
    BFree : Oh, if you only want to store 20 or so, then yes, you don't need a full db for that. Application Settings, or just a regular XML file will do just fine.

Silverlight bound TextBox loses data when browser closes

When I bind a TextBox control to a string property of a object using two way binding, it works fine - as long as the user moves off the control before he closes the browser window/tab.

But what about the user who makes a change to the contents of a text box then closes the window expecting the data to have been saved?

While it is possible to hook into the TextChanged event or Application_Exit() handler and manually update the property, you're essentially re-doing the work of the binder. Nevertheless these seem to be the only solutions so far.

nb. The same xaml/code in a WPF app works fine (App.OnExit shows updated data in object).

From stackoverflow
  • Does Silverlight's Binding class have an UpdateSourceTrigger property? In WPF you can tell a control to update its bound source whenever the property changes (rather than when the control loses focus), like this:

    <TextBox Text="{Binding Path=Foo,UpdateSourceTrigger=PropertyChanged}" />
    
    Phil Bachmann : Nice try, I can't find it documented and when I tried it, the page did not load at all. By the way, I tested my original xaml/code in a WPF app and it works fine.
  • I'm making an educated guess here based on significant web development experience but very limited Silverlight experience.

    You could use a bit of Javascript to hook into onunload in the HTML and then call a function in your Silverlight code to handle it.

    Phil Bachmann : Silverlight has a a page unload type event (app_exit), but this still requires the manual retrieval of the control data. Probably the best work-around yet.
  • It seems that this is problem with Silverlight. It does not update bound property on text box until it loses focus.

    One workaround I had to use (I was implementing dynamic filter) is to implement TextChanged event handler and update backing property manually.

    Phil Bachmann : Thanks for that. I've updated the question accordingly.

Best way to save a Stream to a file in asp.net 3.5?

I have a Stream object that is populated with the contents of an XSD file I have as an embedded resource on a project I am working on like so:

using ( Stream xsdStream = assembly.GetManifestResourceStream( xsdFile ) )
{
  // Save the contents of the xsdStream here...
}

Within this using block I would like to prompt the user with a Save File dialog on the web where they can choose to save off this XSD file contained within the stream.

What is the best way to accomplish this? I am completely lost and can't seem to Google the right terms to get a relevant answer.

Thanks!

From stackoverflow
  • If you aren't using AJAX, you can use Response.WriteFile. Else I'd use a MemoryStream. That's how I did it here. Sorry it's in VB.NET, I haven't transcoded it. Note this also lets you download a file THROUGH the webserver, i.e. if your file is on an app server w/o public access.

    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Data.Sql
    Imports System.Net
    Imports System.IO
    
    Partial Class DownloadFile
    Inherits System.Web.UI.Page
    
    Protected Sub page_load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim url As String = Request.QueryString("DownloadUrl")
    If url Is Nothing Or url.Length = 0 Then Exit Sub
    
    'Initialize the input stream
    Dim req As HttpWebRequest = WebRequest.Create(url)
    Dim resp As HttpWebResponse = req.GetResponse()
    Dim bufferSize As Integer = 1 
    
    'Initialize the output stream
    Response.Clear()
    Response.AppendHeader("Content-Disposition:", "attachment; filename=download.zip")
    Response.AppendHeader("Content-Length", resp.ContentLength.ToString)
    Response.ContentType = "application/download"
    
    'Populate the output stream
    Dim ByteBuffer As Byte() = New Byte(bufferSize) {}
    Dim ms As MemoryStream = New MemoryStream(ByteBuffer, True)
    Dim rs As Stream = req.GetResponse.GetResponseStream()
    Dim bytes() As Byte = New Byte(bufferSize) {}
    While rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0
    Response.BinaryWrite(ms.ToArray())
    Response.Flush()
    End While
    
    'Cleanup
    Response.End()
    ms.Close()
    ms.Dispose()
    rs.Dispose()
    ByteBuffer = Nothing
    End Sub
    End Class
    
  • It sounds to me that you should take a look at the WebResource.axd handler.

    Microsoft have an excellent article on the subject.

    Edit:

    It seems that tsilb beat my answer by a minute or so. However, the AssemblyResourceLoader (aka. WebResource.axd) is already implemented to do this for you and to do it properly, and don't forget that this puppy supports output caching. So go ahead use that instead and spare yourself the trouble. ;)

  • You will want to set the content-disposition:

    Response.AddHeader "Content-Disposition","attachment; filename=" & xsdFile
    

    You will also want to set the Content-Type to text/plain and Content-Length to the size of the file. Then you write the contents of the file.

    JohannesH : While this answer does provide valuable information, that is if Rob wanted to roll his own streaming, it doesn't answer the question about how to stream the file in the first place. If Rob wanted to go that way, I think tsilb has a better answer. However I still think my way is a lot easier... ;)
  • private void DownloadEmbeddedResource( 
      string resourceName, Assembly resourceAssembly, string downloadFileName )
    {
      using ( Stream stream = resourceAssembly.GetManifestResourceStream( resourceName ) )
      {
        if ( stream != null )
        {
          Response.Clear();
          string headerValue = string.Format( "attachment; filename={0}", downloadFileName );
          Response.AppendHeader( "Content-Disposition:", headerValue );
          Response.AppendHeader( "Content-Length", stream.Length.ToString() );
          Response.ContentType = "text/xml";
    
          var byteBuffer = new Byte[1];
    
          using ( var memoryStream = new MemoryStream( byteBuffer, true ) )
          {
            while ( stream.Read( byteBuffer, 0, byteBuffer.Length ) > 0 )
            {
              Response.BinaryWrite( memoryStream.ToArray() );
              Response.Flush();
            }
          }
    
          Response.End();
        }
      }
    }
    

    I ended up using this method above. Thank you for helping me with the syntax tsilb. JohannesH, I would have used your recommendation if the resource wasn't already coming from a different assembly (Sorry, I should have cleared that up in my original question).

    The code above works but I am encountering a fairly weird problem... After the method completes and the download finishes, the page is still never seems to come back to life and the mouse is still in hourglass mode like it still thinks work is being done. Any idea on how to remedy that?

    Thanks again for all your help!

Call C++ library in C#

I'm a newbie for C#, i have a lot of libraries are wrote with C++, when I want to call these libraries in C#, i met many problems. I want to know if there is a book or guideline to tell me how to do that.

From stackoverflow

Best Way to Animate Sprites in Flex

Is there a preferred way to handle animation when using Flex -- For instance, if I want to render a ball and bounce it around the screen?

From stackoverflow
  • I prefer to use a tweening library for things like this. Check these out:

    Tweener

    TweenLite / TweenMax

    KitchenSync

    I've had good luck actually using the first two, and have read great things about the last one.

  • If you're building a Flex application, you should use Flex's native Effect classes. They're probably already compiled into your app, since the core components use them, and you won't increase your SWF size with duplicate functionality like you would if you used another library. For simple animations, either mx.effects.AnimateProperty or mx.effects.Tween should work well.

    If you're working on a regular ActionScript project (without the Flex framework), then I concur with the answer given by Marc Hughes. However, if that's the case, then please don't say you're using Flex because that implies that you're using the Flex framework and it can be very confusing. If you mean Flex Builder, then please use the full name to avoid potential misunderstandings.

  • You can't always use Flex's effect class with plain sprites. Certain effects expect your target object (the object to be tweened) to implement IUIComponent interface, while others don't. So you can either use mx.effects.Tween, or if you must use the one of the effects classses, you will need to coerce your sprite into a UIComponent.

    Another option is to use one of the tween packages suggested above or roll your own with goasap!

    goasap

    Tiago : Thanks, that was exactly what I was looking for.
  • You can use mx.effects.AnimateProperty even though your target is not a UIComponent.

    If the tween you want to acheive is a simple one (Move, Resize, Fade etc) this saves you writing the boiler plate code that mx.effects.Tween requires.

Update Junction table in many-to-many relationship

This is a follow up question to this one:

http://stackoverflow.com/questions/416565/query-examples-in-a-many-to-many-relationship

regarding updating the junction table. To do this, I would have to use both key values in the junction table, in the WHERE clause.

Users       UserAddresses     Addresses
=======     =============     =========
FirstName   UserId            City
LastName    AddressId         State
                              Zip

In this example, for instance, say I wanted to update the AddressId field in the UserAddresses table, because a user changed his address. I would have to use both the existing UserId and the address AddressId in the update WHERE clause.

I'm using a stored procedure, and passing in UserId and the new AddressId as parameters.

I've tries this:

CREATE PROCEDURE dbo.test
(
@UserId int,
@AddressId int
)
AS
create table #temp
    (
    UserId int not null,
    AddressId int not null
    )
    insert into #temp select UserId, AddressId from UserAddresses where UserId = @UserId

update UserAddresses
set AddressId = @AddressIdD
WHERE (UserId+AddressId in #temp table = UserId+AddressId passed in as parameters)??

I've tried all sorts of combinations, but I can't seem to get the syntax right.

The UserId passed in, would ofcourse be the same as the one in the UserAddresses table, but this is just me trying some things. The WHERE clause is where it seems to go wrong.

Any thoughts?

From stackoverflow
  • This actually looks like a many-to-one relationship. If it's not you'll need the old address id as well as the new address id and user id to make the change. If it's a many to one relationship then a simple update should work since only one user id/address id pair will exist for each user id:

    update UserAddresses
    set AddressId = @AddressId
    where UserId = @UserId
    

    If it truly is a many-to-many relationship you need to find the existing pair out of many possible ones and update that one -- that's where you'll need both the new and old address ids in addition to the user id.

    update UserAddresses
    set AddressId = @NewAddressId
    where UserId = @UserId and @AddressId = @OldAddressId
    
    Soeren : It is a M-T-M rel., and that's why I wanted to select the existing UserId and AddressId into a temp table, and then refer to that table in the actual update. I think this should be possible, but I can't get the syntax right.
    tvanfosson : Yes, but you are only selecting by UserID into the temp table. If a user can have many addresses, then you need to find the pair matching the old address that is being removed and replace just it.
  • Why use the temp table?

    CREATE PROCEDURE dbo.test
    (
    @UserId int,
    @AddressId int
    )
    AS
    update UserAddresses
    set AddressId = @AddressIdD
    WHERE UserId = @UserId
    
  • tvanfossom pointed out the problem in your code correctly, I think.

    With the tables above, your operation could be done in various ways:

    • INSERT the link to the new address and DELETE the link to the old address, either keeping or deleting the address record that's being linked to.
    • UPDATE the link record as tvanfossom described (LuckyLindys query will set all registered addresses of the user to the same one).
    • UPDATE the address record that's being linked to.

    Which one you use depends on what you want in your application. I'd probably just update the linked address, or do you need to keep the old one?

base64 and UTF-8 encoding issue

Hello everyone,

I am writing a simple web method which returns byte[], and the byte[] is encoded by UTF-8. I have investigated related WSDL and soap message, seems the underlying web services stack will use base64 encoding?

For various reasons, I can not use or re-encode my return byte[] from UTF-8 to base64. Any ideas to modify the base64 encoding to UTF-8 encoding?

Here is my related web methods, SOAP message and related type in WSDL

Web service server side code

        [WebMethod]
        public byte[] HelloWorld2()
        {
            return utf8encodedbytes;
        }

SOAP response

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <HelloWorld2Response xmlns="http://tempuri.org/">
      <HelloWorld2Result>base64Binary</HelloWorld2Result>
    </HelloWorld2Response>
  </soap:Body>
</soap:Envelope>

related type in WSDL

xsd:base64Binary

thanks in advance, George

From stackoverflow
  • Your question doesn't really make a lot of sense I'm afraid - byte arrays aren't encoded with text encodings like UTF-8. You normally apply a UTF-8 encoding to text to get a byte array. To transfer arbitrary byte arrays in XML you should then use base64.

    If you want to transfer text you should just return a string to start with.

    What is the original data, before any kind of encoding happens? If it's a byte array, you should return a byte array and the XML should automatically contain base64-encoded data. If it's text, you should return a string and let XML cope with the encoding.

  • So what's stopping you from using Convert.ToBase64() and Convert.FromBase64()? These functions do exactly that: converting byte array to base64 strings and vica versa.

Fixing the timezone on Solaris 10

I have no ideas how to fix this. In my /etc/TIMEZONE file the TZ variable has the correct value (Canada/Eastern) and still it's showing a -1 hour lag. Where else should I be looking?

From stackoverflow
  • That is the correct file to edit. The only other step required is a reboot. The reason a reboot is required is that the init process reads the value of TZ when it is started, and all other processes inherit this value. As far as I know, there is no way to make the change effective without doing a full reboot.

    Also, make sure /etc/TIMEZONE is symlinked to /etc/default/init. For example:

    [root@server:/etc]ls -l /etc/ | grep TIMEZONE

    lrwxrwxrwx 1 root root 14 Jul 7 2008 TIMEZONE -> ./default/init

    Nik : It's all good on that side and I've done multiple reboot since I changed that file. Still, the problem persist. Thanks anyway!
  • Is your machine patched up-to-date? There were changes in DST handling for North America in 2007. On my Solaris 10 I have:

    -bash-3.00$ ls -l /usr/share/lib/zoneinfo/Canada/Eastern -rw-r--r-- 2 root bin 1252 Jul 14 2008 /usr/share/lib/zoneinfo/Canada/Eastern -bash-3.00$ openssl md5 /usr/share/lib/zoneinfo/Canada/Eastern MD5(/usr/share/lib/zoneinfo/Canada/Eastern)= 82980b1345aab5a97d90307edfefb6da

    Do you use NTP to set the time automatically or do you do it manually?

    Volker

  • When you actually log into the host, what timezone is set in your shell session?

    If the timezone in your shell session doesn't match /etc/TIMEZONE, then you probably need to reboot for the timezone change to take effect.

    If the timezone in your shell session is correct, but the actual time is wrong, then either the system clock is off or the timezone definition file is wrong somehow. You can run "date -u" to get the UTC time, which will help you figure out if the actual clock is wrong.

  • You should check what your hardware clock is. I would suggest doing this:

    • Set the UTC time correctly. i.e. (5 AM in the example):

    $ date -u -s "05:00"

    Thursday, April 29, 2010 05:00:00 AM UTC

    • Set the hardware clock accordingly (tod for SPARC and rtc for x86):

    $ rtc -c (the '-c' argument sets the DST correctly)

    • Check the date again:

    $ date

    Thursday, April 29, 2010 02:00:11 AM ART

    Regards,

    Leandro.

Best book to learn Windows assembly programming?

The other day I came across a site by the name http://securityxploded.com/enumheaps.php. On this site the author was able to understand and analyze the Windows assembly code generated. Which book can I follow to grab the knowledge of understanding Windows assembly code?

From stackoverflow
  • Assembly code is CPU specific, not OS specifc.

    cdonner : This is true, but irrelevant. Windows only runs on Intel platform. Windows assembly code has very distinct characteristics, and there are people who can read it. Felix Kasza would be one of them. I don't think he read about about it, though.
    cdonner : Sorry for the typos. It's this EEE keyboard ...
    John Nolan : Waah! a downvote. I'm fairly ignorant on the subject so thanks for the comments.
  • There are lots of books available to learn x86 assembly. A good, but perhaps a tad outdated one is called Art of Assembly Language and is available free online.

    Of course as others have pointed out, assembly language is specific to the processor rather than the operating system, but you clearly intend to learn x86 assembly.

    Jim Anderson : Outdated? How much has X86 assembly language changed?
    Dan Olson : Quite a bit since the 286/386 days when the book was first written. I haven't kept tabs on how up to date it's been kept.
  • Windows is going to be running on an Intel processor, so it's going to be x86 assembly language. As someone who has written for several processors at assembly level I'd have to suggest that you'd need a really good reason to need to do so in today's world.

    If you are merely interested then I'd just surf the web for x86 assembly language information and pick up what you can. If you have a definite need to learn x86 assembly for work or a project then I'd probably start with the Intel Programmers References

    MSalters : X86, X64, or Itanium. The latter one is _really_ different.
  • Jeff Duntmann's "Assembly Step by Step" is easy to follow.

  • A great introduction to x86 assembly language that is still relevant is the two part series by Matt Pietrek in the old Microsoft Systems Journal magazine:

    coolcake : yes, this is the kind of article i was looking for. just jump start!!
  • Iczelion's tutorials are a good place to start, even if a bit old now:

    http://win32assembly.online.fr/

    You may also want to have a look at the following:

    http://www.asmcommunity.net/

    http://en.wikibooks.org/wiki/X86_Assembly

    Also, as pointed out by Lazarus, Intel's documentation is very useful.

    If you want to get a feel for it, it may be easier to start by playing with ASM blocks in a higher level language, - one used to be able to do that in e.g. MS C++. Also the built-in assembler (BASM) of Codegear's Delphi if pretty powerful (Delphi 2009 supports up to SSE4.2 instruction sets). This frees you from having to write complete programs in assembly (that is, e.g. MASM, - ML.exe [or ML64.exe] - nowadays available with Microsoft's driver development kit)