Saturday, February 5, 2011

searchings rows from table

i want to select particular rows from the JTable which contains a particular string.. please help me for this..

  • Call JTable.getModel then just loop through using TableModel.getValueAt

  • Something like this will do the trick:

    void selectMatchingRows(JTable table, String regex) 
    {    
      for (int row = 0; row < table.getModel().getRowCount(); row++) 
      {
        for (int col = 0; col < table.getModel().getColumnCount(); col++) 
        {
          if (table.getModel().getValueAt(row, col).toString().matches(regex)) 
          {
            table.getSelectionModel().setSelectionInterval(row, row);
          }
        }
      }
    }
    

    Making sure the ListSelectionModel.selectionMode is MULTIPLE_INTERVAL_SELECTION.

    From Nick Holt

How can I copy an Excel sheet into a workbook whose windows are not visible?

source.Sheets(RevisionHistory).Copy before:=target.Sheets(1)

This does not work when all the windows for the 'target' workbook are not visible. When Visible=True for them, then it works.

The easy answer is just to make them visible. But, they are being worked on and it a problem for the user to see all that activity.

  • Try Application.ScreenUpdating = False before making the sheet temporarily visible. Remember to set it back to True again :-)

XMLHttpRequest problem

Hi,

I am writing one Web Application using XUL. In that Iam using AJAX XMLHttpRequest Object for sending request to server. When I use GPRS connection to send the request to the server from my web application the request is not going, but readyState has changed to 4 and status=0. If the request is not going out how the readyState is Changing.

The same Code working fine in local network. If I send the request to server from the browser using GPRS it is working fine. Can any body help me out in solving this problem.

Thanks in Advance.

  • the request is not going

    How do you determine that?

    Do you use the HTTP scheme? If so, status == 0 is an issue, (google says there are known quirks in Firefox).

    status == 0 is also returned when the request is using a non-HTTP protocol. So if you're making a file:// request accidentally, it would explain all the symptoms...

    [edit 2009-09-07] Also found this issue: https://bugzilla.mozilla.org/show%5Fbug.cgi?id=488605 aborted XMLHttpRequests have status==0 since Firefox 3.

    [edit] I'm not /quite/ sure, but I think that cross-domain requests that are not allowed also end up with status == 0.

    From Nickolay
  • Hi

    Thanks for the reply. Sorry for delay. I determined it by the tool WireShark.

    No Iam using http protocol only. my url is http://IPaddress/?rqty=some-request-name. And Iam setting the request header as

    httpObject.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

    is it still using non-Http Protocol?

    Please help me out Iam not able to figure it out?

    Thanks and Regards A Srinivas

    shahkalpesh : In case you dont know, you can use comments to let the person replying know of your feedback rather than posting it as a separate answer.
    Nickolay : So did you check the issue I google-linked to? You haven't indicated you did. Yes, from the looks of it you're using the HTTP protocol. I can only suggest you continue minimizing the problematic code until the problem becomes apparent. Perhaps the app does send the the request, but it gets handled by something at the OS level before getting to the network stack? I would also fire a debugger and look at the code - where readyState changes without sending a request, but only after trying everything else above.
    Nickolay : grr, stupid stripping-paragraphs logic in comment formatting...

c# app to take in excel document, and list all pivot tables on each sheet and refresh in its own thread. (faster refresh using multi threading)

Is it possible to create an multi threaded application,

The lists all the pivot tables in an excel document,

And fires a new thread to refresh each pivot table.

Currently a applicatoin.refreshall takes 3hrs.

I also do not think that vba code can be mulithreaded.

Any ideas welcome

  • I'm not sure that making this process multithreaded would necessarily help. 3 hours is a pretty long time for anything - I suspect you have other problems with this excel document. How big is the file?

Rails - etags vs. page caching (file cache)

What would be some advantages of using etags/stale?/fresh_when? instead of page caching (on a file cache)?

Apache automatically handles etags for static files, but even if it didn't, page caching would still be better since the Rails app doesn't even get called.

