Monday, February 21, 2011

Silktest void 0 bug?

I'm running some tests with Silk and it keeps throwing this error "void 0". Does anyone have any idea how I can stop this code from executing?

My platform is XP SP3, and FireFox 3.6.

Anyone have any ideas?

From stackoverflow
  • Run the failing test in debug mode, stepping through until you get the error. Once you know what is causing it, post that and maybe someone can help resolve the problem.

    I use Silk regularly, and hearing that you're getting "void 0" with no other context is useless.

Manipulating the DOM tree

Hi,

If I load a page in an iframe, run doc.querySelect to retrieve a node N, append N to doc.body by doc.body.appendChild(N), and then remove all children from doc.body until it reaches N, would N be guaranteed to be rendered the same way as pristine in Firefox or IE? So far in the example that I have tried, it's alright, but I was wondering if it'd fail in other settings.

Thanks

From stackoverflow
  • I may be missing something, but why not copy the node, delete the children of doc.body, then append the node to the now empty doc.body? Use the cloneNode() method for copying the node.

    henchman : also a nice idea. don't forget to ignore the iframe while deleting :-)
    s.wong : Sure. But would the browser draw the node the same way as before the manipulation? Would deleting neighbour nodes affect the result of the drawing?
    Robusto : Yes, of course it would. If you are not deleting any parentNodes, from which it might inherit CSS rules, everything should be fine.
  • If you have valid markup and a corresponding doctype that should be fine :-)

Rails ActiveRecord date between

I need to query comments made in one day. The field is part of the standard timestamps, is created_at. The selected date is coming from a date_select. How can I use ActiveRecord to do that?

I need somthing like:

"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"
From stackoverflow
  • This code should work for you:

    Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})
    

    For more info have a look at Time calculations

    rtacconi : Ok but from the form I get this: {"written_at(4i)"=>"18", "written_at(5i)"=>"56", "content"=>"rrrrrr", "written_at(1i)"=>"2010", "written_at(2i)"=>"5", "written_at(3i)"=>"4"} How can I build an object to use beginning_of_day?
    baijiu : Please add the code of the form in your question...
    rtacconi : This is what I need: http://purab.wordpress.com/2009/06/16/deconstructing-date_select-in-rails/
  • If you only want to get one day it would be easier this way:

    Comment.all(:conditions => ["date(created_at) = ?", some_date])
    

How to make a mysite profile property display in a different way?

Hello,

We have a string in AD which is actually storing a date in the YYYYMMDD format, which when you map it in sharepoint to a profile property, just looks plain ugly, e.g. 20091130. Our AD people are refusing to change the format of it in AD, so we were wondering if there was a way (javascript perhaps?) of changing it so that it at least add's in some hyphens, e.g 2009-11-30.

Anyone? :-)

From stackoverflow
  • var udate = "20091130";
    var format_date = udate.substr(0,4)+'-'+udate.substr(4,2)+'-'+udate.substr(6,2);
    

    The only solution I can think of.

ASP.NET MVC - getting started with Linq and SQL procedure

Today is my first day using ASP.NET MVC, and I'm finding it very intriguing. I only just started learning asp.net.

So basically I'm trying to call a procedure from an MSSQL database, and with it I need to send a paramater "PlaceID", which is an integer. This procedure basically just picks out a number of columns from different tables in the database. Here is the Linq to SQL code

The ultimate goal is to be able to retrieve all the information and return it as JSON with a function that will be available for a javascript.

I'm wondering what is the best way to proceed from here. I know I have to create a view, but I'm still unclear exactly on how I can call the procedure and make it store all the information. I could really use some help on this, some code examples would be excellent. I already wrote a C#.net function to convert a datatable to JSON using a stringbuilder, but I get the feeling there is a smarter way to do things.

Any help is very appreciated.

From stackoverflow
  • Might I suggest going through the NerdDinner.com example first. I really think that you may have started down the wrong road and it would be worth backing up and doing some review first. For one thing, you probably don't want to be mixing DataTables and LINQ, typically you'd work with strongly-typed models and have your data context/repository return IQueryable/IEnumerables of the model instead of a DataTable. For another, there is a controller method that is able to turn a model into JSON for you. Generally, you should need to write your own JSON serialization.

    cc0 : I'm going through the tutorial they've got there. It seems excellent. I'm just not quite sure how to deal with importing procedures rather than tables. It'd be great if I could get some help explaining how to go from there.
    tvanfosson : If your procedure has a schema that matches a table, then simply drag the procedure onto the table in the designer. If there is no matching schema, then I usually will create a view that returns the same schema as the procedure, add that view as an entity in the designer, then drag the procedure onto the view. Either of these two mechanisms will create a method on the DataContext that invokes the stored proc and returns elements of the appropriate type. In some circumstances -- say when it returns a count or nothing -- I think you can also simply add the procedure to the "methods" pane.

