Friday, April 15, 2011

Java bean machine

Here is what I'm suppose to accomplish:

Write a program that stimulates a bean machine Your program should prompt the user to enter the number of balls and the number of slots in the machine. Simulate the falling of each ball by printing its path.

EX.


Enter the number of balls: 5
Enter the number of slots: 7


LRLRLRL
RRLRLLL
LLRRLLR
LRLLRLR
RRRLRRL
_ _ 0
_ _ 0
0 0 0

Here is my code so far:

import javax.swing.JOptionPane;        
public static void main(String[] args) {
            int balls=0;
            int slots=0;
            char [] direction= new char [slots];
            int slot=0;
            int i=0;
            int path=0;

            balls= Integer.parseInt(JOptionPane.showInputDialog("Enter" +
                    " the number of balls to be dropped:"));
            slots= Integer.parseInt (JOptionPane.showInputDialog("Enter " +
                    "the number of slots:"));

            for (int j=1;j<=balls;j++){
                while(i<slots){
                    path= (int)(Math.random()*100);
                    if (path <50){
                        direction [slots]='L';
                    }
                    else{
                        direction [slots]='R';
                    }
                i++;
                slot++;
            }
            System.out.println("The pathway is" +direction[0]+direction[1]+direction[2]+direction[3]+direction[4]);

       }
    }


There are a few things that I'm having problems with:

  1. In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?

  2. How can I print the number 'balls' that the user entered in the pattern as shown above?

  3. Are there any other problems with my code?