So, in what instances would I use the methods provided by Rails (stale?/fresh_when?)?

  • One thing that comes to mind is that fresh_when will still save you some rendering even if you cleared the entire page cache. Here you'd be using both in tandem.

    I'm curious about other answers as well.

    From kch
  • Another use that occurred to me was that you could still process some information before letting Rails hand out the "304 Not Modified" header. Like if you want to record hits to a page.

    From Ivan
  • They are really complimentary. Etags/fresh_when etc. help you play nice with downstream caches (like your own Varnish/Squid instances or Rack::Cache or the Browser cache or ISP Proxy Servers…)

    Page caching saves you from hitting your rails stack entirely because Apache/your webserver serve the file, so no DB lookups are done. But you have to deal with cache expiration to keep the cache fresh.

    Using etags/conditional get, you don't save much processing time since you still need to to get all the records used on the page:

    def show
      @article = Article.find(params[:id])
      @feature = Feature.current
      fresh_when :etag => [@article, @feature] 
    end
    

    in the case that the user has a current page, it saves you some rendering time and the bandwidth required to send down the page.

    From gerrit

Efficiency of web proxy scripts vs. http proxy?

I was wondering which class would be more efficient: PHP (Glype, PHProxy), CGI (CGIProxy), or javascript based scripts that run on a webserver, or an http proxy run through squid. Assuming neither class was doing any caching, would one or the other be much more efficient at handling web browsing?

And how could I write a simple script to benchmark differences between the two?

Thanks!

  • By far, Squid; anything that requires running CGI or PHP will be much slower, because they require a process per request.

How do you get the text inside the new HTMLEditor in ASP.Net Ajax Control Toolkit?

How do you get the text inside the new HTMLEditor in ASP.Net Ajax Control Toolkit?

  • controlName.Content will get you the content of the Editor control.

iPhone Application