Which pointer to delete?

I'm trying to multithread something and i have my program set up such that i have a structure/class of variables that will be passed into each thread for processing.

In this class, there are variables that hold pointers to arrays some threads have common arrays from which they read data off of, instead of duplicating those arrays, pointers are given to each function that direct them to one array. These common arrays are initialized in the main program and then the variables in an array of classes are pointed to that array which is then in turn passed off to a thread.

My question is at which level (main program or thread) should i use the delete command to terminate that array? Also, what happens to the other pointers when i do that? are they automatically deleted as well or do i have to manually keep track of those. Lastly, what happens if i accidentally delete an array while another thread is still using it?

Thanks,

-Faken

From stackoverflow
  • If you delete an array which other thread is still using, you get undefined behaviour, mist probably a crash.

    For your case I would recommend to clean up in the main thread, after all the worker threads are finished.

    Another possibility would be to use a shared pointer, which would automatically free the resources as soon as no thread is using them (though beware that you need to protect your access to the shared pointer -- for shared_ptr in MSVC's standard library it's protected automatically).

  • delete does not modify the pointer, but makes the memory being pointed to unuseable.

    So once some memory is deleted, you cannot reference it. This is just as true for a single pointer as multiple pointers:

    You can use shared pointers that will use reference counting so that the underlying memory will only be deleted when all pointers are released. For your example, you need to make sure the shared pointers are thread safe.

  • all variable inside a process (application) are shared across threads, any modification to a variable or memory will have effect to all threads that have access to it, unless you are using thread local storage (TLS).

    If you delete an array, then another thread using it, the result will be like when you delete an array then you re-access it somewhere in your code (mostly crash due to access violation).

    as for "which level" question, i think it is better to deallocate an object by the thread which create the object to avoid confusion, and be sure that those objects are no longer needed by another thread.

Reading file content changes in .NET

In Linux, a lot of IPC is done by appending to a file in 1 process and reading the new content from another process.

I want to do the above in Windows/.NET (Too messy to use normal IPC such as pipes). I'm appending to a file from a Python process, and I want to read the changes and ONLY the changes each time FileSystemWatcher reports an event. I do not want to read the entire file content into memory each time I'm looking for changes (the file will be huge)

Each append operation appends a row of data that starts with a unique incrementing counter (timestamp+key) and ends with a newline.