From stackoverflow
  • Well, for starters, I'm getting a consistent ArrayIndexOutOfBoundsException on the line direction[slots] = 'L'; (or 'R'). That's because direction is always of length 0, since you initialized it to slots when slots was 0. Move the line

    char [] direction= new char [slots];
    

    to after slots is input.

    Next, you always assign the 'L' or 'R' to the position immediately after the end of the array. That's another reason for the ArrayIndexOutOfBoundsException I was getting. Change the assignment to

    direction[i] = 'L'; // or 'R'
    

    Next, you don't reset i after the while loop. So the path is calculated only for the first ball and then reused for all the others. I would make it a for loop instead, like this:

    for (i = 0; i < slots; i++) {
        // your code here (make sure you don't change i inside the loop)
    }
    

    Finally, as others have said, you should be using a loop to print out the path. You know how long the direction array is (it's direction.length, if you didn't know), so you can just loop through it and print out each letter.

    Once you've made these changes, your program should work (edit: except that it doesn't keep track of which slot each ball ends up in). It will still have some room for improvement, but finding those things is part of the fun--isn't it?

    에이바 : Thanks for your help I'm working on fixing it right now.
  • In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?

    Use a for loop, and System.out.print() so you don't get a new line after each step.

    How can I print the number 'balls' that the user entered in the pattern as shown above?

    For each slot, you need to record the number of balls which ended up in that slot, and the maximum for any slot. Given these two values, you can loop over each slot, and print '_' or '0' the appropriate number of times with a nested loop.

    Are there any other problems with my code?

    You only appear to be printing the path of the last ball dropped, rather than each ball, but that might just be your indentation being squiffy. Post properly formatted, complete code.

    The example output you have seems to be reading input from the console, not using swing.

    You're declaring variables too early. It's better to declared variables on first use, and if they don't change mark them final. If you had:

    final int slots= Integer.parseInt (...
    

    instead of

    int slots = 0;
    ...
    slots= Integer.parseInt (...
    

    then at least one of your bugs would be caught by the compiler.

  • Some answers:

    1. Think for loop again. System.out.print or System.out.printf will help.
    2. System.out.println("Number of balls: "+ something that makes an int into a string (what would that be?)
    3. Why are you putting the result of Math.random() into an int? What would happen if you used:

      if(Math.random() < 0.5) { // do something
      } else { // do the opposite
      }

asp.net thread monitoring from another page

In asp.net 2.0 , c#.

Is it possible to start a thread from a page, for example when a asp:button is clicked and from another page, check if that thread has exited?

Reason: We have a page that starts a long server-side script when a button is clicked. However, since we don't want to wait the ending of the script on that page, we thought about creating a thread that executes the script, then get the thread ID and redirect the user on a 'Please wait' page that refresh check every 5 seconds to check if the thread has exited.

Any better idea on how to achieve that?

Thank you!

From stackoverflow
  • This can be done, but I would use Ajax to make the experience better, however.

    Basically, you would call your method and it would return the identifier for the thread. It doesn't have to be the thread id, but you need some sort of unique identifier that can be passed between pages/calls.

    Before you return from that call/page, you would execute your thread.

    Then, when your client checks on the status, it would check the session, or some other shared state, which would have the result keyed on the id you returned earlier.

    If it finds a value corresponding to the key, then it displays the result (and removes the result from the shared state), otherwise, it checks again in a specified period of time.

  • There is already an approach built into ASP.NET to do this sort of thing - it is the Asynchronous page model. There are 2 ways that this can be implemented and you can find details on them here with all the benefits explained.

mysqldb on python 2.6

I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6?

From stackoverflow
  • You can try this mysql package, which has a 2.6 version:

    http://pypi.python.org/pypi/MySQL-python/

    PierrOz : is there a package for windows ?
    Manzabar : The page coonj linked to indicates there is. You should be able to install the package using easy_install. Go to http://peak.telecommunity.com/DevCenter/EasyInstall for details on using easy_install.
    Therms : No it doesnt. There are only linux packages there.
  • There are versions of mysqldb for python 2.6, they're just not available on the official site. It took me a while (and unfortunately I lost the link) but you can search google and find people who have compiled and released 2.6 versions of mysqldb for windows x64 and x32.

    EDIT:

    http://sourceforge.net/forum/forum.php?thread_id=3108914&forum_id=70460

    http://sourceforge.net/forum/forum.php?thread_id=2316047&forum_id=70460

    That fourm has a link to versions of mysqldb for Python 2.6

    flybywire : The links take to http://www.thescotties.com/mysql-python/test/MySQL-python-1.2.3c1.win32-py2.6.exe which I tried and was satisfied with on 29th Nov 09
  • This one has both 32 and 64 versions for 2.6:
    http://www.codegood.com/archives/4

C#: Accessing Inherited Private Instance Members Through Reflection

I am an absolute novice at reflection in C#. I want to use reflection to access all of private fields in a class, including those which are inherited.

I have succeeded in accessing all private fields excluding those which are inherited, as well as all of the public and protected inherited fields. However, I have not been able to access the private, inherited fields. The following example illustrates:

class A
{
    private string a;
    public string c;
    protected string d;
}

class B : A
{
    private string b;
}

class test
{
    public static void Main(string[] Args)
    {
        B b = new B();       
        Type t;
        t = b.GetType();
        FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic
                                         | BindingFlags.Instance); 
        foreach(FieldInfo fi in fields){
             Console.WriteLine(fi.Name);
        }
        Console.ReadLine();
    }
}

This fails to find the field B.a.

Is it even possible to accomplish this? The obvious solution would be to convert the private, inherited fields to protected fields. This, however, is out of my control at the moment.

From stackoverflow
  • You can't access the private fields of A using the type of B because those fields don't exist in B - they only exist in A. You either need to specify the type of A directly, or retrieve it via other means (such as getting the base class from the type of B).

    Timwi : Rubbish, of course they exist in B. If they weren't in B, how could a method inherited from A that accesses such a private field work?
    Andy : The instance of B may have A's private members, but the Type of B has no knowledge of such members.
  • I haven't tried it, but you should be able to access the base type private members through the Type.BaseType property and recursively accumulate all the private fields through the inheritence hierarchy.

  • As Lee stated, you can do this with recursion.

    private static void FindFields(ICollection<FieldInfo> fields, Type t) {
     var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
    
     foreach (var field in t.GetFields(flags)) {
      // Ignore inherited fields.
      if (field.DeclaringType == t)
       fields.Add(field);
     }
    
     var baseType = t.BaseType;
     if (baseType != null)
      FindFields(fields, baseType);
    }
    
    public static void Main() {
     var fields = new Collection<FieldInfo>();
     FindFields(fields, typeof(B));
     foreach (FieldInfo fi in fields)
      Console.WriteLine(fi.DeclaringType.Name + " - " + fi.Name);
    }
    
    Timwi : Instead of the "if" clause to ignore inherited fields, you could just specify BindingFlags.DeclaredOnly.
  • You can access private members of Class A from Class B with 'Nested Classes' . You make Class A as Outer Class and Class B as Inner Class

    Class A { ... Class B { ....... }

    }

    Odrade : I'm not able to modify the classes. I'm just trying to garner info about them via reflection.

Why does an SWT Composite sometimes require a call to resize() to layout correctly?

Sometimes we encounter an SWT composite that absolutely refuses to lay itself out correctly. Often we encounter this when we have called dispose on a composite, and then replaced it with another; although it does not seem to be strictly limited to this case.

When we run into this problem, about 50% of the time, we can call pack() and layout() on the offending composite, and all will be well. About 50% of the time, though, we have to do this:

Point p = c.getSize();
c.setSize(p.x+1, p.y+1);
c.setSize(p);

We've had this happen with just about every combination of layout managers and such.

I wish I had a nice, simple, reproduceable case, but I don't. I'm hoping that someone will recognize this problem and say, "Well, duh, you're missing xyz...."

From stackoverflow
  • Looks to me like the layout's cache is outdated and needs to be refreshed.

    Layouts in SWT support caches, and will usually cache preferred sizes of the Controls, or whatever they like to cache:

    public abstract class Layout {
        protected abstract Point computeSize (Composite composite, int wHint, int hHint, boolean flushCache);
        protected boolean flushCache (Control control) {...}
        protected abstract void layout (Composite composite, boolean flushCache);
    }
    

    I'm relatively new to SWT programming (former Swing programmer), but encountered similar situations in which the layout wasn't properly updated. I was usually able to resolve them using the other layout methods that will also cause the layout to flush its cache:

    layout(boolean changed)
    
    layout(boolean changed, boolean allChildren)
    

    Hope that helps...

    Jared : +1 and accepted. Wish I could +10 this one :P
  • A composite's layout is responsible for laying out the children of that composite. So if the composite's size does not change, but the relative positions and sizes of the children need to be updated, you call layout() on the composite. If, however, the size or position of the composite itself needs to be updated, you will have to call layout() on its parent composite (and so on, until you reach the shell).

    A rule of thumb: If you have added or removed a control, or otherwise done something that requires a relayout, walk up the widget hierarchy until you find a composite with scrollbars and call layout() on it. The reason for stopping at the composite with scrollbars is that its size will not change in response to the change - its scrollbars will "absorb" that.

    Note that if the change requiring a layout is not a new child, or a removed child, you should call Composite.changed(new Control[] {changedControl}) before calling layout.

  • In the meantime I learned a little more about SWT's shortcomings when changing or resizing parts of the control hierarchy at runtime. ScrolledComposites and ExpandBars need also to be updated explicitely when the should adapt their minimal or preferred content sizes.

    I wrote a little helper method that revalidates the layout of a control hierarchy for a control that has changed:

    public static void revalidateLayout (Control control) {
    
     Control c = control;
     do {
      if (c instanceof ExpandBar) {
       ExpandBar expandBar = (ExpandBar) c;
       for (ExpandItem expandItem : expandBar.getItems()) {
        expandItem
         .setHeight(expandItem.getControl().computeSize(expandBar.getSize().x, SWT.DEFAULT, true).y);
       }
      }
      c = c.getParent();
    
     } while (c != null && c.getParent() != null && !(c instanceof ScrolledComposite));
    
     if (c instanceof ScrolledComposite) {
      ScrolledComposite scrolledComposite = (ScrolledComposite) c;
      if (scrolledComposite.getExpandHorizontal() || scrolledComposite.getExpandVertical()) {
       scrolledComposite
        .setMinSize(scrolledComposite.getContent().computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
      } else {
       scrolledComposite.getContent().pack(true);
      }
     }
     if (c instanceof Composite) {
      Composite composite = (Composite) c;
      composite.layout(true, true);
     }
    }
    
    Jared : Yeah - I've had to do that before - it's a pain. It wouldn't hurt to phrase this as a separate question and answer, for searchability's sake.

Problem injecting a VB parameter into a stored procedure (FireBird)

Everyone here has always been such great help, either directly or indirectly. And it is with grand hope that this, yet again, rings true.

For clarification sakes, the Stored Procedure is running under FireBird and the VB is of the .NET variety

I have a stored procedure (excerpt below, important bit is the WHERE)

  select pn, pnm.description, si_number, entry_date, cmp_auto_key, 
  parts_flat_price,    labor_flat_price, misc_flat_price, woo_auto_key, 
  wwt_auto_key
  from parts_master pnm, wo_operation woo
 where pn like :i_pn || '%'
   and pnm.pnm_auto_key = woo.pnm_auto_key
  into :pn, :description, :work_order, :entry_date, :cmp, :parts_price,
       :labor_price, :misc_price, :woo, :wwt

I am trying to pass a parameter from a vb app, that uses the parameter I_PN, the code of which follows below (The variables for MyServer and MyPassword are determined form an earlier part of the code.)

    Try
        Dim FBConn As New FirebirdSql.Data.FirebirdClient.FbConnection()
        Dim FBCmd As FirebirdSql.Data.FirebirdClient.FbCommand

        Dim MyConnectionString As String
        MyConnectionString = _
        "datasource=" & MyServer & ";database=" & TextBox4.Text & "; & _
        user id=SYSDBA;password=" & MyPassword & ";initial catalog=;"

        FBConn = New FirebirdSql.Data.FirebirdClient. & _
        FbConnection(MyConnectionString)

        FBConn.Open()
        FBConn.CreateCommand.CommandType = CommandType.StoredProcedure

        FBCmd = New FirebirdSql.Data.FirebirdClient. & _
        FbCommand("WIP_COSTS", FBConn)

        FBCmd.CommandText = "WIP_COSTS"

        FBConn.CreateCommand.Parameters. & _
        Add("@I_PN", FirebirdSql.Data.FirebirdClient.FbDbType.Text). & _
        Value = TextBox1.Text

        Dim I_PN As Object = New Object()
        Me.WIP_COSTSTableAdapter.Fill(Me.WOCostDataSet.WIP_COSTS, @I_PN)
        FBConn.Close()
    Catch ex As System.Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try

When I execute the VB.App and try to run the program, I get the following Error:

Dynamic SQL Error
SQL Error Code = -206
Column Unknown
I_PN
At Line 1, column 29

And I can't quite put my finger on what the actual problem is. Meaning, I don't know if my logic is incorrect on the VB side, or, on the Stored Procedure.

Any coding that is included is kludged together from examples I have found with various bits of code found during long sojourns of GoogleFu.

As anyone with more than a month or two of experience (unlike me) with VB can attest with merely a glance - my code is probably pretty crappy and not well formed - certainly not elegant and most assuredly in operational. I am certainly entertaining all flavors of advice with open arms.

As usual, if you have further questions, I will answer them to the best of my ability.

Thanks again.

Jasoomian

From stackoverflow
  • Can you show entire stored procedure here? What version of Firebird do you use?

  • Try changing this:

    FBConn.CreateCommand.Parameters. & _
            Add("@I_PN", FirebirdSql.Data.FirebirdClient.FbDbType.Text). & _
            Value = TextBox1.Text
    

    ... to this:

    FBCmd.Parameters.AddWithValue("@I_PN", TextBox1.Text)
    

    Basically, you want to add stored procedure parameters to the Command object, not the Connection object.

    Jasoomian : HardCode - still no joy. Still receiving the same error at run time.
    HardCode : I don't know the syntax of Firebird's SPs, but this statement - where pn like :i_pn || '%' - looks like it is saying "LIKE the parameter OR %" - instead of - "LIKE the parameter concatenated with %". Should it maybe be "where pn like :i_pn + '%'"
    Jasoomian : In Firebird, the || is the concatenation character, so, the code is already doing what you suggested (at least in that manner.)
  • Andreik,

    Here is the entire stored Procedure. And our Firebird is Version 1.5.3, written with IbExpert version 2006.12.13, Dialect 3

    Begin
    For
    select pn, pnm.description, si_number, entry_date, cmp_auto_key, parts_flat_price,
           labor_flat_price, misc_flat_price, woo_auto_key, wwt_auto_key
      from parts_master pnm, wo_operation woo
     where pn like :i_pn || '%'
       and pnm.pnm_auto_key = woo.pnm_auto_key
      into :pn, :description, :work_order, :entry_date, :cmp, :parts_price,
           :labor_price, :misc_price, :woo, :wwt
    
    Do begin
       labor_hours = null;
       work_type = null;
       parts_cost = null;
       labor_cost = null;
       ro_cost = null;
       customer = null;
    
       select company_name
         from companies
        where cmp_auto_key = :cmp
         into :customer;
    
       select work_type
         from wo_work_type
        where wwt_auto_key = :wwt
         into :work_type;
    
       select sum(sti.qty*stm.unit_cost)
         from stock_ti sti, stock stm, wo_bom wob
        where sti.wob_auto_key = wob.wob_auto_key
          and sti.stm_auto_key = stm.stm_auto_key
          and wob.woo_auto_key = :woo
          and sti.ti_type = 'I'
          and wob.activity <> 'Work Order'
          and wob.activity <> 'Repair'
         into :parts_cost;
    
       select sum(sti.qty*stm.unit_cost)
         from stock_ti sti, stock stm, wo_bom wob
        where sti.wob_auto_key = wob.wob_auto_key
          and sti.stm_auto_key = stm.stm_auto_key
          and wob.woo_auto_key = :woo
          and sti.ti_type = 'I'
          and wob.activity = 'Repair'
         into :ro_cost;
    
       select sum(wtl.hours*(wtl.fixed_overhead+wtl.variable_overhead+wtl.burden_rate)),
              sum(wtl.hours)
         from wo_task_labor wtl, wo_task wot
        where wtl.wot_auto_key = wot.wot_auto_key
          and wot.woo_auto_key = :woo
         into :labor_cost, :labor_hours;
    
       suspend;
       end
    End
    

    Hardcode - I responded in the comments to your suggestion.

  • After a little rethinking and a bit more research, I finally got my code working..

            Try
    
            ' Code for checking server location and required credentials
    
            Dim FBConn As FbConnection
            ' Dim FBAdapter As FbDataAdapter
            Dim MyConnectionString As String
    
            MyConnectionString = "datasource=" _
                            & MyServer & ";database=" _
                            & TextBox4.Text & ";user id=SYSDBA;password=" _
                            & MyPassword & ";initial catalog=;Charset=NONE"
    
            FBConn = New FbConnection(MyConnectionString)
            Dim FBCmd As New FbCommand("WIP_COSTS", FBConn)
    
            FBCmd.CommandType = CommandType.StoredProcedure
            FBCmd.Parameters.Add("@I_PN", FbDbType.VarChar, 40)
            FBCmd.Parameters("@I_PN").Value = TextBox1.Text.ToUpper
    
    
            Dim FBadapter As New FbDataAdapter(FBCmd)
            Dim dsResult As New DataSet
            FBadapter.Fill(dsResult)
    
            Me.WIP_COSTSDataGridView.DataSource = dsResult.Tables(0)
    
            Dim RecordCount As Integer
            RecordCount = Me.WIP_COSTSDataGridView.RowCount
            Label4.Text = RecordCount
    
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show _
            ("There was an error in generating the DataStream, " & _
            "please check the system credentials and try again. " &_ 
            "If the problem persists please contact your friendly " &_ 
            "local IT department.")
        End Try
    
        ' // end of line
    

    I had also thought that I would need to make changes to the actual stored procedure, but, this turned out to be incorrect.

    The code may not be pretty, and I need to do more work in my TRY block for better error handling; but, it works.

    Thanks to all who chimed in and helped me get on track.

    J

ASP.NET MVC jQueryUI datepicker not working when using AJAX.BeginForm

I have an ASP.NET MVC Partial View that contains a Html.TextBox that is configured to use the datepicker from JQueryUI. This is done by ensuring the style is set to .datepicker. This all worked fine. However I have changed my forms to Ajax.BeginForm and included a Ajax.ActionLink that displays it after clicking on the link. Since adding this the datepicker does not display. In fact no JavaScript that previously worked is now even being invoked after a returning a partialview from the controller. Even if i PUT THE JavaScript/JQuery in the partial view itself it still does not use it. I really am confused, can someone please help?

Examples shown below

<div id="claims">
        <div id="divViewClaims">
            <% Html.RenderPartial("ViewClaim", Model.Claims ?? null); %>
        </div>
        <br /><br />
        <div id="claim">
            <% Html.RenderPartial("AddEditClaim", new Claim()); %>          
        </div>
    </div>

Action Link, when clickon calls Controller Action to return PartialView, The JavaScript called on the OnSuccess fires but nothing else, that previously was hooked up by the document.ready function. All my scripts are in seperate files and referenced in master page.

<%= Ajax.ActionLink(string.Format("Add A{0} Claim", Model.Count > 0 ? "nother" : string.Empty), "AddClaim", "Driver", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "claim", OnSuccess="showAddClaim" }, new { @class = "ControlLink" })%>

Controller Action

public ActionResult AddClaim()
{
      return PartialView("AddEditClaim", new Claim());
}

Partial View, which shows the textbox with the style set to datepicker

<% var ajaxOptions = new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divViewClaims", InsertionMode = InsertionMode.Replace, OnSuccess="hideAddClaim" }; %>
        <% using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { @name = "ClaimControl", @id = "ClaimControl" }))
           { %>

    <fieldset>  
        <legend><%= Model.Id==0?"Add":"Edit" %> Claim</legend> 
        <p>
            <label for="Title">Claim Date</label>
            <%= Html.TextBox("Date", Model.Date.ToString().TrimEnd('0', ':', ' ') ?? "", new { @class = "datepicker" })%>  
        </p>

I appreciate any help on this.

From stackoverflow
  • If the element is created after document.ready you should re-match the element to jQuery.

    Check out jQuery Live

  • I know it's bit too late to answer this ;), but what works for me is to use the OnSuccess property from the AjaxOptions. So, your code could be like this:

    using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { @name = "ClaimControl", @id = "ClaimControl", OnSuccess="the_javascript_function_below" })
    

    where the_javascript_function is the name of a function that does this:

    $(".datepicker").datepicker();