Hello, I want to integrate some links on my iphone application. That is when user touch on the button say "Yahoo" then Yahoo's page will be opened and then all the functionalities of Yahoo mail has proceeds. How can I do that? I have a bit idea about NSURL, but not much. Please help me for that. Thanks in advance..

  • In the action method of the target put something like:

     [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.google.com"]];
    
    lostInTransit : To come back to ur application, you will have to tap on the app's icon in springboard. If you want to stay within the app and open the URL, use a UIWebView instead
    From HyLian
  • To open the page in Mobile Safari, you need to implement something like the following:

    NSURL *url = [NSUR URLWithString:@"http://www.google.com"];
    [[UIApplication sharedApplication] openURL:url];
    

    You could return to your application using Custom URL Schemes (for more information see the iPhone Application Programming Guide), but since you want to access sites over which you have no control, I presume that isn't an option? Could you use a UIWebView control within your app instead?

    From Edd

RegEx for ICQ UIN

What RegularExpressionValidator.ValidationExpression should I use to allow only ICQ UIN like input?

xxx-xxx-xxx and xxx-xxx-xx and xx-xxx-xxx and xxxxxxxxx so on..

i.e. with dash as separator and without.

  • You can use the following simple expression.

    ^([0-9]-?){7,8}[0-9]$
    

    The drawback is, that it allows things like 1-2-3-4-5-6-7-8. If you want to restrict the layout more, you can use complexer expressions.

    ^(?=([0-9]-?){8,9})([0-9]{2,3}-?)*(?<!-)$
    

    This expression asserts that the string contains exactly eight or nine numbers and some dashes using the positive look ahead assertion (?=([0-9]-?){8}). Then it matches groups of two or three numbers optionaly separated by dashes and finally asserts that the string does not end with a dash using the negative look behind assertion (?<!-).

    This still allows some irregular patterns like 12-34567-89. If you want to eliminate them, too, you will have to list all allowed patterns. But I suggest not to do so, but allow as much flexibility as possible - I would allow every string with eight or nine numbers and any number of dashes - even --123---4-5-67--8 and then reformt the user input in a predefined format.

    ^(-*[0-9]-*){8,9}$
    
    Massa : Some comments: (1) when I used ICQ, I had a 6-digit number; (2) I think ICQ numbers cannot start with 0; (3) Just ignore the dashes is a nice policy IMHO: `^-*[1-9][0-9-]*$` would be enough...
    Nathan Fellman : Massa, you're giving away your internet age with this... My ICQ also has a 6-digit number, and I joined 11 or 12 years ago.

Lock down Word & PowerPoint features

Does anyone know of a way to lock down (remove/hide/disable) Word & PowerPoint in Office 2007?

Simply put I want to disable the user from using some functionality in them (mostly formatting). Some ideas of ways to do it, which I just can’t seem to find solutions based on:

  • Word has a protect document option which locks some features away, but I need more and also for PowerPoint – i.e. this is on a document level.
  • Some sort of UI automation which disables buttons – i.e. an application which disables them remotely. I am happy with the fact that if the UI automation is not running they get past it.
  • Group policy or registry settings
  • Rights Management Server (not sure even if that's right - just popped into my head)
  • The solution found was to create a standard VSTO add-in, add a ribbon (XML) to it and then using the commands node to disable buttons. For a list of the idMso's see this download.

    <?xml version="1.0" encoding="UTF-8"?>
    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
    <commands>
     <command idMso="Bold" enabled="false"/>
     <command idMso="Font" enabled="false"/>
     <command idMso="FontSize" enabled="false"/>
     <command idMso="Italic" enabled="false"/>
     <command idMso="Underline" enabled="false"/>
     <command idMso="Shadow" enabled="false"/>
     <command idMso="Strikethrough" enabled="false"/>
     <command idMso="ChangeCaseGallery" enabled="false"/>
     <command idMso="CharacterSpacingGallery" enabled="false"/>
     <command idMso="FontColorPicker" enabled="false"/>
     <command idMso="FontColorMoreColorsDialogPowerPoint" enabled="false"/>
     <command idMso="FontDialogPowerPoint" enabled="false"/>
     <command idMso="GroupParagraph" enabled="false"/>
     <command idMso="BulletsGallery" enabled="false"/>
    </commands>
    <ribbon startFromScratch="false">
     <tabs>
      <tab idMso="TabAddIns">
       <group id="MyGroup"
           label="My Group">
       </group>
      </tab>
     </tabs>
    </ribbon>
    

Rails Many to Many relationship issue

I have the following models:

class Person < ActiveRecord::Base
  has_many :accounts, :through => :account_holders 
  has_many :account_holders
end

class AccountHolder < ActiveRecord::Base
  belongs_to :account
  belongs_to :people
end

class Account < ActiveRecord::Base
  has_many :people, :through => :account_holders 
  has_many :account_holders
end

However, I am getting issues when using this relationship. Account.first.account_holders works just fine, but Account.first.people returns:

NameError: uninitialized constant Account::People
    from /Users/neil/workspace/xx/vendor/rails/activesupport/lib/active_support/dependencies.rb:105:in `const_missing'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/base.rb:2204:in `compute_type'
    from /Users/neil/workspace/xx/vendor/rails/activesupport/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/base.rb:2200:in `compute_type'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/reflection.rb:156:in `send'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/reflection.rb:156:in `klass'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/associations/has_many_through_association.rb:73:in `find_target'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/associations/association_collection.rb:353:in `load_target'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb:139:in `inspect'

Any ideas?

  • belongs_to requires the singular form. In AccountHolder:

    belongs_to :person
    

How to set Printer Settings while printing PDF

I'm trying to print a PDF file using Process object. And upto certain extent I could print it successfully. But now I want to set printer properties.. like no of copies, Paper size etc. But I don't see any property to set these values. I'm using following code to print PDFs string fileName = ""; string arguments = ""; string verbToUse = ""; int i = 0; ProcessStartInfo startInfo = new ProcessStartInfo(); OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = "c:\\";
        openFileDialog1.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((fileName = openFileDialog1.FileName) != null)
            {
                startInfo = new ProcessStartInfo(fileName);

                if (File.Exists(fileName))
                {
                    i = 0;
                    foreach (String verb in startInfo.Verbs)
                    {
                        // Display the possible verbs.
                        MessageBox.Show(i.ToString() + ". " + verb);
                        i++;
                    }
                }
            }

            //Console.WriteLine("Select the index of the verb.");
            string index = "2";
            if (Convert.ToInt32(index) < i)
                verbToUse = startInfo.Verbs[Convert.ToInt32(index)];
            else
                return;

            startInfo.Verb = verbToUse;
            if (verbToUse.ToLower().IndexOf("printto") >= 0)
            {
                //Printer Name
                arguments = @"\\hydfsvt02\HPLaserJ";
                startInfo.Arguments = arguments;
            }

            Process newProcess = new Process();
            newProcess.StartInfo = startInfo;

            try
            {
                newProcess.Start();

                MessageBox.Show(newProcess.ProcessName + " for file " + fileName + " started successfully with verb " + startInfo.Verb);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                MessageBox.Show(" Win32Exception caught!");
                MessageBox.Show(" Win32 error = " + ex.Message);
            }
            catch (System.InvalidOperationException)
            {
                MessageBox.Show("File " + fileName + " started with verb " + verbToUse);
            }
        }
  • I have written an application that does batch printing of PDF files.

    It's not possible to specify the printer settings that you want to use. It's not even possible if you use the COM interface with the Adobe Standard/Pro versions.

    Your options are to, 1. Buy a license to a third-party PDF renderer that you can use to convert the PDF to Bitmaps and use the PrintDocument to control the PrinterSettings

    1. Use something like GhostScript to convert the PDF files to BMP files and then use the PrintDocument class to print the BMP files. You can then control the PrinterSettings.

Performance impact of Java class files generated with "-target 1.5" running on a 1.6 VM?

After migrating my whole setup from Java 1.5 to 1.6 (J2EE, Tomcat) a couple of months ago, I just realized that Maven is still configured to generate class files targeted for 1.5 via Sun's javac parameter "-target 1.5". Can I expect any performance boosts when changing "-target 1.5" to "-target 1.6"?

  • I don't see why there'd be a performance difference. There's no major differences between the class format of 1.5 and 1.6. If nothing else changes specifying the target will change the classversion id in the generated classes.

  • It shouldn't make much difference. 1.6 files can have stack map/table structures that improve bytecode verification speed (Apache Harmony just uses a smarter algorithm).

    If you were to go to 1.4 the initial loading of a class constant would be slightly slower, but that's irrelevant given how long a class takes to load (a new form of the ldc bytecode replaces Class.forName, but the result was stored in a static field.)

    In general it doesn't matter. The runtime compiler is the important bit and that can pretty much generate the same machine code. In the past there have been made to javac to reduce the optimisation it does so as not to mangle the code for the runtime compiler, but that is independent of the -target flag.

    Kjeld : I think I'm going to change it for the next update. Shouldn't hurt though and feels more consistent...
  • Java 1.6 uses a different class-file-format, that simplifies the process of the bytecode-verification. So startup-times should improve a little, if you use the new class-file-format.

    From Mnementh

MySQL get the date n days ago as a timestamp

In MySQL, how would I get a timestamp from, say 30 days ago?

Something like:

select now() - 30

The result should return a timestamp.

  • I think you are after DATE_SUB.

    From joeslice
  • You could use:

    SELECT unix_timestamp(now()) - unix_timestamp(maketime(_,_,_));
    

    For unix timestamps or:

    SELECT addtime(now(),maketime(_,_,_));
    

    For the standard MySQL date format.

  • DATE_SUB will do part of it depending on what you want

    mysql> SELECT DATE_SUB(NOW(), INTERVAL 30 day);
    2009-06-07 21:55:09
    
    mysql> SELECT TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day));
    2009-06-07 21:55:09
    
    mysql> SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day));
    1244433347
    