From stackoverflow
  •     using (FileStream fs = new FileStream
           (fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (StreamReader sr = new StreamReader(fs))
            {
                while (someCondition)
                {
                    while (!sr.EndOfStream)
                        ProcessLinr(sr.ReadLine());
                    while (sr.EndOfStream)
                        Thread.Sleep(100);
                    ProcessLinr(sr.ReadLine());            
                }
            }
        }
    

    this will help you read only appended lines

    Robert Harvey : Tested, it works. Pretty cool technique.
  • You can store the offset of the last read operation and seek the file to that offset when you get a changed file notification. An example follows:

    Main method:

    public static void Main(string[] args)
    {
        File.WriteAllLines("test.txt", new string[] { });
    
        new Thread(() => ReadFromFile()).Start();
    
        WriteToFile();
    }
    

    Read from file method:

    private static void ReadFromFile()
    {
        long offset = 0;
    
        FileSystemWatcher fsw = new FileSystemWatcher
        {
            Path = Environment.CurrentDirectory,
            Filter = "test.txt"
        };
    
        FileStream file = File.Open(
            "test.txt",
            FileMode.Open,
            FileAccess.Read,
            FileShare.Write);
    
        StreamReader reader = new StreamReader(file);
        while (true)
        {
            fsw.WaitForChanged(WatcherChangeTypes.Changed);
    
            file.Seek(offset, SeekOrigin.Begin);
            if (!reader.EndOfStream)
            {
                do
                {
                    Console.WriteLine(reader.ReadLine());
                } while (!reader.EndOfStream);
    
                offset = file.Position;
            }
        }
    }
    

    Write to file method:

    private static void WriteToFile()
    {
        for (int i = 0; i < 100; i++)
        {
            FileStream writeFile = File.Open(
                "test.txt",
                FileMode.Append,
                FileAccess.Write,
                FileShare.Read);
    
            using (FileStream file = writeFile)
            {
                using (StreamWriter sw = new StreamWriter(file))
                {
                    sw.WriteLine(i);
                    Thread.Sleep(100);
                }
            }
        }
    }
    
    jameszhao00 : I'm a bit of a noob when it comes to file operations. Does seek load everything into memory or does it only load from offset to offset+length?
    João Angelo : To my knowledge the seek operation will not load any data and just position the file stream at the specified position. In this case the position will be where the new data starts.

Batch Insert with Mysql Connector for .NET

I was wondering if there is any Bulk Insert functionality available on the MySql Connector. I do have to create millions of records and I believe the batching will be a great feature for this.

I'm working on an MVC project with a MySql datastore.

Thanks, Leonardo

From stackoverflow
  • I haven't worked with .NET, but can you use the LOAD DATE INFILE-option in MySQL? It can do millions of records per minute, depending on your database hardware.

    Good luck!

    Homer1980ar : I was looking for something more programming related. But I will take your advice in case there is too slow.

How can I use a data file in a VS 2008 unit test?

I have the files checked in to svn. The key is that I don't want to hardcode the paths to the files. How can I use relative paths and be able to find the data files consistantly?

From stackoverflow
  • The best way to do this is as follows:

    1. Add a directory called "Test Data" to your VS2008 or VS2010 Test Project.
    2. Put your data file in that directory.
    3. In the properties for your data file, Set "Copy to Output Directory" to "Copy if Newer"
    4. Add this attribute to your test method: [TestMethod, DeploymentItem(@"Test Data\", @"Test Data\")]
    5. Your test data will be in the same directory as your assembly when you run the unit tests.

F# - How to populate an System.Collections.Generic.List from array

I have following code that populates a System.Collections.Generic.List I don't like it so I was wondering if there is a better way to do this.

let getDirectories = 
        Directory.GetDirectories(_baseFolder)
let languagesList = new System.Collections.Generic.List<string>()
Seq.cast getDirectories 
|> Seq.map(fun dir -> (new DirectoryInfo(dir)).Name) 
|> fun range -> languagesList.AddRange(range)
From stackoverflow
  • Have you tried:

    let list = new System.Collections.Generic.List<string>(arr)
    

    List<'T> has a constructor that takes an IEnumerable<'T> so it happily takes any seq<'T> you pass to it.

    : +1 he he (embaracced) ok now I shall punish myself.
  • In addition to Mehrdad's answer

    I find it helpful to define helper modules for many standard collections and .Net types to make them more F# friendly. Here I would define the following

    module BclListUtil =
      let ofArray (arr: 'T array) = new System.Collections.Generic.List<'T>(arr)
      let ofSeq (arr: 'T seq) = new System.Collections.Generic.List<'T>(arr)
    

    Then you could change your original code to the following

    let getDirectories = 
            Directory.GetDirectories(_baseFolder)
    let languagesList = 
          getDirectiories
          |> Seq.map (fun dir -> (new DirectoryInfo(dir)).Name)
          |> BclListUtil.ofSeq
    
    kvb : Note also that you can use the shorter (and potentially less ambiguous) type abbreviation `ResizeArray<_>` instead of `System.Collections.Generic.List<_>`.
    JaredPar : @kvb, thanks, I didn't realize there was already a type alias present.
  • The F# alias for System.Collections.Generic.List<_> is ResizeArray<_> as kvb noted. The F# PowerPack includes a ResizeArray module for working with BCL Lists in an idiomatic F# fashion similar to the Seq and List modules.

    However, for some strange reason this module seems to include ofArray and ofList and toSeq but not ofSeq.

C# Clearing the columns in a datagridview also removes al the rows?

Does it makes sense that when columns of a datagridview are cleared, all rows are removed?

From stackoverflow
  • In a table display such a s DataGridView, if there are no columns, there cannot be any rows, and vice versa.

    Martijn : First I was somewhat surprised that all my rows were gone after clearing the columns. But when I think about it, it does makes sense :)
  • If you are removing all of the columns, then there can be no rows associated with them. You'd need at least one column in order to have rows.

  • Why don't you just toggle visibility on the column instead?

    dgv.Columns[sColumnName].Visible
    

How to have drawn objects(g.draw(...)) respond to mouse events?

I have this program where it draws a bar graph in a JFrame. The bars of the bar graph change color when I click on them. So my question is whats the best way to approach this? The bruteforce way,i.e. calculate the mouse click and see if it falls within the bars' range, or extends the BufferedImage class and have it implement mouselistener? Because if i were to create a class that extends a jpanel and override its paintcomponent method, it would for sure not run efficiently. And the bars of the bar graph will be animating also, as in values will be fed to the program and the graphs get updated all the time.

From stackoverflow
  • I would personally go for the "listen for clicks over the whole component and work out which bar a click falls on". It shouldn't be hard to do - just division to work out which bar, then a bounds check to work out if the particular bar is long enough for that point to be painted.

    Introducing "one control per bar" feels like a recipe for trouble in terms of getting layout etc right. I'm sure it can be done - and I'm sure those with more GUI experience have less trouble with layout than I do - but I strongly suspect it would much more work.

    vamsi : Ya i figured, just wanted to see if there were any other ways, better ways that is. Thanks.

adding all swf files from dir to player in vb

how can i add all swf files from dir to player in vb by just selecting directory....and play it in shockwave flash player in vb.......

i have tested a swf file and it is working fine now how can i achieve the above target

From stackoverflow
  • best way i would suggest is,

    put all these in a xml or flat file.

    in your VB, read the file and play it like a playlist.

What's the difference between xsd:include and xsd:import?

What's the difference between xsd:include and xsd:import? When would you use one instead of the other, and when might it not matter?

From stackoverflow
  • I'm interested in this as well. The only explanation I've found is that xsd:include is used for intra-namespace inclusions, while xsd:import is for inter-namespace inclusion.

  • The fundamental difference between include and import is that you must use import to refer to declarations or definitions that are in a different target namespace and you must use include to refer to declarations or definitions that are (or will be) in the same target namespace.

    Source: http://xsd.stylusstudio.com/2002Jun/post08016.htm

    Lord Torgamus : I found these explanations helpful as well: http://xsd.stylusstudio.com/2005Mar/post05007.htm http://msdn.microsoft.com/en-us/library/ms256480.aspx

Fourier transform and maximum

Is there a way to compute efficiently the Fourier transform of the max of two functions (f,g), knowing their Fourier transform?

From stackoverflow
  • I doubt it. The Fourier transform of max(f, g) can be computed efficiently if and only if the Fourier transform of |f| can be computed efficiently. (Because max(f,g) = (f+g+|f-g|)/2.)

    But there seems to be no relationship between F{f} and F{|f|}...

    poulejapon : thank you very much
  • Assuming you mean the max at each point, and since max is a non-linear operation, there is not going to be any way to do this. You would need to do the max operation in the time domain and then perform the Fourier transform.

Accessing properties of programmatically created UIButton from within a method

I have created several UI elements in the viewDidLoad method. I want to change the color of a particular UIButton from within one of my methods. How can I do this? I've tried something similar to: self.view.myUIButton.backgroundColor = myUIColor That doesn't work. What am I missing?

From stackoverflow
  • Useless you set the buttons as properties of the view controller, it loses the locally scoped references to them when the -viewDidLoad method completes.

    You can set the tag attribute for the buttons and then save the tags in a property. Then you can walk the viewController.view.subviews to find the subview with the right tag.

    That latter is very cumbersome and shold be used only if your interface elements are highly variable.

    In most cases you want something like:

    UIButton *button1;
    UIButton *button2;
    @property(nonatomic, retain)  UIButton *button1;
    @property(nonatomic, retain)  UIButton *button2;
    

    then in viewDidLoad you would use:

    self.button1=[[UIButton alloc] initWithFrame:aRect];

    then in any other method you could access the specific button with self.button1.someAttribute

    moshy : RE: tags, you can just use viewWithTag: instead of interating the subviews

Email validation in PHP

Possible Duplicate:
Is there a php library for email address validation?

Hi there, I was just wondering if any of you use a particular public script or set of functions for dealing with email validation in PHP. The built-in PHP function isn't really anything to brag about.

Thanks for your time.

From stackoverflow
  • I use to validate with cakephp function which can be found here

    The regexp is this one:

    '^[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+(?:[a-z]{2,4}|museum|travel)$'
    

    and can be found here

    soren.qvist : Great! Thanks, I'll check it out
    soren.qvist : At the end it also excludes museum and travel?
    Enrico Carlesso : No, it validates every 2-4 letter first-level domain (com, it, en, es, uk, org...) and the two long exceptions, .museum and .travel (which are first-level domains to, as shown http://en.wikipedia.org/wiki/Generic_top-level_domain). In simple words, museum and travel are the only two first-level domain longer than 4 char, so must be included.
    soren.qvist : Oh, didn't even know those existed. Thanks.
    Enrico Carlesso : You're welcome.

Printing mailing labels - php, MySQL, FPDF

I'm having trouble getting this script to output a pdf for mailing labels. It throws this error: Parse error: syntax error, unexpected $end

<?php
define('FPDF_FONTPATH','/home/directory/public_html/sub/font/');
require_once('fpdf.php');
//Connect to your database
mysql_connect("localhost", "db_user","db_pw") or
    die ("Could not connect to database");
mysql_select_db("database_name") or
    die ("Could not select database");

$query  = "SELECT employee_name, street_address, City, state, zip_code FROM employees ORDER BY `employee_name` ";
$result = mysql_query($query) or die('Error, query failed');
$num_rows = mysql_num_rows($result);

function PrintAddressLabels($result){ 


  $pdf=new FPDF(); 

  $pdf->Open();
  $pdf->AddPage(); 
  $pdf->SetFont('Arial','B',14);
  $pdf->SetMargins(0,0); 
  $pdf->SetAutoPageBreak(false); 
  $x = 0;
  $y = 0;
  $i=0;

  while (TRUE) {

    if ($row=$result[$i]) {

      //positions set above 
      $LabelText = sprintf("%s\n%s %s\n%s, %s, %s", 
      $row['employee_name'],
      $row['street_address'],
      $row['City'],
      $row['state'],
      $row['zip_code']);


      Avery5160($x,$y,&$pdf,$LabelText);

      $y++; // next row 
      if ($y == 10 ) { // end of page wrap to next column 
        $x++; 
        $y = 0; 
        if ($x == 3 ) { // end of page 
          $x = 0; 
          $y = 0; 
          $pdf->AddPage(); 
        }
      }
      $i++; //counter through result
    } else {
      // Error quit printing 
      break; 
    }

  {
  $pdf->Output('mailing_labels.pdf','D');
}
?>
From stackoverflow
  • You appear to be missing the matching } for your while(). Or your function..

  • Right before you output the pdf, you have a { which should be }.

    I've formatted the code you posted so that blocks are indented. This makes it easier to se where you might be missing a }.

    KAH : I'm trying to teach myself php, so please pardon my ignorance on indenting and formatting. I appreciate your assistance. I will research on proper formatting, and try to do better in the future. I've swapped the curly bracket around. Now I'm getting a blank white screen.

Share data between mod_python processes

I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter.

What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something database based completely overkill.

From stackoverflow
  • Put it in shared memory.

    pafcu : Actually the author of sysv_ipc seems to recommend using posix_ipc instead.
  • The quickest way is to use file IO. One process writes the file and the other reads it. You can use the mmap module to make this a little more seamless. One interesting alternative that I haven't tried (yet) is to use some derivative of multiprocessing.Manager to communicate between the processes. I haven't tried the latter, I was looking for some way to create a process-shared semaphore.

db4o object update dilemma

I am new to db4o.

I have this question in mind: when the object are retrieved from DAL, maybe it will update in Business layer, then we lost it's original property, so when it comes to updating how can I find which one is the original object in the database to update?

From stackoverflow
  • You should load the object via its ID:

    objectContainer.get().ext().getByID(id);
    

    or via its UUID:

    objectContainer.get().ext().getByUUID(uuId);
    

    See the docs for the latter one. For an explanation see the answer here or the docs here. In short use uuid only for long term referencing.

    Benny : then i will have to store the ID of the object retrieved from db somewhere?
    Karussell : hmmh, yes. I don't know of the architecture you are using but typically the ids are stored in the session instead of the entire object and the objects are loaded again from its id on the next request. But as mnemosyn already pointed out: you typically won't need ids as long as you reference to the same object (db4o will then do the update). Maybe you can give us some code with the problems you have.
    Benny : @Karussell, as mnemosyn pointed out, as long as the object instance and the ObjectContainer instance are the same one, the object update is easy, so, is this mean i need keep the database open during the life time of my app? then this is so different from the way we use RDBMS, coz, RDBMS normally only open the database for CRUD, and close it right away.
    Karussell : sorry, I don't understand what you mean and need :-( you don't need to let the db-container open. the id will always be the same (as long as you don't do a defragmentation). So you can open an instance in different container - the instance will have the same id in both containers! you can use db4o nearly in the same way as e.g. hibernate. Apply the popular session per request pattern. Some days ago I created an example with db4o+wicket+guice: http://karussell.wordpress.com/2010/01/18/crud-with-wicket-guice-db4o-neodatis/ hopefully that will take you further to a solution :-)
  • You need to be more precise about "the object". If you modify the object instance's properties, simply storing it again will perform an update:

    MyClass someInstance = ObjectContainer.Query<MyClass>().FirstOrDefault();
    someInstance.Name = "NewName";
    someInstance.PhoneNumber = 12132434;
    ObjectContainer.Store(someInstance); // This is the update call
    

    [This is just pseudo-code]

    So you don't need to match objects to each other as you would have to when using an RDBMS.

    However, you need to make sure you are not using a different instance of ObjectContainer, because a different container will not know these objects are the same instance (since there is no ID field in them).

    Your application architecture should help to do this for most workflows, so there should be really only one IObjectContainer around. Only if timespans are really long (e.g. you need to store a reference to the object in a different database and process it somehow) it'd use the UUID. AS you already pointed out, that requires to store the ID somewhere else and hence complexifies your architecture.

    If you however intend to create a new object and 'overwrite' the old object, things get somewhat more complicated because of other objects that might refer to it. However, this is a somehwat pathological case and should typically be handled within the domain model itself, e.g. by copying object data from one object to another.

    Benny : so, are you suggesting that i keep the database open during the running of the application so that i will only have one instance of ObjectContainer?
    mnemosyn : Essentially, yes. The idea is that the ObjectContainer is responsible for keeping object identities. Therefore, whenever you close a container you lose that information. In contrast to typical RDBMS, where you open/close connections as quick as possible, db4o containers should remain open all the time you potentially need access to your data model. In a web application, for example, you would open the connection upon request begin and close it when the request is completed. In a desktop application, you might want to keep the instance open even longer. Note that it keeps references!

Preload images for AJAX content using jQueryUI-tabs

So I've got a pretty nice application going using ui-tabs.. problem is, I cannot for the life of me figure out a way to pre-load images in my ajax content before the tab panel is shown. The only way I can think of is to create my own ajax functionality for the loading of tab-panel content, and adding something like this to the ajax call:

success: function(response){
    $(response).find('img').preload({
            onFinish: function(){
                    currentTabPanel.show();
            }
    });

}

But I'm thinking there's GOT to be a better way of going about this using the built in AJAX methods and events in the jQueryUi.tabs() object.. I just don't think I'm seeing it... arg.. any ideas??

From stackoverflow
  • What is response? What does it represent?

    Assume you have a list of objects representing images called imgList:

    var imagePreloader = new Image();
    
    if(imgList.length != 0)
    {
       imagePreloader.load(function() {
          if(imgList.length != 0)
          {
             var img = imglist.pop();
             imagePreloader.src = img.imgSrc;
          }
          else
          {
             currentTabPanel.show();
          }
       });
    
       imagePreloader.src = imgList.pop().imgSrc;   
    }
    
    RavenHursT : Response is just some HTML markup that may or may not have some img tags in it. So where would you put this code so that the tab panel content won't show until this code is finished loading?
  • This is a dirty little script I use sometimes but it works great:

    var imgstopreload = new Array('file1.jpg', 'file2.jpg', 'etc.jpg');
    for (x in imgstopreload){
        (new Image).src = imgstopreload[x];
    }
    

    I wouldn't do this for lots of big images because the page won't finish loading until the images are done, but if you have to have them ready, it works. Just put it in your index :)

    RavenHursT : Yeah.. only problem is, the images in the AJAX content are dynamic. I'm not going to be able to know the names of the images. That's why I have the $(response).find('img').preload() code above... thanks though..

Java - Can final variables be initialized in static initialization block?

Upto my theoretical knowledge, static variables can be initialized in static initialization block.

But when I tried to implement the above (static variables that are final too), I got an error as showing in the below snapshot.

Sanpshot can directly be accessed at http://i49.tinypic.com/5vxfn4.jpg (in case it is not clear in the below size).

From stackoverflow
  • Yes of course: static final can be initialized in a static block but.... You have GOTOs in that example (that you don't see but the try/catch is basically a 'GOTO catch if something bad happens').

    If an exception is thrown, subsequent final variables shall not be initialized.

    Note that overall static fly against the logic of OO and make the OO purists want to cry.

    From a more 'down to earth' point of view it shall undoubtly complicate your testing as well as make debugging harder.

    Yatendra Goel : Can I throw exception from `static initialization block`. What can I do when a code in `static initialization block` throw some exception which I don't want to handle.
    awk : you can initialize the variables outside of the try catch block, e.g. doing the exception throwing code in try catch and initializing in finally...
    Kevin Brock : @awk: he would need to use locals to do the assignment if the exception throwing code is the getString(...) method call.
    awk : @Kevin of course, the final variables have to be assigned to something, so in the catch block he would probably assign it to null
  • You can do this but you need to exit the static block by throwing an exception - you can rethrow the exception that was caught or a new one. Generally this exception must be a RuntimeException. You really should not catch a generic Exception but more specific exception(s) that might be thrown from within your try block. Finally, if a static initializer throws an exception then it will render the class unusable during that specific run because the JVM will only attempt to initialize your class once. Subsequent attempts to use this class will result in another exception, such as NoClassDefFoundError.

    So, to work, your initializer should read something like this:

    static {
        try {
            ...
        } catch (Exception e) {
            e.PrintStackTrace();
            throw new InitializationFailedException("Could not init class.", e);
        }
    }
    

    Assuming that InitializationFailedException is a custom RuntimeException, but you could use an existing one.

    Kevin Brock : Not sure why there was a down vote, please explain.

Another .htaccess Question about redirects

I want to redirect /forums/uploads/profile/photo-thumb-[RANDOMNUMBER].jpg

to a static no photo file like: /forums/uploads/profile/photo-thumb-none.jpg

I know it can be done with .htaccess I am currently experiencing lots of 404 Errors.

Thanks

From stackoverflow
  • You need a RegEx for this. So that any request that matches that regular expression will be redirected to the other file.
    So try this:RewriteRule /forums/uploads/profile/photo-thumb-[0-9]*.jpg /forums/uploads/profile/photo-thumb-none.jpg

Subversion "label" like SourceSafe

Is there a way to do something similar to a SourceSafe label in svn? I know of the bransch/tag, but I would like to have a more lightweight way of just setting a name for a specific revision.

From stackoverflow
  • You should be using tags for this.

  • That's exactly what tags are for. See Tags on svn-book.

  • A Tag is very lightweight, although it is made from the "copy" command.

    In subversion, copies are very simple, fast, and effective. You should not have any concerns over performance or storage space.

  • Tags in Subversion are the correct way to do this. They might not "look" lightweight because they are tree copies, but because Subversion copies very lazily, it will not take up any disk space beyond that which is used to record the transaction "copied /trunk/ to /tags/whatever". The Subversion book has more information about tags.

  • But I won't to see the tag record from trunk's log, just like the lable in source safe. Could you help me?

  • I think if you create a tag from the revision number of your trunk, then you can start see the logs of the trunk.

  • How about changing the label position in the revision log?

    Example: I created a tag named "production version" which marks file1.txt at revision 8 and few days later I want the same tag tell me that file1.txt is marked at revision 16

    In VSS one is able to "move the label" in the revision log in this scenario. In SVN I would not like to create "production version1", "production version2" ...

Text on the Button with space in between disappears in IE

I have some 6 buttons to be displayed in the toolbar and the buttons have to be displayed in such a fashion that there is a grouping i.e 3 buttons followed by a bit of space and then again another 3 buttons. I am using JSF as the UI framework.

The issue lies when my last button in the 1st group has text with space in between has to be displayed ie "Click Here", Only Click gets displayed

Actually i m using table html tag to group the set of buttons

<table>
    <tr>
        <td>
            <%-- 1st 3 buttons --%>
            <%-- the last button here has the text "Click here", But only Click is displayed in UI --%>
       </td>
       <td></td>
       <td></td>
       <%-- This is used to get the gap between group of buttons and this is what is causing the issue --%>
       <td>
           <%-- Another 3 buttons --%>
       </td>
    </tr>
</table>

Code for one of the Button (all others are rendered similarly)

<hx:jspPanel id="b1" rendered="true">
    <p:outputButtonLink id="b11" rendered="true"  
        value="Click Here"
        iconSrc="../../images/click1.gif"
        href="#" onclick="return Show();">
    </p:outputButtonLink>
</hx:jspPanel>
From stackoverflow
  • IE doesn't render "empty" table cells. Put &nbsp; in them to make IE to render them.

    <td>&nbsp;</td>
    

    That said, I strongly recommend you to learn a bit more about CSS. This is an easy fix with margin.

    Arun : Thanks for ur response balu, but tat dint work. I have figured out that having the table itself to group the buttons is causing the issue.
    Arun : Thank you very much , I was able to fix it by setting the css property width:100% for td

web2py and GNU GPL v2.0

web2py is listed under GNU GPL v2.0 so my question is:

If I develop an application using web2py do I have to release it under GNU GPL v2.0?

From stackoverflow
  • No. This is stated clearly in the web2py license http://web2py.com/book/default/section/1/7 http://web2py.com/book/default/section/1/8

  • If you create an application that is based on (still uses) web2py, extends web2py, or integrates with the web2py source then it would be subject to the GPL V2. If you use web2py as a tool and it is not related to the product you are using it on, you should be just fine.

    Be careful about shipping and distribution. To be GPL 2.0 compatible, you have to release the full source and build code if you create a "distribution". If you send it out to someone, share it, or sell it you are quite possibly subjecting your code to GPL 2.0 terms. If you are putting it on a server for private hosting or contracting someone else to do work on it, you most likely are not subject to those terms.

    Jacob

Linq To Sql Intellisense Property Names

If I had two tables such as this:

Profile Table 
-------------
PK ProfileID int
FK AddressPrimaryID int
FK AddressSecondaryID int

Address Table
-------------
PK AddressID int
Address nvarchar
City nvarchar
State nvarchar
Zip nvarchar

Notice, the profile has a two relationships to the same table, the address table. When I create my linq to sql class in VS2k8, I add my tables to the dbml. Then I am referencing this profile table in a service and I perform a query to return the first record from the profile repository. No problems there...

I get my single record and I now have intellisense on the object (profile object). I have all my properties plus the Address(object) and Address1(object). Now the Address and Address1 are the actual objects from the relationship built by linq to sql, what I want to know is can I control what the name is for this object in intellisense, so instead of Address and Address1 I could have AddressPrimary and AddressSecondary for the object name in intellisense. It would just make things clearer. Any ideas?

From stackoverflow
    1. Right Click the association on the DBML design surface and click properties.
    2. Expand "Child Property".
    3. Set the "Name" property to whatever you'd like.

Make Aptana never use Windows line endings

Is there a way to configure Aptana so that it always uses Unix line feeds instead of Windows line feeds?

From stackoverflow
  • You can change this setting by going into "Preferences" > "Workspace" and change the "New text file line delimiter" from "Default" to "Other" and then select "Unix" in the drop-down menu.

Actionscript duplicate variable definition

if(true) {
  var a:int = 1;
}
else {
  var a:int = 2;
}

In the above actionscript code I get duplicate variable definition
error because "a" has been declared twice.
But, doesn't "a" exist in two "different" scopes?

Is there an elegant way of removing this warning, rather
than pulling "a" out of both the scopes and moving it outside
the if block?

I need that alternate solution since it is in just too many places
in a code which I have to refactor.

From stackoverflow
  • No, as JavaScript, ActionScript has only one possible scope - function. {} does not create new scope, only function() {} does.

  • There is no elegant solution, other than pulling out the variable or the second time just referencing the variable, not declaring it.

    Check out this answer as well:

    http://stackoverflow.com/questions/2316605/want-to-remove-warnings

  • yup, all you need to do is

    if(true) {
      var a:int = 1;
    }else {
      a= 2;
    }
    

    and your error will be gone

Prevent inline-block from wrapping on white-space: pre?

It seems Chrome is wrapping an inline-block element if it is at the end of a line even if there is a white-space:pre container around it with overflow: auto. Is there a workable solution to prevent this from happening without changing the content?

<div style="width:400px;height:200px;overflow:auto;white-space:pre">
The span should be at the end of this text, however, it wraps to the next line.<span style="width:1px;display:inline-block;height:1em;background:red"></span>
</div>

The white-space must be preserved using newlines at least. Spaces and tabs may be compressed.

From stackoverflow
  • Try changing your white-space setting to white-space: nowrap instead.

    bmeck : This does prevent the span from wrapping, however it takes away the whitespace preservation used by the white-space: pre.
    Steve Danner : Would it work to change the white-space setting in your div style and to wrap the inner text with a
     tag?