Wednesday, February 9, 2011

what does "Total Length of columns in constaint is too long" err mean in Informix?

I get the Total length of columns in constraint is too long. erro from the following

sql] Failed to execute:   CREATE TABLE GTW_WORKFLOW_MON ( WORKFLOW_NAME VARCHAR(255) NOT
NULL, WORKFLOW_LOADED NUMERIC(20) NOT NULL, ACTIVITY_NAME VARCHAR(255) NOT NULL, FLAGS    
INTEGER NOT NULL, MONITOR_NAME VARCHAR(255) NOT NULL, CLASSNAME VARCHAR(255) NOT NULL, S

TR0 VARCHAR(255), STR1 VARCHAR(255), STR2 VARCHAR(255), NUM0 VARCHAR(255), NUM1 
VARCHAR(255), NUM2 VARCHAR(255), DATE0 VARCHAR(255), DATE1 VARCHAR(255), DATE2 
VARCHAR(255), PRIMARY KEY (WORKFLOW_NAME,WORKFLOW_LOADED,ACTIVITY_NAME,MONITOR_NAME) )

  [sql] java.sql.SQLException: Total length of columns in constraint is too long.
  • Your primary key constraint is 785 bytes (255+20+255+255). If you increase your database page size to 4K it should work, barely. You should also reconsider if you need your columns to be as wide as you are defining them.

    I found a discussion group where an engineer, Radhika Gadde, describes that the maximum index size is related to page size. He says:

    which error you are getting while creation of Tables. Maximum Index key length can be calculated as follows:

    [(PAGESIZE -93)/5] -1

    like for 2k it is [( 2048-93)/5] -1 =[1955/5] -1 =391-1=390

    if PAGESIZE is 4K it is [(4096-93)/5] -1 =4003/5-1=800-1 =799

    Jonathan Leffler : Nit pick - NUMERIC(20) is equivalent to DECIMAL(20) and occupies (20/2)+1 = 11 bytes. But your basic answer is correct.

How to push a key and release it using C# ?

I am writing a C# program which captures signals from a external device, and sends keystrokes to another application. I am using SendKeys and it works fine.

SendKeys does "press" a key by holding and releasing it immediately. I would like to make it push key and release it at will.

My question is : "is there a way to send a "push" signal to a key, then a "release" signal after a certain amount of time ?"

I am not sure SendKeys is able to do this. Any clue ?

  • I don't think it's possible from .NET directly You could try using keybd_event native call by p/invoking the funtion as described here: http://pinvoke.net/default.aspx/user32.keybd_event

    The MSDN for keybd_event is here: http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx

    Hope that helps!

    controlbreak : Nice ! Worked fine to me. Thank you very much !
    From Adam Haile
  • You could use SendInput or keyb_event, both are native API functions. SendInput has some advantages over keybd_event, but SendInput is only available starting with XP.

    Here is the msdn link http://msdn.microsoft.com/en-us/library/ms646310.aspx

    Hope this helps

  • I once was looking to do the same thing on powerpoint, to hide the cursor, and later to stop the slideshow. But it's hard and tricky as there's many top level windows appeared in powerpoint, also it's hard to figure out which part of the emulation failed if it doesn't work. After looking into the message queue using Spy++, I notice that the accelerator command was sent after the keypress, so instead, I emulated the accelerator command, and it works like charm. So you might want to look into alternative like this.

    From faulty

Is it possible to print just the canvas element?

I've created a web page that lets you input some information and then draws an image in a canvas element based on that info. I have it pretty much working the way I want except for the printing.

Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it?

Update:

The answer was so simple. I was thinking of a lot more complicated solution.

I wish I could pick more than 1 answer. I wasn't able to get the canvas to print when I used * to disable display. The simplest solution was to just turn off the form that I was using for input, using form {display:none;} in the CSS inside an @media print{}. Thanks for the quick response.



    @media print {
           form {
         display:none;
       }
    }

  • I'm not 100% sure of the support, but you can use CSS and put an attribute in the <link> tag for media="print". In this CSS file, just hide the elements you don't want to show while printing: display:none;

  • You could try something like this:

    @media print {
      * {
        display:none;
      }
    
      #SOME-CANVAS-ID {
        display:block;
      }
    }
    

    I'm not sure if a canvas is block by default, but you could try something along the lines of that and see if it works. The idea is that it will hide everything (*) for print media, except for some other arbitrary element as long as the rule's precedence is higher (which is why I used the ID selector).

    Edit: If CSS3 (specifically the negation pseudo-class) had more support, your rule could be as simple as this:

    *:not(canvas) {
      display:none;
    }
    

    However, this may cause the <html> and <body> tags to be hidden, effectively hiding your canvas as well...

    olliej : I know Safari supports :not(), I would be stunned if Opera doesn't, and i believe firefox trunk supports it (I don't know about Firefox 3.0) -- And given they are the browser that actually support the Canvas element that should be sufficient :D
    olliej : http://www.css3.info/selectors-test/test.html claims that all 3 support not -- so if you're using canvas, :not() is fine.