Reorder tabs in WPF TabControl

Is there an easy way to customize the WPF TabControl so that it supports TabItem drag and drop - similar to what IE and firefox do.

  • You could use or get started with Bea Stollnitz's existing helpers for Dragging and Dropping in an ItemsControl. It does have some limitations as she mentions, but it's a great place to start, and probably will work as is for most all of the functionality you will require.

    After importing her DragDropHelper and Adorner classes, it's very simple to use them with the TabControl (Since it is a descendant of ItemsControl).

    Setting a simple drag template, and the properties on the TabControl are all we need. Since the solution is set up to handle dragging of data bound items, if your tabs are statically declared in XAML instead of using the TabControl.ItemsSource then you can just bind their DataContext to themselves.

    <Window x:Class="Samples.Window1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:dd="clr-namespace:DragDropListBox"
     Title="Dragging TabItems"
     Height="300"
     Width="300">
    
    <Window.Resources>
     <DataTemplate x:Key="Local_TabItemDragTemplate">
      <Border CornerRadius="5"
        BorderBrush="Black"
        BorderThickness="2"
        Background="DodgerBlue">
       <TextBlock Margin="5"
            Text="{Binding Path=Header}" />
      </Border>
     </DataTemplate>
    </Window.Resources>
    
    <StackPanel>
     <TabControl dd:DragDropHelper.IsDragSource="true"
        dd:DragDropHelper.IsDropTarget="true"
        dd:DragDropHelper.DragDropTemplate="{StaticResource Local_TabItemDragTemplate}">
      <TabControl.ItemContainerStyle>
       <Style TargetType="{x:Type TabItem}">
        <Setter Property="DataContext"
          Value="{Binding RelativeSource={RelativeSource Self}}" />
       </Style>
      </TabControl.ItemContainerStyle>
      <TabItem Header="Tab 1" />
      <TabItem Header="Tab 2" />
      <TabItem Header="Tab 3" />
      <TabItem Header="Tab 4" />
     </TabControl>
     <TabControl dd:DragDropHelper.IsDragSource="true"
        dd:DragDropHelper.IsDropTarget="true"
        dd:DragDropHelper.DragDropTemplate="{StaticResource Local_TabItemDragTemplate}">
      <TabControl.ItemContainerStyle>
       <Style TargetType="{x:Type TabItem}">
        <Setter Property="DataContext"
          Value="{Binding RelativeSource={RelativeSource Self}}" />
       </Style>
      </TabControl.ItemContainerStyle>
      <TabItem Header="Tab 5" />
      <TabItem Header="Tab 6" />
      <TabItem Header="Tab 7" />
      <TabItem Header="Tab 8" />
     </TabControl>
    </StackPanel>
    

    alt text

    From rmoore
  • That works very well. Is there any way to implement this in a TabControl ControlTemplate?

    From

Isolate a specific thread to run in medium trust

I'm writing a .net win app that loads foreign assemblies and executes third party scripts. I am looking for a way to sanitize the code executed by the foreign script, and only allow the third party scripts access to a defined set of websites. Creating a PermissionSet with its state set to none, and then adding the desired websites, and selecting "Permit only", would seem to do the trick, if it wasn't for the fact that the third party code can, under full trust, revert this by using Assert. Still I want the part of the code that I control myself to run under full trust, so I am looking for a way to restrict the trust level for a particular thread, or at a particular point in the stack, programmatically.

Any help would be much appreciated.

  • You can't do this on a thread level.

    The appropriate way to have different trusts in a single application is by creating a separate AppDomain for the third party scripts to run under.

    Chris Brumme wrote a good blog post regarding AppDomains for some background reading.

    David Hedlund : looks like i have a lot of reading up to do. thanks for pointing me in the right direction.

Remove border on activex ie control

For the application im building, i use an activex ie control. It works greate but i cant work out how to remove the border around it.

I have tried overriding the invoke call and setting DISPID_BORDERSTYLE to zero but it looks like it never gets hit.

Any ideas?

  • i think you need to implement IDocHostUIHandler on your host. then in GetHostInfo you can return the DOCHOSTUIFLAG_NO3DBORDER or DOCHOSTUIFLAG_NO3DOUTERBORDER flag.

    ~jewels

    Lodle : thanks, with that tip it pointed me to this: http://msdn.microsoft.com/en-us/library/aa770041%28VS.85%29.aspx
    From Jewel S

Should example xml in an xsd documentation annotation be escaped?

Lets say I have an xsd schema and I have several <annotation/> elements with <documentation/> elements in them. If I wanted to place example xml in the <documentation/> elements, should I escape the example xml?

e.g.:

<annotation>
    <documentation>Example Xml: &lt;element&gt;some text&lt;/element&gt;</documentation>
</annotation>

or:

<annotation>
    <documentation>Example Xml: <element>some text</element></documentation>
</annotation>

XmlSpy 2009 seems to try to validate example xml, which in this case is Oasis 8.1 which I did not write, and fails. If I escape the xml, the schema display view of XML Spy does not unescape the &lt; and &gt;.

It would seem the correct thing to do is include the un-escaped xml. XML In A Nutshell Third Edition shows an example on page 282 where there is an anchor tag in an xsd box, but does not recommend specifically what to do in cases of the documentation containing examples of the schema being used..

  • Compromise: leave the examples unescaped, but wrap them in a <![CDATA[ ... ]]> block. This should prevent XML Spy from attempting to validate your examples without requiring they be escaped.

    <annotation>
        <documentation><![CDATA[Example Xml: <element>some text</element>]]></documentation>
    </annotation>
    
    Justin Dearing : That's simpler than escaping.
    From Ben Blank
  • The element permits any well-formed XML content to be inside, so yes, the second example is correct as well.

    Although the XML Schema definition does not go into detail about the element, several documents I've seen use HTML inside to format the documentation. I could also think of using C# XML cocumentation-line comments inside.

    So, while you may use arbitrary well-formed XML inside , I would advise against it - because some automatic documentation tool using the XSD may choke on it. Instead, I would recommend wrapping the documentation with <![CDATA[ which lets you write smaller-than-signs and ampersands. End your CDATA-section with ]]>.

    From nd