Same class, different namespaces, a way to simplify?

I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.

Right now In my code I'm forced to do something like this:

if( _animalType == AnimalType.Pig )
{ 
     //namespace is pigfeet
     PigFeet.Feet feet = new Feet();
     feet.WashFeet();
}

if( _animalType == AnimalType.Horse )
{
     //namespace is horsefeet
     HorseFeet.Feet feet = new Feet();
     feet.WashFeet();
 }

This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically?

  • In your namespace imports you can assign an alias to a specific namespace or member.

    using PigFeet = PigFeet.Feet;
    using HorseFeet = HorseFeet.Feet;
    
    //now your sample code should look something like
    
    if( _animalType == AnimalType.Pig )
    { 
         //namespace is pigfeet
         PigFeet feet = new PigFeet();
         feet.WashFeet();
    }
    
    if( _animalType == AnimalType.Horse )
    {
         //namespace is horsefeet
         HorseFeet feet = new HorseFeet();
         feet.WashFeet();
     }
    
    From spoon16
  • Namespaces are just a way to organize your types. In your case you're having 2 or more different classes that have methods with the same signature but don't have a common interface. In case you cannot change the code of the classes, the only way to avoid duplication here is to use reflection while loosing compile-time type-safety.

    From Orlangur
  • The namespace isn't the problem - it's simply that the 2 classes aren't related, so there's no inheritance chain that you can use for polymorphism.

    You'll need to look at something like duck typing, or an adapter pattern, or building your own proxy classes to get yourself to a common interface. For small numbers of implementations, I've gotten away with just building a single adapter class that delegates to whatever non-null instance it has:

    interface IFeet {
       void WashFeet();
    }
    
    class FeetAdapter : IFeet {
       private PigFeet.Feet _pigFeet;
       private HorseFeet.Feet _horseFeet;
    
       private FeetAdapter(PigFeet.Feet pigFeet) {
          _pigFeet = pigFeet;
       }
    
       private FeetAdapter(HorseFeet.Feet horseFeet) {
          _horseFeet = horseFeet;
       }
    
       public void WashFeet() {
          if (_pigFeet != null) {
             _pigFeet.WashFeet();
          } else {
             _horseFeet.WashFeet();
          }
       }
    
       public static FeetAdapter Create(AnimalType animalType) {
          switch (animalType) {
             case AnimalType.Pig:
                return new FeetAdapter(new PigFeet.Feet());
             case AnimalType.Horse:
                return new FeetAdapter(new HorseFeet.Feet());
          }
       }
    }
    

    For larger cases, you'd be better off with a separate PigFeetAdapter and HorseFeetAdapter that both implement IFeet, along with a FeetAdapterFactory to create them - but the concept is the same as I show above.

  • Here's me making things worse before making them better.

    You can encapsulate all the AnimalType decision logic in a single class.

    Between the two types (PigsFeet and HorseFeet), there are some similiar methods... Since WashFeet has a common signature (void with no params), System.Action can be used to reference that method. Other methods with common signatures (and parameters) may require System.Func(T). Other methods without common signatures may need to be coerced into a common signature.

    Here's the client code:

    AnimalFeetFacade myFacade = new AnimalFeetFacade(_animalType);
    myFacade.WashFeet();
    

    Here's the encapsulation class.

    public class AnimalFeetFacade
    {
      public AnimalFeetFacade(AnimalType theType)
      {
        if (theType == AnimalType.Pig)
        {
          _washFeet = WashPigFeet;
          //TODO reference more PigFeet methods here
        }
        else if (theType == AnimalType.Horse)
        {
           _washFeet = WashHorseFeet;
           //TODO reference more HorseFeet methods here
        }
        else
        {
           throw new NotImplementedException("AnimalFeetFacade only works with PigFeet and HorseFeet");
        }
      }
    
      protected Action _washFeet;
    
      public void WashFeet()
      {
        _washFeet.Invoke();
      }
    
      protected void WashPigFeet()
      {
        PigFeet.Feet = new PigFeet.Feet()
        feet.WashFeet()
      } 
    
      protected void WashHorseFeet()
      {
        HorseFeet.Feet = new HorseFeet.Feet()
        feet.WashFeet()
      }
    }
    
    From David B

jQuery slideToggle jumps around

I'm using the jQuery slideToggle function on a site to reveal 'more information' about something. When I trigger the slide, the content is gradually revealed, but is located to the right by about 100 pixels until the end of the animation when it suddenly jumps to the correct position. Going the other way, the content jumps right by the same amount just before it starts its 'hide' animation, then is gradually hidden.

Occurs on IE7/8, FF, Chrome.

Any ideas on how I would fix this?