How to use CVS in TestComplete ?

Please, tell where to find free SCC provider for CVS. Because TestComplete, as i have understood works only through SCC.

Thank you.

  • It looks like TestComplete works directly with cvs. All you need is cvs.exe per their webpage. If you need a copy of cvs for windows, I recommend Tortoise CVS.

    From Alex B
  • Jalindi Igloo is free, but very outdated. CVS SCC Proxy is newer, but I'm not sure if it's free.

    From Helen

How to get line number information from XMLBeans' XMLError

The subject basically says it all.

XmlBeans' XmlError.getLine() always returns -1.

Is there any way to get at least an approximate position for an error?

I have already tried the XmlObject, but since whitespace, quotes, et al. are stripped or changed, that's not much help.

  • The documentation suggests you can do this by providing XmlOptions:

    setLoadLineNumbers

    If this option is set, line number annotations are placed in the store when parsing a document. This is particularly useful when you want XmlError objects to contain line numbers. Note: This adds line numbers info only for start tags. For line number info on end tags use: setLoadLineNumbers(java.lang.String) Example: xmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT)

    From McDowell

how to install php and javabridge on Tomcat

how to set the environment variables of javabridge.what are the setting can be change for installing JavaBridge and php on Tomcat

  • you'll probably find that you'll need to set up Apache2 as the default web-server, and then use the Apache2-Tomcat Connector to pass any tomcat connections to tomcat.

    As for the environment variables, it depends on the environment, is it windows or linux (and which flavour of linux)?

    From phalacee

jCombobox JPA HQL inner join error.

Hi everyone ,

i am new at Java , i got a problem like this ; i have got a desktop application , there is 2 jComboBox in JFrame.One of this jComboBox is hold Personels from Personel Table and another is take Personel's title.When jComboBox1's selected index changes occurs it will get personelid and fill jComboBox2 with its title.Thats so simple.But when selected index changes it filling with titles but showing something like Ljava.lang.object.xxxxx...

ERROR

Here is my codes ;

  if (jComboBox1.getSelectedItem() !=null) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("SwingDenemePU");
    EntityManager em = emf.createEntityManager();
    Query sorgu = em.createQuery("from Personel p,Unvan u where  p.unvanID = u.unvanID and u.unvanID=:id");

int id = ((Unvan)jComboBox1.getSelectedItem()).getUnvanID();

   sorgu.setParameter("id", id);

   personelList = sorgu.getResultList();

    Object[] items = new Object[personelList.size()];

    for (int i = 0; i < personelList.size(); i++) {
items[i] = personelList.get(i);
    }
    DefaultComboBoxModel def = new DefaultComboBoxModel(items);
    jComboBox2.setModel(def);

if i change items[i] = personelList.get(i) to ;

            Personel personel = personelList.get(i);
        items[i]=personel.getPersonelAdSoyad();

i am getting Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to DBClasses.Personel error.

  • The default combo box renderer simply invokes the toString() method of the Object contained in the model. So when you add a String to the model you see the value of the String because thats what the toString method returns.

    If you are storing a Personel Object in the model then you have two choices:

    a) add a toString() method to the Personel class b) create a custom renderer to display a property from the Personel class.

    Read the JComboBox API and you will find a link to the Swing tutorial on "How to Use Combo Boxes" which provides an example of a custom renderer.

    From camickr
  • you query appears incorrect, not sure what your mappings are but try something more like these:

        Query sorgu = em.createQuery("select p from Personel p,Unvan u where p.unvanID = u.unvanID and u.unvanID=:id");
    

    or

        Query sorgu = em.createQuery("from Personel p where p.unvanID=:id");
    
    Ibrahim AKGUN : thanx man u r solved my problem.
    From objects

Unable to inject smalldatetime into D-SQL statement

Hi, when i try to execute this sql statement i am getting the error.. Conversion failed when converting character string to smalldatetime data type.