Thanks in advance.

  • This is just a shot in the dark, but if the function is manipulating the height css property of your element(s), according to this site you have to separate the padding and display:none in your css to keep it from jumping

  • Try messing with how the element is positioned/displayed/floated. I've had similar problems which were solved by playing with those settings.

    From Ben
  • I have found a workaround, but I'm still not sure of the details. It seemed that when the 'overflow: hidden' style was added by jQuery, the effect that a nearby floated element had changed. The workaround was to place a permanent 'overflow: hidden' on the slideToggle'd div, and also a negative margin-left to counterbalance the effect.

    I am surprised that changing the overflow value has such an effect on layout, but there you have it...

  • Does your document contains any DOCTYPE declaration? Without it, some browser render the page in "quirck" mode which doesn't always lead to the result you are expecting..

    see here

    To make sure your page render as intended, add the following declaration to the top of the page (that is, before the html tag).

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    
    Andrew : Doctype fixed it on IE8 for me, thanks. Daily vote limit reached. Sorry.
    From matdumsa
  • I have specified xhtml-transitional ()

  • I've encountered the same error, solved it by positioning the element with position: relative; width: 709px; The fixed width did the trick.

  • setting a fixed width worked for me too

    nickb : Fixed width alone seems to do the trick. No need for any positioning.

What to use for membership in ASP.NET

I'm not very experienced at using ASP.NET, but I've used built in membership providers for simple WebForms application, and I found them PITA when trying to extend the way they work (add/remove few fields and redo controls accordingly). Now I'm preparing for MVC (ASP.NET MVC or Monorail based) project, and I'm thinking - is there a better way to handle users? Have them log in/log out, keep certain parts of the site available to certain users (like logged in users, or something similar to "share this with friends" feature of many social networking sites, where you can designate users that have access to certain things. How best to acheave this in the way that will scale well?

  • Have you considered using ActiveDirectory for this? Or, perhaps, OpenLDAP? You can manage each user's groups, permissions, 'authority', and so on.

    Krzysztof Koźmic : I can't use that. It's a web-facing site, and its users will have nothing to do with Active Directory users
    From Yuval
  • It depends.

    If it's an internal application, Active Directory or OpenLDAP might be the way to go.

    If it's a public application, I suggest to look at aspnet_regsql. You will be able to setup a database with Authentication in no time.

    From Maxim
  • I guess, I wasn't clear on that. To rephrase my question: Would you use standard ASP.NET membership provider for a web-facing app, or something else (what)?

  • The Membership Provider in ASP.NET is very handy and extensible. It's simple to use the "off the shelf" features like Active Directory, SQL Server, and OpenLDAP. The main advantage is the ability to not reinvent the wheel. If your needs are more nuanced than that you can build your own provider by extending overriding the methods that the ASP.NET controls use.

    I am building my own Custom Membership Provider for an e-commerce website. Below are some resources for more information on Membership Providers. I asked myself the same questions when I start that project.

    These resources were useful to me for my decision:

    I personally don't think there is a need to use something other than the builtin stuff unless you either want to abuse yourself or your needs are impossible to satisfy by anything the builtin functionality.

How do I elegantly print the date in RFC822 format in Perl?

How can I elegantly print the date in RFC822 format in Perl?

  • use POSIX qw(strftime);
    print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
    
    Adam Bellaire : Oh, nice, I didn't know there was something in the core that would do this.
    Tom Feiner : Thank you ,this is exactly, what I was looking for when I asked for an elegant way :)
    From njsf
  • The DateTime suite gives you a number of different ways, e.g.:

    use DateTime;
    print DateTime->now()->strftime("%a, %d %b %Y %H:%M:%S %z");
    
    use DateTime::Format::Mail;
    print DateTime::Format::Mail->format_datetime( DateTime->now() );
    
    print DateTime->now( formatter => DateTime::Format::Mail->new() );
    

    Update: to give time for some particular timezone, add a time_zone argument to now():

    DateTime->now( time_zone => $ENV{'TZ'}, ... )
    
    From ysth

Solaris timezone in C (missing %z on strftime)

I have an application that writes to another application and needs to provide the date + timezone of the system. I have been using strftime with the %z argument to get the timezone, and it has been working very well on Linux. However, last week we decided to merge it to solaris just to find out that %z is not present.

Someone suggested to use %Z, which will give the timezone name, but I need the %z which gives the timezone with the offset format, like +0100 or -0300 ...

Anyone has ideas?

  • %z is not POSIX. You will have to calculate the offset yourself by finding the difference between localtime and gmtime.

    For a Perl example, see here.

    From Rich

True random number generator

Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it.

Does anybody know about that article?

  • It's not possible to obtain 'true' random numbers, a computer is a logical construct that can't possibly create 'truly' random anything, only pseudo-random. There are better and worse pseudo-random algorithms out there, however.

    In order to obtain a 'truly' random number you need a physical random source, some gambling machines actually have these built in - often it's a radioactive source, the radioactive decay (which as far as I know is truly random) is used to generate the numbers.

    Newtopian : There are many sources that contain enough entropy to be suitable for random generators, thermal drift and white noise are such example. These in turn can affect the different components in the computer. MEasuring this effect *can help* with randomness.
    Newtopian : so ... yes, strictly speaking a computer is incapable of generating random sequence computationally, but since this system is based ultimately on analogue components it is possible to still get a glimpse of the "real" world and extract some if it inherent randomness.
    : radioactive decay isn't necessarily 'truly' random, we simply haven't found a determinant for it yet.
    dmckee : @devinb: While your claim cannot be *absolutely* ruled out, it would require throwing out a century of experimentally verified physics. Quantum randomness is either *really* random or non-local. Either way it is beyond human prediction.
    kronoz : I love these hardcore geek debates :-)
    From kronoz
  • I believe that was on thedailywtf.com - ie. not something that you want to do.

    It is not possible to get a truly random number from pseudorandom numbers, no matter how many times you call randomize().

    You can get "true" random numbers from special hardware. You could also collect entropy from mouse movements and things like that.

    From Blorgbeard
  • Well, to begin with, you need some true entropy to create a random number.
    Pseudo-random + Pseudo-random does not true random make. :)

    I did see an article about using the noise from a webcam in a dark box as entropy, but that is a bit outside the subject.

  • You could seed a psuedo random number generator with a truly random seed from a service like http://www.random.org/. However, if you know the seed you can still predict the psuedo random number generator.

    wnoise : pseudo, not psuedo.
    From cdv
  • Not here, but here is some information and truly random numbers.
    Random.org

    From HadleyHope
  • According to Wikipedia /dev/random, in Unix-like operating systems, is a special file that serves as a true random number generator.

    The /dev/random driver gathers environmental noise from various non-deterministic sources including, but not limited to, inter-keyboard timings and inter-interrupt timings that occur within the operating system environment. The noise data is sampled and combined with a CRC-like mixing function into a continuously updating ``entropy-pool''. Random bit strings are obtained by taking a MD5 hash of the contents of this pool. The one-way hash function distills the true random bits from pool data and hides the state of the pool from adversaries.

    The /dev/random routine maintains an estimate of true randomness in the pool and decreases it every time random strings are requested for use. When the estimate goes down to zero, the routine locks and waits for the occurrence of non-deterministic events to refresh the pool.

    The /dev/random kernel module also provides another interface, /dev/urandom, that does not wait for the entropy-pool to re-charge and returns as many bytes as requested. As a result /dev/urandom is considerably faster at generation compared to /dev/random which is used only when very high quality randomness is desired.

    From Espo
  • @Blorgbeard: Thanks. it was here

    From goldenmean
  • @Espo: No! Just because /dev/random seeds itself from more sources other than the current time doesn't mean it's truly random. Keyboard timings and kernel jitter are not truly random. However, I think that it can use a hardware RNG is there is one installed on the system. Then it would, in fact, be truly random.

    That said, in the vast majority of cases you don't need true random numbers. I think the only true RNG we use in my company is in a secure cryptoprocessor in a machine that basically just generates keys.

    Hamish Downer : Keyboard timings etc do have a certain (if low) level of information entropy. If put into decent algorithms you can generate true randomness. /dev/random is one implementation. The yarrow algorithm is another. The yarrow paper explains it will (google for it).
    From vt
  • @vt: Thank you for your information. The info in my first paragraph was from wikipedia. I will update that wikipedia-article later tonight with your answer if you get upvoted.

    From Espo
  • One of the best method to generate a random number is through Clock Drift. This primarily works with two oscillators.

    An analogy of how this works is imagine a race car on a simple oval circuit with a while line at the start of the lap and also a while line on one of the tyres. When the car completes a lap, a number will be generated based on the difference between the position of the white line on the road and on the tyre.

    Very easy to generate and impossible to predict.

    From GateKiller
  • At the end of the post, I will answer your question of why you might want to use multiple random number generators for "more randomness".

    There are philosophical debates about what randomness means. Here, I will mean "indistinguishable in every respect from a uniform(0,1) iid distribution over the samples drawn" I am totally ignoring philosophical questions of what random is.

    Knuth volume 2 has an analysis where he attempts to create a random number generator as you suggest, and then analyzes why it fails, and what true random processes are. Volume 2 examines RNGs in detail.

    The others recommend you using random physical processes to generate random numbers. However, as we can see in the Espo/vt interaction, these processes can have subtle periodic elements and other non-random elements, in part due to outside factors with deterministic behavior. In general, it is best never to assume randomness, but always to test for it, and you usually can correct for such artifacts if you are aware of them.

    It is possible to create an "infinite" stream of bits that appears completely random, deterministically. Unfortunately, such approaches grow in memory with the number of bits asked for (as they would have to, to avoid repeating cycles), so their scope is limited.

    In practice, you are almost always better off using a pseudo-random number generator with known properties. The key numbers to look for is the phase-space dimension (which is roughly offset between samples you can still count on being uniformally distributed) and the bit-width (the number of bits in each sample which are uniformally random with respect to each other), and the cycle size (the number of samples you can take before the distribution starts repeating).

    However, since random numbers from a given generator are deterministically in a known sequence, your procedure might be exposed by someone searching through the generator and finding an aligning sequence. Therefore, you can likely avoid your distribution being immediately recognized as coming from a particular random number generator if you maintain two generators. From the first, you sample i, and then map this uniformally over one to n, where n is at most the phase dimension. Then, in the second you sample i times, and return the ith result. This will reduce your cycle size to (orginal cycle size/n) in the worst case, but for that cycle will still generate uniform random numbers, and do so in a way that makes the search for alignment exponential in n. It will also reduce the independent phase length. Don't use this method unless you understand what reduced cycle and independent phase lengths mean to your application.

    Nick Johnson : Er, what? Avoiding repeats would _reduce_ the randomness. Random sequences repeat. And nobody is going to crack a PRNG by "searching through the generator and finding an aligning sequence" They'll either search all possible seeds, or if you use a poor PRNG, just directly figure out the sequence.
    Nick Johnson : Also, your proposal for making it "more random" is security through obscurity. Don't invent your own cryptosystems, you're not smart enough (and nor am I). Perfectly satisfactory cryptographically secure PRNGs are already readily available.
    John the Statistician : You are confusing repeats of a sample, rounded to fit your desired range, and repeating the entire state of the system. Since deterministic RNGs are deterministic, if the state of the whole system is the same, the behavior of the generator will repeat(pumping). Please read Knuth vol 2 or other lit
    John the Statistician : To other readers:, don't feel like you aren't smart enough to a) test whatever built in generator you are using (there are lot of bad ones, unsuitable for simulation work) b) learn enough about the existing generators to know which will suit your needs c) learn to best use results
    Nick Johnson : You said "such approaches grow in memory with the number of bits asked for (as they would have to, to avoid repeats), so their scope is limited." if you mean only that the whole state can repeat (obviously this is the case), that's not much of a limitation: n bits of state allows 2^n states.
    John the Statistician : It's true that 2^n is a bound on periodicity, but it's very hard to design algorithms that maintain the other independence properties desired and use them all, so the real bound is much tighter. Growing techniques aren't very practical, more of a design technique for deterministic infinite spaces
    Nick Johnson : Still, the state only grows with the log of the period. Certainly not of "limited" scope. And your proposed obfuscation suffers from the same limitation.
    John the Statistician : Well, they are of limited scope, because you could usually just start out with the max n you can use, and design an RNG for that size much easier. It's handicapping yourself with implicit zeros.
    Nick Johnson : Limited scope compared to what? PRNGs are used in a huge variety of applications, including cryptography. What's the alternative?
    John the Statistician : The obfuscation loses cycles (state) & phase to avoid lookups, if you expose the generated bitstream. I don't advise the technique. I treated the question as "how do I randomize a randomizer to make it look as though it's not from particular deterministic algorithm, while still maintaining RNG"
    John the Statistician : I mean state growing generators are generally less applicable than fixed size generators, because it's easier just to design for a larger fixed size. The scope of where you would pick a growing state over a fixed state is limited.
    Nick Johnson : Ah. Now I see what you mean. I thought you were talking about the scope of fixed state PRNGs.
    John the Statistician : I hope this is helping. If it's making everyone more frustrated, I'm sorry. I'm really happy to edit the post more if I've made any really serious mistakes. I'm come from a simulation background, not security, so if there's any terminology/techniques I don't seem to know, please point me to them.
  • I have to disagree with a lot of the answers to this question.

    It is possible to collect random data on a computer. SSL, SSH and VPNs would not be secure if you couldn't.

    The way software random number generator work is there is a pool of random data that is gathered from many different places, such as clock drift, interrupt timings, etc.

    The trick to these schemes is in correctly estimating the entropy (the posh name for the randomness). It doesn't matter whether the source is bias, as long as you estimate the entropy correctly.

    To illustrate this, the chance of me hitting the letter e in this comment is much higher than that of z , so if I were to use key interrupts as a source of entropy it would be bias - but there is still some randomness to be had in that input. You can't predict exactly which sequence of letters will come next in this paragraph. You can extract entropy from this uncertainty and use it part of a random byte.

    Good quality real-random generators like Yarrow have quite sophisticated entropy estimation built in to them and will only emit as many bytes as it can reliably say it has in its "randomness pool."

    NullUserException : -1 Cryptographically secure pseudorandom != True random
  • If you believe in a deterministic universe, true randomness doesn't exist. :-) For example, someone has suggested that radioactive decay is truly random, but IMHO, just because scientists haven't yet worked out the pattern, doesn't mean that there isn't a pattern there to be worked out. Usually, when you want "random" numbers, what you need are numbers for encryption that no one else will be able to guess.

    The closest you can get to random is to measure something natural that no enemy would also be able to measure. Usually you throw away the most significant bits, from your measurement, leaving numbers with are more likely to be evenly spread. Hard core random number users get special hardware that measures radioactive events, but you can get some randomness from the human using the computer from things like keypress intervals and mouse movements, and if the computer doesn't have direct users, from CPU temperature sensors, and from network traffic. You could also use things like web cams and microphones connected to sound cards, but I don't know if anyone does.

    Dan : Actually, it has been mathematically proven that there is no underlying order behind the "randomness" inherent in quantum mechanics (Bell's Inequality, http://en.wikipedia.org/wiki/Bell%27s_theorem). Unless you're willing to accept nonlocality, which makes the universe really weird :-P
    dmckee : I would like to emphasize Dan's comment here. This was a bone of contention throughout most of the 20th century, but the issue is well settled at this point. Moreover Bell's theorem is surprisingly accessible to the non-specialist.
    From rjmunro
  • @kronoz: Some processors (such as the AMD Geode) have a hardware RNG, based on noisy transistors, which exploit quantum randomness for a true random source.

    Radioactive decay is unnecessary, there are many other equally random effects.

    From sysrqb
  • John von Neumann once said something to the effect of "anyone attempting to generate random numbers via algorithmic means is, of course, living in sin."

    Not even /dev/random is random, in a mathematician's or a physicist's sense of the word. Not even radioisotope decay measurement is random. (The decay rate is. The measurement isn't. Geiger counters have a small reset time after each detected event, during which time they are unable to detect new events. This leads to subtle biases. There are ways to substantially mitigate this, but not completely eliminate it.)

    Stop looking for true randomness. A good pseudorandom number generator is really what you're looking for.

    dmckee : Hardware radio-decay RNGs usually compare the size of the two intervals between three (detected) decays. This kills the dead-time issue. 'Course it leave DNL, and other electronics issues, but what you need is not "really, *really* random", but "random enough".
    dmckee : As long as I'm riffing on physics today: you generally wouldn't actually choose a Geiger-Muller tube for this any more. Silicon detectors are smaller, cheaper, and require less power.
    Arkapravo : @rjh: Very nice to quote Neumann !
    From Rob Hansen
  • There is this article on SO, it might be the one you were looking for: http://stackoverflow.com/questions/137340/true-random-number-generation-using-ping

  • An algorithm for truly random numbers cannot exist as the definition of random numbers is:

    Having unpredictable outcomes and, in the ideal case, all outcomes equally probable; resulting from such selection; lacking statistical correlation.

    There are better or worse pseudorandom number generators (PRNGs), i.e. completely predictable sequences of numbers that are difficult to predict without knowing a piece of information, called the seed.

    Now, PRNGs for which it is extremely hard to infer the seed are cryptographically secure. You might want to look them up in Google if that is what you seek.

    Another way (whether this is truly random or not is a philosophical question) is to use random sources of data. For example, unpredictable physical quantities, such as noise, or measuring radioactive decay.

    These are still subject to attacks because they can be independently measured, have biases, and so on. So it's really tricky. This is done with custom hardware, which is usually quite expensive. I have no idea how good /dev/random is, but I would bet it is not good enough for cryptography (most cryptography programs come with their own RNG and Linux also looks for a hardware RNG at start-up).

    jcinacio : +1 - simple terms and good explanation. also, /dev/random is indeed good enough for crypto (check http://en.wikipedia.org/wiki//dev/random)
    Brian Stinar : An algorithm is defined as a step-by-step procedure which terminates in a finite amount of time. A PRNG is a specific type of algorithm, but there is no reason that I could not actually have a random number generation algorithm based on physical phenomenon like one based on capturing photons and measuring their polarity. The definition of algorithm and of random are both important, and the fact that a PRNG is a specific subset of 'algorithm'. They all are algorithms.
    From Sklivvz
  • I recommend hooking the logic circuits of a Bambelweeny 57 Sub-Meson Brain to an atomic vector plotter suspended in a strong Browian Motion producer (say a nice hot cup of tea).

    http://hitchhikers.wikia.com/wiki/Infinite_Improbability_Drive

    From Andy Brice
  • To summarize some of what has been said, our working definition of what a secure source of randomness is is similar to our definition of cryptographically secure: it appears random if smart folks have looked at it and weren't able to show that it isn't completely unpredictable.

    There is no system for generating random numbers which couldn't conceivably be predicted, just as there is no cryptographic cipher that couldn't conceivably be cracked. The trusted solutions used for important work are merely those which have proven to be difficult to defeat so far. If anyone tells you otherwise, they're selling you something.

    Cleverness is rarely rewarded in cryptography. Go with tried and true solutions.

  • TOUR OF ACCOUNTING

    Troll: Over here we have our random number generator.

    Troll: NINE NINE NINE NINE NINE NINE

    Dilbert: Are you sure that's random?

    Troll: That's the problem with randomness - you can never be sure.


    If you are using random data for cryptography, you also want to look at the dispensation of the values that have been generated. There are plenty of values that could be generated randomly that would be wholly unacceptable for use in cryptography. Although, unlikely all nines is still a valid random number.

    From Elijah
  • A computer usually has many readily available physical sources of random noise:

    • Microphone (hopefully in a noisy place)
    • Compressed video from a webcam (pointed to something variable, like a lava lamp or a street)
    • Keyboard & mouse timing
    • Network packet content and timing (the whole world contributes)

    And sometimes

    • Clock drift based hardware
    • Geiger counters and other detectors of rare events
    • All sorts of sensors attached to A/D converters

    What's difficult is estimating the entropy of these sources, which is in most cases low despite the high data rates and very variable; but entropy can be estimated with conservative assumptions, or at least not wasted, to feed systems like Yarrow or Fortuna.

    From

good resource for socket errors?

Where can I find a list of all types of bsd style socket errors?

  • You can also find a list of error codes (and a general description of their meaning) on the Open Group's pages for each function (like connect, for example).

    From Head Geek
  • In the documentation? For instance, for connect(), see:

    % man connect
    ...
      ECONNREFUSED
              No-one listening on the remote address.
      EISCONN
              The socket is already connected.
    
      ENETUNREACH
              Network is unreachable.
    
    From bortzmeyer
  • Of you want to know all possible errno's or some comments on them you could take a look at the header files, on a Linux system there are located in

    • /usr/include/asm-generic/errno-base.h
    #ifndef _ASM_GENERIC_ERRNO_BASE_H
    #define _ASM_GENERIC_ERRNO_BASE_H
    
    #define EPERM   1 /* Operation not permitted */
    #define ENOENT   2 /* No such file or directory */
    #define ESRCH   3 /* No such process */
    #define EINTR   4 /* Interrupted system call */
    #define EIO   5 /* I/O error */
    #define ENXIO   6 /* No such device or address */
    #define E2BIG   7 /* Argument list too long */
    #define ENOEXEC   8 /* Exec format error */
    #define EBADF   9 /* Bad file number */
    #define ECHILD  10 /* No child processes */
    #define EAGAIN  11 /* Try again */
    ...
    
    • /usr/include/asm-generic/errno.h
    #ifndef _ASM_GENERIC_ERRNO_H
    #define _ASM_GENERIC_ERRNO_H
    
    #include 
    
    #define EDEADLK  35 /* Resource deadlock would occur */
    #define ENAMETOOLONG 36 /* File name too long */
    #define ENOLCK  37 /* No record locks available */
    #define ENOSYS  38 /* Function not implemented */
    #define ENOTEMPTY 39 /* Directory not empty */
    #define ELOOP  40 /* Too many symbolic links encountered */
    #define EWOULDBLOCK EAGAIN /* Operation would block */
    ...
    

    If you want to know what errno a call, e.g. socket() or connect() can return, when install the development manpages and try man socket or man connect

    From amo-ej1
  • Many functions will set errno on failure, and instead of going through errno.h yourself and converting the error number to strings, you are much better off calling perror.

    perror will print the current errno's corresponding message to stderr with an optional prefix.

    Example usage:

    if (connect())
    {
        perror("connect() failed in function foo");
        ...
    }
    

    perror has friends called strerror and strerror_r who might prove useful if you want to capture the string for use in places other than stderr.

    From freespace

What is the state of the art user interface for browsing complex version control system history?

When using Mercurial I sometimes find that it is hard to understand the relationship between changesets when there are thousands of changesets, and sometimes ten or more active branches at any one time. Currently, I use hgview which is okay, and while it makes a reasonable attempt to represent the parent relationships it is still basically one dimensional. I imagine something making use of graph visualisation programs such as GraphViz might work nicely, or perhaps something more wacky.

Currently I'm working on projects with around 30,000 revisions, and I expect that number to grow significantly; if 100 full time developers really grok distributed version control and start committing regularly and sharing their full development history then we could end up dealing with millions of revisions. A browser which doesn't have to load the entire history in to RAM every time you want to look at it therefore becomes necessary

I'm interested in good history browsers for any version control systems as well, especially if there is a chance I can port them to Mercurial.

  • the gitk(1) tool for git is what I use at work. Note that it takes a git rev-list constraint so you can limit what you see. You definitely want to begin doing such selective picking in the long run when the amount of commits go up.

    From jlouis
  • I use ClearCase VCS at work and its Version Tree browser could presumably suit you. But, alas, I don't know any separate ready-made tool for this.

    From Rorick

Why is obj folder generated for?

The default output path for any project is Visual studio is bin/Debug, but I have noticed that obj folder is also generated which again contains dlls and pdbs. Can someone tell me why is this folder generated

  • "obj" folder is used to store temporary object files and other files used to create the final binary.

    Further reading here

    From casademora

Looking for a Complete Delphi (object pascal) syntax

I need a complete Object Pascal syntax (preferably Delphi 2009). Some of the syntax is given by the help files, but not all information is provided. So I started collecting loose bits of information. Recently I added these to a more or less complete syntax description (EBNF like).

Although it looks extensive, there are still bugs and I'm sure parts are missing (specially in the .NET syntax). So I'm asking the SO Delphi community. Do you have any information or can you correct the errors? In return I provide the complete syntax to the community. It probably saves you some time ;-). In the future, I like to do the same for other languages (Like C#/C++/Java).

The syntax description I already have is given: My Syntax sofar. Or if you like a Text version. (The XHTML is generated from the text version).

Please note that the syntax focusses on the syntactical part, because the lexical part is not really a problem.

Update

I have a new version of the Delphi Syntax. html version. It includes al versions including 2009. Prism extentions are still on the todo list. And I'm not sure if I'm going to keep them together.

For the real purists, it also contains the full assembler code (which does not support the full 100% of the intel set but only a few instructions are missed.).

  • What exactly are the bugs and functionality you're missing?

    From scanning over your document, it seems you mingle syntax and semantics. I do not understand why to distinguish between SimpleTypeFloat and SimpleTypeOrdinal on a syntactic level, or code operator precedence as syntactic feature in AddOp and MulOp. true, false, nil are identifiers just as any variable name you choose.

    From devio
  • You could always read the source to the Free Pascal Compiler. It supports Object Pascal.

    Marco van de Voort : Or just try to run your parser on the FPC testsuite. It has a lot of example programs of the more "ODD" Obj Pascal features
    From Hugh Allen
  • God, last time I saw a copy of the PDF reference for the entire language was a long time ago. Normally there's a pretty good reference manual in %PROGRAM_FILES%\CodeGear\Rad Studio\5.0\Help (for D2007)
    There should be a reference to the language syntax hiding somewhere on the Codegear web site.

    From Petesh
  • Try this: DGrok - Delphi grammar

    Gamecat : This looks promissing. Thanx!
    From DiGi
  • There is no complete, published syntax for Delphi. Bear in mind that .net and win32 delphi have different syntaxes.

    This project has hand-build Delphi parser in it. And lots of test cases of code that compiles but pushes the limits of the syntax.

    From Anthony
  • Try http://docs.codegear.com/

  • Delphi 7's grammar is in the back of the Object Pascal book.

    You mean for a few thousand dollars they don't even send you that? Do they even send you a 6' x 6' poster?

    Gamecat : Nope, I they don't have it either. Thats why.
  • This might be a good help. It is the parser used in TwoDesk's Castalia.

    Marco van de Voort : The FPC using RAD, Lazarus has also highlighting parsers based on mw* (later synhighlighter)

C#/.NET Lexer Generators

I'm looking for a decent lexical scanner generator for C#/.NET -- something that supports Unicode character categories, and generates somewhat readable & efficient code. Anyone know of one?


EDIT: I need support for Unicode categories, not just Unicode characters. There are currently 1421 characters in just the Lu (Letter, Uppercase) category alone, and I need to match many different categories very specifically, and would rather not hand-write the character sets necessary for it.

Also, actual code is a must -- this rules out things that generate a binary file that is then used with a driver (i.e. GOLD)


EDIT: ANTLR does not support Unicode categories yet. There is an open issue for it, though, so it might fit my needs someday.

  • The two solutions that come to mind are ANTLR and Gold. ANTLR has a GUI based grammar designer, and an excellent sample project in C# can be found here.

    Alex Lyman : Gold doesn't generate /code/ for the lexer -- it builds a special binary file that a driver then reads at runtime. As for Antlr, I can't find anything that even implies that it supports Unicode /classes/ (it seems to allow specified unicode characters, but not entire classes)
    artur02 : ANTLR doesn't support unicode character classes
  • GPLEX seems to support your requirements.

    Alex Lyman : How the hell did I never know about GPPG?
    leppie : I have been using it for years now :) GPLEX only recently (last year).
    From leppie
  • I agree with @David Robbins, ANTLR is probably your best bet. However, the generated ANTLR code does need a seperate runtime library in order to use the generated code because there are some string parsing and other library commonalities that the generated code relies on. ANTLR generates a lexer AND a parser.

    On a side note: ANTLR is great...I wrote a 400+ line grammar to generate over 10k or C# code to efficiently parse a language. This included built in error checking for every possible thing that could go wrong in the parsing of the language. Try to do that by hand, and you'll never keep up with the bugs.

    From casademora