Does anyone know what i am doing wrong?

declare @modality varchar(50)
declare @datefrom smalldatetime

set @modality = 'xxxxxxx'
set @datefrom = '20090101'

declare @var1 nvarchar(4000)
select @var1 = 
    'select
     sum('+ @modality +') as ' + dbo.fnc_titlecase(@modality) +'
    from dbo.vw_RawData
    where vw.date >= ' + @datefrom + ''

exec sp_executesql @var1
  • You are trying to concatenate the smalldatetime with a varchar. Change

    Solution 1

    declare @datefrom smalldatetime
    

    to

    declare @datefrom varchar(8)
    

    and

    select @var1 = 'select sum('+ @modality +') as ' + dbo.fnc_titlecase(@modality) +
    ' from dbo.vw_RawData where vw.date >= ' + @datefrom + ''
    

    to

    select @var1 = 'select sum('+ @modality +') as ' + dbo.fnc_titlecase(@modality) +
    ' from dbo.vw_RawData where vw.date >= ''' + @datefrom + ''''
    

    Solution 2

    change

    select @var1 = 'select sum('+ @modality +') as ' + dbo.fnc_titlecase(@modality) +
    ' from dbo.vw_RawData where vw.date >= ' + @datefrom + ''
    

    to

    select @var1 = 'select sum('+ @modality +') as ' + dbo.fnc_titlecase(@modality) +
    ' from dbo.vw_RawData where vw.date >= ''' + convert(varchar(10), @datefrom, 121) + ''''
    
  • In the statement select @var1 = 'select sum('+ @modality +') as ' + dbo.fnc_titlecase(@modality) +' from dbo.vw_RawData where vw.date >= ' + @datefrom + '' SQL Server is trying to do date arithmetic by casting all the surrounding strings to a smalldatetime instead of converting @datefrom to a string and performing string concatenation.

    Possible fixes.

    • Change @DateFrom to a sting so that the concatenation works. Note you will have to add some quotes so that the string in @Var1 is properly formated.
    • Use convert function to convert @datefrom to a string. Look up the right conversion number in Books online. I don't have time to right now. Don't use cast, it won't give a
    • Use a paramertized SQL String. Look up sp_executesql in Books Online. (Or wait, StackOverflow always has someone to point out how to avoid dynamic SQL.)

    EDIT: Just checked. cast(@DateTime as Varchar(...)) gives a string that I thought might be hard to parse, but it seems to work, might try that instead of convert. Make sure the varchar() is big enough

MSRP vs FTP

What is difference between MSRP(Message Session Relay Protocol) protocol and FTP protocol ( in terms of transferring files)

  • What precisely do you mean by "operationally"?

    FTP is a protocol for transferring files over IP.

    MSRP is a protocol for sending instant messages.

    They are not at all alike. You might as well ask what the operational differences between dogs and TheTXI are.

    Pesto : Well, for one, most dogs aren't obsessively fixated on ponies.
    Welbog : @Pesto: One could say the same of FTP.
    From Welbog
  • I assume you're asking in terms of transferring files.

    ftp, or File Transfer Protocol, is designed for transferring files from a dedicated server.

    msrp, or Message Session Relay Protocol, is used for "transmitting a series of related instant messages". This can be used to transfer files to another user.

    The big difference I can see is that ftp requires a server, while msrp is user to user, or peer to peer.

    From pgs

About font appointment

I found this css

body {
font: 13px/1.231 arial,helvetica,clean,sans-serif;
*font-size: small;
*font: x-small;
}

What is 1.231?

  • The value 1.231 is the value for the line-height property (see the font shorthand property for further information). The number without a unit refers to the element’s font size.

    Prashant : yes that's the line-height property value, as given and explained here: http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/ For more explaination of font styling see this image: http://media2.smashingmagazine.com/images/clean-optimized-code/figureB.gif
    From Gumbo

How would you code Gmail's "Labels" text searchable checkbox list selection drop down control in ASP.NET/Ajax/JQuery?

I imagine having to interact with Gmail is a necessity for most programmers. Gmail's control for associating labels to emails is monumentally effective UI behavior.

For those unfamiliar with the behavior, it's basically a button-initiated pop up panel (drop down UI effect) containing:

1) a text entry box 2) scrollable multi-checkbox list and 3) a submit button.

...all neatly and tightly stacked on top of each other. This panel allows the user to type into the search box to control the items of the scrollable checkbox list in real time. Once all desired items are selected, the submit button initiates the server action.

I imagine the most challenging aspect would be getting the the text box control to govern which items are in the scrollable checkboxlist without having to hit the server (or ajax at most).

  • What I would do is to create a ASP.net server control and do the filtering with JavaScript. Since all of the items are displayed from the beginning, I thing there is no need for doing any Ajax call (it's not like autocompletion where it would make sense). The submit button would then be just a normal postback to the server as usual.

    For providing the real-time javascript filtering you could think of implementing a servercontrol that follows the databinding mechanism of .Net, accepting a datasource and providing an appropriate databind method. Maybe it would be convenient then to convert the passed data to some JSON format that can then be easily loaded and managed on the client-side by some appropriate JavaScript function.

    From Juri

Javascript for/in loops through properties, not indexes and returns strings.

Ok, I have this code:

var room = [ { time: 0, people: 0 } ];

and then:

time = 5;
for( var i in room ) {
  if( room[i].time < time ){
    spliceIndex = i + 1;
  }
}
console.log(spliceIndex);

And the console reads: 01 - Which means the 1 is concatenated which further means that i is a string, and not an integer as expected. Casting the index to integer fixed the problems, but I was banging my head for hours.... Can anyone explain why is this happening? I get this on Firefox 3.5 and Safari 4.

  • Because for-in lists object properties, not array indexes. Object properties are strings, and array indexes show up as properties, only they are numeric strings.

    Discodancer : :) nobody said that in the javascipt books i read. thanks.
    Matthew Crumley : That's why it's not a good idea to use a "for in" loop on arrays. They iterate over *all* the array's properties (except the built-in ones, which are non-enumerable), including string properties and properties inherited from Array.prototype.

PHP: Retrieving value of checkboxes when name doesn't have array

A form I don't have any control over is POSTing data to my PHP script. The form contains checkboxes along these lines:

<input type="checkbox" value="val1" name="option"/>
<input type="checkbox" value="val2" name="option"/>

If I were to write the code for the form, I'd write name="option[]" instead of name="option". But this is not a change I can do. Now, if both checkboxes are checked, $_POST["option"] returns just one of the values. How can I, in PHP retrieve all the values selected?

  • You can read the raw post data. For example:

    <fieldset>
        <legend>Data</legend>
        <?php
        $data = file_get_contents("php://input");
        echo $data."<br />";
        ?>
    </fieldset>
    
    <fieldset>
        <legend>Form</legend>
        <form method="post" action="formtest.php">
            <input type="checkbox" value="val1" name="option"/><br />
            <input type="checkbox" value="val2" name="option"/><br />
            <input type="submit" />
        </form>
    </fieldset>
    

    Check both boxes and the output will be:

    option=val1&option=val2
    

    Here's a live demo. All you have to do then is to parse the string yourself, into a suitable format. Here's an example of a function that does something like that:

    function parse($data)
    {
        $pairs = explode("&", $data);
        $keys = array();
        foreach ($pairs as $pair) {
            list($k,$v) = explode("=", $pair);
            if (array_key_exists($k, $keys)) {
                $keys[$k]++;
            } else {
                $keys[$k] = 1;
            }
        }
    
        $output = array();
        foreach ($pairs as $pair) {
            list($k,$v) = explode("=", $pair);
            if ($keys[$k] > 1) {
                if (!array_key_exists($k, $output)) {
                    $output[$k] = array($v);
                } else {
                    $output[$k][] = $v;
                }
            } else {
                $output[$k] = $v;
            }
        }
    
        return $output;
    }
    
    $data = "foo=bar&option=val1&option=val2";
    
    print_r(parse($data));
    

    Outputs:

    Array
    (
        [foo] => bar
        [option] => Array
            (
                [0] => val1
                [1] => val2
            )
    
    )
    

    There might be a few cases where this function doesn't work as expected though, so be careful.

    Ian Elliott : Nice, didn't know that
    Jani Hartikainen : Depending on your PHP settings you may not be able to use file_get_contents on the php://input stream. In this case, you will need to use fopen('php://input', 'r') and stream_get_contents($fp)
    chendral : What PHP settings would that be?
    From Emil H
  • Thaks for the great explanation :) You people are sooo good..