Wednesday, March 23, 2011

grid view combobox

how to add items to a data grid view combo box

From stackoverflow
  • Hi Sara.

    You have a very good example here. Basically, the combobox is created and populated independently from the data binding.

    This is a very generic question. If you're having more specific problems please let us know.

To upload an excel file as a clob

Could some one give an idea about how to convert an excel file into a CLOB in oracle through JDBC. I would like to know how to covert excel file into a String using API available as part of JDK and the conversion from string to clob should be straight forward. Thanks in advance. If a similar question was already raised, kindly provide me the link.

From stackoverflow
  • You will need a library out side of the standard java api to read a binary excel document.

    You could use the JExcelApi to read in the Excel document then create a CSV String as you read in the document.

    If you don't want to use an outside library then I would change the field type to blob and use the setBlob method of java.sql.PreparedStatment passing it a FileInputStream.

  • When you need to parse the data (read the contents) you can use a library like Apache POI

    If you want to use the only standard API, then save the excel as CSV file and process the file as a comma seperated value list. That can easily be done with readline to read each line and split that line to values using the split method on a String.

    If you do not need to parse data you should stream the data directly from file to a CLOB and not first transform the excel to a String An example can be found here: http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/advanced/LOBSample/LOBSample.java.html

local git check-ins -- hide from main repository?

I thought I remembered reading somewhere a way to do this, but I can't find it.

I'm working locally, on a local branch even, and I'm checking in as needed, or daily or whatever. When I get the code to the point where I want to push it to the main repository, is there a way to just push the file as is, and not push all of the history? Or when I merge from a branch back to main, can I not merge the history?

Are these even good ideas? Thanks for the help -- still learning, here!

joe

From stackoverflow
  • You could merge your changes as a single commit on the main branch:

    $ git checkout main
    $ git merge --squash local
    

    That discards all of your local history, of course. All in all that is not something I would do. Instead, if you’re worried about embarrassing or compromising commits in your local history, use git rebase to rewrite your local history; afterward, perform a normal merge and push out your cleaned-up local history as well.

    Edit/clarification: an interactive rebase will allow you to easily remove or "squash" commits in your history:

    $ git checkout local
    $ git rebase -i main
    

Adding ORDER BY clause to MySQL query makes it return in ~30 seconds, up from ~0.5

So I have this query that is relatively fast at ~0.5 seconds but when I add an ORDER BY clause it jumps up to nearly 30 seconds.

Original query: (returns in ~0.5 seconds)

SELECT table1.*,table2.* FROM table1 LEFT OUTER JOIN table2 ON table1.column2=table2.column3 WHERE table1.column1='value' LIMIT 4

Query with ORDER BY: (returns in ~30 seconds)

SELECT table1.*,table2.* FROM table1 LEFT OUTER JOIN table2 ON table1.column2=table2.column3 WHERE table1.column1='value' ORDER BY table1.column4 DESC LIMIT 4

Note I added an index to the column that is being used by the ORDER BY and it changed nothing.

Any ideas as to what would be causing this?

From stackoverflow
  • This takes longer because the query can't just pick the first 4 items it finds. It has to order the entire list and then choose the top 4 from that.

    Fix this by adding an index which includes table1{column4, ...}. If you only need a few columns from table 1 (and they're narrow), I'd add them all to the index (covering index).

    If indexed properly, the SQL engine can pull just the first four columns that you want--not the entire set.

    If you do have indexing and it's not helping, run the query with EXPLAIN to see what the execution plan looks like (good tip, @IronGoofy):

    EXPLAIN 
      SELECT table1.*,table2.* 
      FROM table1 
      LEFT OUTER JOIN table2 ON table1.column2=table2.column3 
      WHERE table1.column1='value' ORDER BY table1.column4 DESC LIMIT 4
    
  • How are you running the query?

    It is common for some tools to retrieve only the first 100 or so records, and pull down more as needed.

    Adding the ORDER BY forces the tool to retrieve the ENTIRE dataset.

    If you are in MySql browser, try running w/o the ORDER BY, and then use CTRL-END to scroll to the bottom of the datagrid. How long does that take?

  • Is table1.column1 indexed? If yes, then the query optimizer will use that index to select the initial set of rows from table1, since it's at worst an index range scan (very fast).

    If this query is one that's run frequently, you may get the performance you want by indexing on (column1,column4). I don't know MySQL very well, but with Oracle you could boost performance even more by indexing (column1,column4,column2), which would make the optimizer do all of its work from the index, and not touch table data at all.

    However, adding indexes is a tradeoff: it will increase the time taken by every insert (or update of the indexed columns), makes your database larger, and may cause an overall slowdown as scarce memory resources (ie, buffer cache) get assigned to the new index.

    Michael Haren : You are right for *EXCESSIVE* indexing. Normal indexing tends to help with selects AND updates/deletes (the record must be found before it can be updated/deleted). I've yet to find a case where I had a reasonable set of indexes on a table and they were found to be hurting performance.
    kdgregory : I've worked on applications that were extremely write-intensive. We gave a great deal of thought before adding indexes, and often made per-customer recommendations (based on that customer's particular usage patterns). My point is that "reasonable" depends on the situation.
    kdgregory : (contd) And more importantly, when doing database physical design, you have to keep in mind the tradeoffs that each decision entails.
    Michael Haren : I'll grant you that--a write-heavy/read-light system does often require a very different db strategy.
  • Concur with Michael's explanation, +1.

    As to the index not making a difference, have a look at the execution plan (not sure how to do that in MySQL - maybe someone can edit this in?). Again, I agree with Michael that this should make things faster (as long as column4 is "selective").

    @kogus: retrieving the whole resultset to the client is not the same as ordering the resultset, the ordering should take place on the server without the need to transfer all results over the network

    Michael Haren : +1-- looking at the query plan is extremely helpful
  • Try running explain:

    EXPLAIN SELECT table1.*,table2.* FROM table1 LEFT OUTER JOIN table2 ON table1.column2=table2.column3 WHERE table1.column1='value' ORDER BY table1.column4 DESC LIMIT 4
    

    This will probably tell you MySQL is doing a filesort. Can you put an index on (column1, column4)?

    Can you tell something more about your model? What indexes are you using? Can you show some explain output? What kind of types are using for the fields?

  • Agreed on the index stuff mentioned by Michael.

    Additionally, in MySQL, you can learn a lot about the performance your query will have by examining the results of prepending EXPLAIN to your query, e.g.

    EXPLAIN SELECT * FROM foo_tbl WHERE foobar = 'foo'
    

    will help you design your queries better, and index appropriately. Read up on EXPLAIN syntax and Optimizing queries with EXPLAIN.

Risk Management: Current & Future Development in Software Development

Hi, Am new to Software Project Management and currently doing some research on Risk Management in S'ware Development. Just interested in knowing what are the current methods applied and any future trends to come. Thnx

From stackoverflow
  • A popular method used by many project managers of my acquaintance is to ensure that every risk is written down as accurately and fully as possible in a RISK LOG and then stored in a sharepoint document library never to be seen again except perhaps briefly as they float out of the effluent pipe and drift on out to sea.

  • thnx, that was helpful. what about the future, any new things coming out. How is it incorporated in Agile.

  • There are so many Risks associated with the average software project that any "risk management strategy" is at best window dressing and at worse gives a false sense of well being.

    For some time now I have been convinced that (as there are relatively much fewer of them!) its much better to concentrate on the factors that will make a project a success.

    • Does the business really want/need it -- is your project sponser sane?
    • The right people -- do you have good developers with the right attitude?
    • Clear and sensible requirments -- does the project brief make sense to you?
    • Tight Schedules -- is the project due for delivery in the next twelve months?
    • Acheivable Schedules -- is it possible to deliver within the next twelve months?
    • Is it based on standard proven technoligy -- not just the latest buzzwordware?

    If the answer to any of the above questions in "no" then you may as well can the project now and save everybodys time and money.

    They are all equally important, but the timescale one is often neglected. Most projects which take longer than 18 months will be cancelled before completion, regardless of the excellence of the team or the implementation. The requirments will change, the business will run out of money, the management strategy will change, you will be taken over by a competitor etc. etc. a lot can happen in eighteen months.

    Alice_I_W : thats true but isn't it better to expose the 'risks' and be prepared than burying them. I think a project should have both a cautious and optimistic approach. So wouldn't risk management be an integral and ongoing part of the process.
    James Anderson : I know its sensible to keep a Risk log etc. But I have seen projects maintain nice long Risk registers which didnt mention the one obvious fact -- the project team were incapable of delivering the goods.
    Etamar L. : I have to agree with the critics on this answer: it does not serve a project well to bury the risks and concentrate on success factors. We concentrate on them anyway, because the successful factors are what we build into the software. Assessing risks helps you know where to concentrate and put resources on.
  • We use risk management fairly heavily. For us, it's a way to document communication up the internal food chain, mostly about external difficulties. We have a formal in-house, self-made web tool that lets us:

    • document the risk as an if/then statement
    • note the anticipated impact in terms of cost, schedule and quality
    • create mitigations - general strategies for coping with the risk. Ignoring is an acceptable strategy if the anticipated impact and probability are low enough.
    • create actions - documentation of concrete action to prevent the risk that have already been taken

    The risks, mitigations and actions are then updated and reviewed at Engineering Status Meetings (ESR) every other month. If something goes really off the rails on the project, the ESRs get more frequent as management "helps".

    The risks are proposed by the front-line managers - in our project, that's me - the software task manager. We're the ones who see something that could potentially derail our ability to complete on time. Then our project management and engineering management see it.

    I found it was a pretty good venue for getting management help for external factors. Risks have included:

    • Critical problems with tools supported by our IT department that aren't getting addressed in a timely manner
    • Problems with other components on other contracts with which we integrate
    • Problems with not getting a key deliverable from our customer
    • Areas of profound technical uncertainty - they can't always be fixed, but at least management knows that there's some stuff we're dealing with.

    Risks stay in the database forever, so they serve as a historical documentation that something was brought to managements attention. At the very least, they are a CYA (cover your a**) procedure - but with our management, they are also a tool for working together to fix a problem. - often with the assistance of upper management leverage. Several of the attendees at ESRs are people with some vast experience at managing technical teams, who tend to be able to offer good suggestions.

    There is definitely some political savvy required. For us, it has to be technical - but you don't want to highlight problems with individual people. Unless you want to highlight a lack of people or a lack of people with sufficient experience/knowledge. My preference is to keep it externally focused most of the time, and manage the team problems personally and quietly with limited help from my managment.

Emacs Command to Delete Up to Non-Whitespace Character

I often want to make a multiline function call and reduce it down to one line. For example, convert...

function_call(
     'first_arg',
     'second')

to

function_call('first_arg', 'second')

Does emacs have some commands to help with this. Specifically, is there a command that will delete all whitespace from the point to the first non-whitespace character?

From stackoverflow
  • Alt-space will reduce a string of whitespace to a single space character, but it won't delete the newline. Still, that should help a little.

    To delete everything from point to the first non-whitespace (or newline), type a non-whitespace char, Alt-space, backspace (to remove final whitespace char), then backspace (to delete the char you added.

    To turn the multi-line function declaration into a single-line declaration, use a combination of Alt-space, backspace, and Alt-E (goto-endofline) commands.

  • Take a look at the fixup-whitespace function. It comes with Emacs, in simple.el. Its docs are:

    Fixup white space between objects around point. Leave one space or none, according to the context.

    This function is typically bound to M-Space.

    Chris Conway : M-SPACE is "just-one-space" not "fixup-whitespace". They seem to do pretty much the same thing, though.
  • You might try delete-indentation, my favorite command for joining multiple lines into one line. In your example, put the cursor on the line with "second" and hit M-^ twice. Here are the docs:

    M-^ runs the command delete-indentation, which is an interactive compiled Lisp function in `simple.el'.

    It is bound to M-^.

    (delete-indentation &optional arg)

    Join this line to previous and fix up whitespace at join. If there is a fill prefix, delete it from the beginning of this line. With argument, join this line to following line.

  • You can always use M-z to delete upto a character.

    For eg in your case:

    M-z ' to delete upto the single quote (unfortunately this will delete the single quote as well, but that is a minor inconvenience).

  • I do this:

    (defun move-line-up ()
      "Removes leading spaces from the current line, and then moves
    the current line to the end of the previous line."
      (interactive)
      (let (start end)
        (save-excursion
          (beginning-of-line)
          ; get first non-space character, only look on this line
          (let ((search-end (save-excursion (end-of-line) (point))))
            (re-search-forward "[^[:space:]]" search-end))
          (setq end (1- (point)))
          (previous-line)
          (end-of-line)
          (setq start (point))
          (delete-region start end))
        (goto-char start)))
    
    (defun move-next-line-up ()
      "Moves the next line to the end of the current line"
      (interactive)
      (next-line)
      (move-line-up))
    

    And bind these as:

    (global-set-key (kbd "C-x ,") 'move-line-up)
    (global-set-key (kbd "C-x .") 'move-next-line-up)
    

    So to solve your problem, on the line that says "second)", just run C-x , C-x ,

  • Specifically, is there a command that will delete all whitespace from the point to the first non-whitespace character?

    There's a command that does almost that:

    M-\ runs the command delete-horizontal-space which is an interactive compiled Lisp function in `simple.el'.

    It is bound to M-\.

    (delete-horizontal-space &optional backward-only)

    Delete all spaces and tabs around point. If backward-only is non-nil, only delete them before point.

  • If you want all of your deletes to act that way, you might check out greedy-delete.

  • I use the following macro to "pull" the next line onto the end of the current line, compressing whitespace.

    (defun pull-next-line() 
      (interactive) 
      (move-end-of-line 1) 
      (kill-line)
      (just-one-space))
    

    This is exactly the opposite of @jrockway's move-line-up and of delete-indentation, which I find more natural. The just-one-space command in the macro is exactly @Mike's M-SPACE.

    I bind pull-next-line to M-J (in analogy with Vim's J, for "join", command) using the following in my .emacs.

    (global-set-key (kbd "M-J") 'pull-next-line)
    

    Example. Calling pull-next-line on the first line of

    function_call(
         'first_arg',
         'second')
    

    yields

    function_call( 'first_arg',
         'second')
    

    Calling it a second time yields

    function_call( 'first_arg', 'second')
    
  • A slightly different approach would be creating a keyboard macro to do the job for you. so, for creating the macro stage a general scenario like so:

    foo
    
    
                   bar
    

    [a line with "foo" then a couple of lines later and with some white spaces, write "bar"]

    then standing anywhere between foo and bar, do the following:

    C-x (                    ; start recording macro
    M-b                      ; move backwards to the beginning of foo
    END                      ; move to the end of foo
    C-space                  ; place mark
    C-M-f                    ; move to the end of bar
    HOME                     ; move to the beginning of the line
    C-w                      ; yank out all the white space
    M-SPACE                  ; leave only one space
    C-x )                    ; end recording the macro
    M-x name-last-kbd-macro  ; name it, call it jline or something 
    

    Now you can always remove all whitespace between two words with M-x one-line

    Make sure you remember to save your keyboard macro by issuing M-x insert-kbd-macro somewhere in your .emacs file - this is how it looks:

    (fset 'jline
       [?\M-b end ?\C-  ?\C-\M-f home ?\C-w escape ? ])
    
  • A rather drastic way of doing this is Hungry-Delete mode:

    Hungry-Delete is a minor-mode that causes deletion to delete all whitespace in the direction you are deleting.

Installing Capicom without SelfReg: Wix Custom Actions Not Found (Err 2721)

After following the advice in this question successfully, I added a couple additional lines of code for another custom action. This one is intended to call regsvr32 on the copy of capicom which I've tried to put in the user's system folder. However, I'm getting error 2721, which seems to be a custom action not found error, from what I've seen. Any suggestions? I'm trying to maintain consistency with previous iterations of my installer by calling regsvr, rather than just adding the registry entries during install, which could be a good idea instead. :::shrug:::

<Directory Id="SystemFolder" Name="Sys">
  ...
  <component ...>
     ...
    <File Id="CapiCom.Dll" LongName="CapiCom.Dll" Name="CAPICOM.DLL" Source=... />
  </component>
</directory>
...
<CustomAction Id="REGCAPICOM" ExeCommand='regsvr32.exe "[SystemFolder]capicom.dll"' Return = "ignore" Execute="deferred" />
...
<InstallExecuteSequence>
  ...
  <Custom Action="REGCAPICOM" After="InstallFiles" />
</InstallExecuteSequence>

Edit: Yes, using regsvr32 as an installer is ugly. But when I downloaded the Capicom SDK, that is what MS said to do in order to install it. Searching around has found many people saying that this is a stupid way to do it...but it's also mechanism MS provided. I'll listen to suggestions for a better way. I don't consider it a big deal if Capicom being left behind when my application is uninstalled, considering that it's a standard windows component.

Edit: Hmmm. Apparently, one of the things running selfreg on the dll does is to create a random seed to add to the registry. Not sure what mechanism it uses to generate this seed but I suspect it would be considered in poor taste to just generate one myself, especially if I gave all the users the same seed. Not sure.... Apparently if I skip this Capicom does it on its own, so I'm fine.

From stackoverflow
  • Uhh, are you really trying to install a Windows system file yourself? That's not allowed on a great many levels. Also, regsvr32.exe is SelfReg and SelfReg is well known to be evil in installations. Actually using the Windows Installer to write the registration is far superiour

    However, the whole design here is very suspect.

    Brian : Ach, I feel silly. I don't recall my original motivation for extracting capicom out of the msi, but you're right that it's a bad idea. I should just execute MS's msi for it instead. That said, I'm still curious what went wrong.
    Brian : Fair enough. I'll just following the installation instructions in MS's capicom redist: To install CAPICOM extract "CAPICOM.DLL" from CAPICOM.CAB to your system32 directory, then execute "regsvr32.exe CAPICOM.DLL" Heh
  • You could use heat on the File to create a output WXS file, that will put the capicom.dll information in the registry without the use of regsvr32, when the msi is executed

    Something like so:

    heat file [Path\Capicom.dll] -template:product -out capicom.wxs
    

    Then add the capicom.wxs to your installer, in that file create a ComponentGroup Element, that contains the Component(s) element(s):

    <ComponentGroup Id="capicom">
      <ComponentRef Id="capicom.dll"/>
    </ComponentGroup>
    

    After in the main WXS file add the Fragment element that will link the capicom component

    The last step is to add the ComponentGroupRef to the feature that it belongs to:

    <Feature Id="PRODUCTFEATURE">
      <ComponentGroupRef Id="capicom" />
      ... [Other components or ComponentGroups references]
    </Feature>
    
    Brian : Good idea, but it won't work. The file is showing up as expected, but it is not being registered properly. I tried manually running regsvr32 after installing and it worked.
  • The Right way:

    • c:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Tools\Deployment\regcap.exe" /O capicom.reg capicom.dll

    • Run program from Adam Tengen's post here.

    Note that Heat (and Tallow, IIRC) do not, as of this posting, work properly on Capicom.

    The Wrong Way:

    <CustomAction Id="RegisterCapicom" Directory="SystemFolder" ExeCommand="regsvr32.exe /s &quot;[SystemFolder]Capicom.dll&quot;" Return="check" Execute="deferred" />
    ...
    <InstallExecuteSequence>
      <Custom Action="RegisterCapicom" After="InstallFiles" />
    </InstallExecuteSequence>
    
    Brian : Yes, I know I could just set selfregcost instead.

SQL Server 2005: Transaction Deadlock

Hi ppl,

I am getting this error very frequently but not consistently on 2 pages in an application which is in a production environment. I just have some screen shots of the error below.

Transaction(Process ID XX) was deadlocked on lock | communication buffer resources with another process and has been chosen as a deadlock victim. Rerun the transaction.

What should the approach be to resolve this error. The db server is SQL Server 2005.

From stackoverflow
  • This article by Brad McGehee is a good place to start.

  • Here is the bible on deadlock troubleshooting:

    http://blogs.msdn.com/bartd/archive/2006/09/09/Deadlock-Troubleshooting_2C00_-Part-1.aspx

    Mitch Wheat : didn't you just answer another question with exactly the same answer?! :-)
    SQLMenace : That was in September, are you talking about this one? http://stackoverflow.com/questions/52566/mssql-server-2000-debugging-deadlocks#52594
  • See also here: Proactive Deadlock Notifications

    Mitch Wheat : I don't wish to seem negative but using the profiler deadlock events is the usual place to start in SQL Server 2005, rather than the trace flags.
  • You could do as the error message suggests and get the program to retry the transaction!

    Depends very much on how "atomic" the transaction is though! i.e. If you were deadlocked its likly that some other process has succesfully updated the row you are interested in. Does it still make sense to apply the update to the row in htese circumstances?

    At the very least present the user with a nicer error message ("Another user has changed the xxxx you were attempting to update. Please review the new values and try again.)

  • You need to run a Deadlock profile trace while the errors are occurring. The article by Brad McGehee is a overview. You need to identify the two offending processes. After that, review the code in the two pages to see what SQL commands are being issued and how often. Most of the time, I have found that simplying reviewing the SQL code being run and knowing how often it runs will qucikly identify the conflict. Fixing it sometimes takes longer...

Framework + Client Code references

Hi,

We are simultaniously working on a base-framework and on a implementation (little test tool) on top of it. There are several things I'd like, and I am wondering if they are all possible:

(.NET 3.5, VS2008)

  • Have a .sln with only the implementation (tool) - project
  • Have a .sln with tool + framework projects
  • Have a .sln with only framework projects

Have a build server (Team City) with 2 build configs: - Framework - Tool

Now while this can probably all work while referencing just .dll's between tool and framework, I would like to work on the framework from within the tool+framework solution, without being confronted with [Metadata] code files constantly.

Any tips?

From stackoverflow
  • Is that possible to join all projects in one big solution? You may have several .sln files referencing same .csproj(or whatever) files.

Algorithm to find subset within two sets of integers whose sums match

Hi,

I'm looking for an algorithm which can take two sets of integers (both positive and negative) and find subsets within each that have the same sum.

The problem is similar to the subset sum problem: http://en.wikipedia.org/wiki/Subset-sum_problem except that I'm looking for subsets on both sides.

Here's an example:

List A {4, 5, 9, 10, 1}

List B {21, 7, -4, 180}

So the only match here is: {10, 1, 4, 9} <=> {21, 7, -4}

Does anyone know if there are existing algorithms for this kinda problems?

So far, the only solution I have is a brute force approach which tries every combination but it performs in Exponential time and I've had to put a hard limit on the number of elements to consider to avoid it from taking too long.

The only other solution I can think of is to run a factorial on both lists and look for equalities there but that is still not very efficient and takes exponentially longer as the lists get bigger..

Any help will be much appreciated!

Thanks,

Yan

From stackoverflow
  • subset sum is Np-complete and you can polynomially reduce your problem to it, so your problem is NP-complete too.

    A. Rex : Perhaps you'd like to mention the reduction: if A and B are your sets for this problem, take A union (-B) in usual subset-sum and you're looking for sum 0.
  • Like the subset sum problem, this problem is weakly NP-complete, so it has a solution that runs in time polynomial(M), where M is the sum of all numbers appearing in the problem instance. You can achieve that with dynamic programming. For each set you can generate all possible sums by filling a 2-dimensional binary table, where "true" at (k,m) means that a subset sum m can be achieved by picking some elements from the first k elements of the set.

    You fill it iteratively - you set (k,m) to "true" if (k-1,m) is set to "true" (obviously, if you can get m from k-1 elements, you can get it from k elements by not picking the k-th) or if (k-1,m-d) is set to "true" where d is the value of k-th element in the set (the case where you pick the k-th element).

    Filling the table gets you all the possible sums in the last column (the one representing the whole set). Do this for both sets and find common sums. You can backtrack the actual subsets representing the solutions by reversing the process which you used to fill the tables.

    Binary Worrier : +1 mate. Bugger me, I had no idea. I have deleted my answer. Nice one :)
  • What others have said is true:

    1. This problem is NP-complete. An easy reduction is to usual subset-sum. You can show this by noting that a subset of A sums to a subset of B (not both empty) only if a non-empty subset of A union (-B) sums to zero.

    2. This problem is only weakly NP-complete, in that it's polynomial in the size of the numbers involved, but is conjectured to be exponential in their logarithms. This means that the problem is easier than the moniker "NP-complete" might suggest.

    3. You should use dynamic programming.

    So what am I contributing to this discussion? Well, code (in Perl):

    @a = qw(4 5 9 10 1);
    @b = qw(21 7 -4 180);
    %a = sums( @a );
    %b = sums( @b );
    for $m ( keys %a ) {
        print "sum(@{$a{$m}}) = sum(@{$b{$m}})\n" if exists $b{$m};
    }
    
    sub sums {
        my( @a ) = @_;
        return () unless @a;
        my $a = shift @a;
        my %a = ( $a => [$a] );
        while( @a ) {
         $a = shift @a;
         for my $m ( keys %a ) {
          $a{$m+$a} = [@{$a{$m}},$a];
         }
        }
        return %a;
    }
    

    It prints

    sum(4 5 9 10) = sum(21 7)
    sum(4 9 10 1) = sum(21 7 -4)
    

    so, notably, there is more than one solution that works in your original problem!

  • Hi guys,

    Thanks a lot for all the quick responses!

    The dynamic programming solution is not really different to the exhaustive approch we have right now and I guess if we need the optimal solution we do need to consider every possible combination but the time it takes to generate this exhaustive list of sums are too long.. Did a quick test and the time it takes to generate all possible sums for x number of elements very quickly go over 1 min:

    11 elements took - 0.015625 seconds
    12 elements took - 0.015625 seconds
    13 elements took - 0.046875 seconds
    14 elements took - 0.109375 seconds
    15 elements took - 0.171875 seconds
    16 elements took - 0.359375 seconds
    17 elements took - 0.765625 seconds
    18 elements took - 1.609375 seconds
    19 elements took - 3.40625 seconds
    20 elements took - 7.15625 seconds
    21 elements took - 14.96875 seconds
    22 elements took - 31.40625 seconds
    23 elements took - 65.875 seconds
    24 elements took - 135.953125 seconds
    25 elements took - 282.015625 seconds
    26 elements took - 586.140625 seconds
    27 elements took - 1250.421875 seconds
    28 elements took - 2552.53125 seconds
    29 elements took - 5264.34375 seconds
    

    which for the business problem we're trying to solve is not really acceptable.. I'm gonna go back to the drawing board and see whether we do indeed need to know all the solutions or can we just do with one (the smallest/largest subset, e.g.) instead and hopefully that can help simply the problem and make my algorithm perform to expectaion.

    Thanks all the same!

  • How the problem is solved. i too face the time issue when i use the perl code.

Defining Business Rules

I have been tasked to come up with a list of the Business rules in one of our current applications. We have a very old document that has somethings, but has not been maintained, and as such is very outdated and inaccurate.

In an attempt to do it better than before, and hopefully more useful I have been asking fellow developers what types of things should be in the document and what they consider a business rule. And apparently we all have a different definition. I read over this wikipedia article, and it confused me more.

What we are trying to accomplish is:

  • Complete list of business rules in our application to allow for easy review.
  • A place to find and lookup these rules, when we are working on something related to it. That way over time when we forget what the rule is a screen is supposedly implementing, we can refer to this document.

Where I get confused is how specific should business rules be. How far do you go?

Example: A screen has two fields, A and B. A is a code and B is the definition of that code. They are stored in the database as a row in some table.

Business Rule 1: When user enters code in field A, field B is auto populated with the corresponding definition.

or

Business Rule 2: Every A code has a single corresponding B definition.

So which is more correct?

From stackoverflow
  • Suggestion:

    Instead of saving the information inside a document which can outdate very quickly/easily I would suggest setting up a company wiki for maintaining the business rules.

    unforgiven3 : I second that. Wikis are great for that kind of thing.
    jschoen : Some of us are pushing for that, I am just not sure how practical the upper management will see that because of our enviroment. Thanks.
  • Option 2) is more correct because it is independent of how the codes were entered. Your option 1) describes a user interface "nicety", whereas 2) establishes a system wide fact - that assersion should be true regardless if a user is entering or another system is entering data.

    1. first and foremost, you must get whoever assigned you this task to define what he/she thinks is a "business rule"; otherwise you risk doing too much or not enough. What you listed as an example sounds like an application specification, not a list of business rules

    2. the remainder of this is my opinion, which may or may not be relevant (see #1) ;-)

    "rule 1" is a behavioral specification for the user-interface application, not a business rule. This could be done a different way without losing functionality, e.g. if the app had a droplist of code descriptions to choose from instead of entering a code

    "rule 2" is a data model constraint, not a business rule

    A business rule is a constraint for how the business operates that is distinct from a natural law, which governs how the world works. The distinction is that a natural law cannot change, while a business rule may change.

    A business rule about codes would govern how the code is used in relation to whatever is being coded. For example, suppose the code described something about a customer account (big, fat, lazy, deadbeat, whatever) and that processing of an order varied depending on the code assigned to the account: the rules for processing based on each code would be business rules.

    More examples:

    • F=Ma (force equals mass times acceleration) is a natural law
    • "new customers must have their PO orders approved by a credit manager" is a business rule
    • "two objects cannot occupy the same space" is a natural law
    • "a customer may only have two outstanding PO invoices at a time" is a business rule
  • How about "An A code alone is not completely descriptive. Every A code must be further defined by a B code."

    If some A codes only allow a subset of B codes you'd have to define that as well.

  • Have you consider documenting Use Cases of your exiting apps?

  • I would like to add to the already clear (accepted) answer provided by Steven that

    That way over time when we forget what the rule is a screen is supposedly implementing, we can refer to this document.

    business rules as such are never implemented, they are -as Steven pointed out- constraints.

    Screens do not implement business rules. Systems adhere to business rules.

    The purpose of archiving an inventory of business rules is not to document the existing software, but instead to document fundamental knowledge that will enable to replace the whole system some 12 years from today. The new system probably won't have a screen just like yours...

    Personally, I like to distinguish business rules and software requirements as explicitly as possible. One is non-negotiable, clear-cut fact. The other is open for discussion for scope and remains malleable to interpretation. Generally I see design documents specifying about 5-10 times more requirements than business rules. More complex domains have more business requirements, but the factor remains.

    To adhere to all business rules is a 1 line requirement. To force system/user input to adhere to business rules requires explicit requirements.

    jschoen : +1 That was a nice addition. Thanks for taking the time to add to this.

Opera and Custom cursor in CSS

Where I normally am verry proud of Opera for implementing everything CSS really correct it seems that implementing a custom cursor with the following line doesn't seem to work

cursor:url("../pics/merge.gif");

The URL is correct since it works for regular background-image properties.
Works in other browsers, but not in Opera.

Any ideas?

From stackoverflow
  • Opera doesn't seem to support the url property. It might even be being removed from the spec (will check that).

    borisCallens : the URL property? You do mean in combination with the cursor? It dftly supports it with background-image...
  • Opera has not yet added support for that. That line is incorrect though, per the specification a fallback cursor is required. So you have to write e.g.

    cursor:url("path/to/cursor"), wait;

    (Disclaimer: I work for Opera.)

    borisCallens : You work for opera? Thanks for such a great product. Also, what's the company like? If they ever think of accepting 1 year foreign interns, please do contact me ;)
    Anne : It's great! And I believe we do: http://www.opera.com/company/jobs/

How to find event listeners on a DOM node?

I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event?

Events are attached using 1) prototype's Event.observe 2) DOM's addEventListener 3) as element attribute element.onclick

From stackoverflow
  • It depends on how the events are attached. For illustration presume we have the following click handler:

    var handler = function() { alert('clicked!') };
    

    We're going to attach it to our element using different methods, some which allow inspection and some that don't.

    Method A) single event handler

    element.onclick = handler;
    // inspect
    alert(element.onclick); // alerts "function() { alert('clicked!') }"
    

    Method B) multiple event handlers

    if(element.addEventListener) { // DOM standard
        element.addEventListener('click', handler, false)
    } else if(element.attachEvent) { // IE
        element.attachEvent('onclick', handler)
    }
    // cannot inspect element to find handlers
    

    Method C): jQuery

    $(element).click(handler);
    
    • 1.3.x

      // inspect
      var clickEvents = $(element).data("events").click;
      jQuery.each(clickEvents, function(key, value) {
          alert(value) // alerts "function() { alert('clicked!') }"
      })
      
    • 1.4.x (stores the handler inside an object)

      // inspect
      var clickEvents = $(element).data("events").click;
      jQuery.each(clickEvents, function(key, handlerObj) {
          alert(handlerObj.handler) // alerts "function() { alert('clicked!') }"
          // also available: handlerObj.type, handlerObj.namespace
      })
      

    (See jQuery.fn.data and jQuery.data)

    Method D): Prototype (messy)

    $(element).observe('click', handler);
    
    • 1.5.x

      // inspect
      Event.observers.each(function(item) {
          if(item[0] == element) {
              alert(item[2]) // alerts "function() { alert('clicked!') }"
          }
      })
      
    • 1.6 to 1.6.0.3, inclusive (got very difficult here)

      // inspect. "_eventId" is for < 1.6.0.3 while 
      // "_prototypeEventID" was introduced in 1.6.0.3
      var clickEvents = Event.cache[element._eventId || (element._prototypeEventID || [])[0]].click;
      clickEvents.each(function(wrapper){
          alert(wrapper.handler) // alerts "function() { alert('clicked!') }"
      })
      
    • 1.6.1 (little better)

      // inspect
      var clickEvents = element.getStorage().get('prototype_event_registry').get('click');
      clickEvents.each(function(wrapper){
          alert(wrapper.handler) // alerts "function() { alert('clicked!') }"
      })
      
    Keith Bentrup : Thx for updating this. It's unfortunate that you have to iterate thru each type of handler.
  • If you have Firebug, you can use console.dir(object or array) to print a nice tree in the console log of any javascript scalar, array, or object. Try: console.dir(clickEvents); or console.dir(window);

  • If you just need to inspect what's happening on a page, you might try the Visual Event bookmarklet.

    Brian Wigginton : This tool is awesome, thanks for posting.

Where can I find a bit shifting guide for C?

I have looked at http://stackoverflow.com/questions/141525/absolute-beginners-guide-to-bit-shifting but I still find the concept of bit shifting difficult to understand.

Can someone point me in the direction of a more basic guide to bit shifting in C. I expect it will be something really long since it will need to cover the whole subject.

I really do not understand it but I want to learn it, so any help would be appreciated.

I am learning the k&r, and that is what this is for so I can do the exercises. I understand the basics, but I still cannot do correct bit shift operations.

EDIT here's the exersices from K&R that have stumped me

Exercise 2-6: Write a function setbits(x, p, n, y) that returns x with the n bits thatbegin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Exercise 2-7: Write a function invert(x, p, n) that returns x with the n bits that begin at poisiton p inverted (i.e., 1 changed into 0 and vice versa) leaving the others unchanged.

Exercise 2-8: Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions

Exercise 2-9: In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why, Use this observation to write a faster version of bitcount

These are exercises from the k&R (the c programming language) book its the best c book there is but I am having trouble understanding bitshifting so I am having problems with these exercises.

From stackoverflow
  • The guide you linked to is really good. What is it you don't understand about bit-shifting?

    I don't know what the K&R is, so I can't help you there.

    Can you be more specific with the question, and I can edit to be more specific about the answer.

    unwind : "K&R" is a reference a "The C Programming Language", the book that rules them all. At least when it comes to C programming. :) K&R are its authors' initials, Kernighan & Ritchie.
    Paul Nathan : K&R: *the* C reference.
  • Bit shifting is nothing but what it literally means: shifting all bits in a given sequence left or right.

    All you have to remember is that every decimal number (like 6, 7, 3, 2) is represented as a sequence of bits in the memory of the computer. So if you find something like this in a piece of C code:

    (7 >> 1)
    

    it means that the bits in the underlying binary representation of 7 are to be shifted right by 1 position.

    I think the explanation in the link you cite is pretty clear. Maybe writing down a sequence of bits on a paper yourself and manipulating them as in the cited link can help.

    Or perhaps you don't possibly yet have the understanding how computers work with numbers internally. In that case, before learning bit shifting, you need to read about that.

  • Your going to need more tools in your toolkit to answer those questions than shifting.

    I think you'll need to start very basic about how numbers are represented in binary. Then you'll want to think about how to set and clear specific bits in that number, or a group of bits at the same time. You'll need to know how to test to see if a certain group of bits is set and about masking. You'll have to be able to do all the above with the bitwise operators and/or/xor/inversion/etc operators. Then you'll want to know about shifting -- moving bits left and right by a specific number of spaces. You'll want to know what happens to the bits left "empty". Is it filled with a 1 or a 0? When is it filled with a 1 or 0?

    Googling "bitwise operations tutorial" seems to have come up with some promising results to begin with. But here's some basics to test yourself against to make sure you understand

    // 1234 in hex, you understand this is not 1234 in decimal? Do you understand
    // how specifying in hex makes it easier to think about the binary representation?
    unsigned short i = 0x1234; 
    // flip all the bits in 0x1234
    printf("%04x", ~i);
    
    // Test - Is the most significant bit set?
    // mask is a binary number with the most significant bit set. Do
    // you understand why this is so?
    unsigned short mask = 0x8000;   
    if ((mask & i) == mask)
    {
        printf("bit set!");
    }
    else 
    {
        printf("bit cleared!");
    }
    
    // set the most significant bit
    i = i | mask;
    printf("Set the MSB of i, check it out: %i\n", i)
    
    // set the second most significant bit
    // Do you see how by shifting mask right one it becomes the next most significant bit?
    i = i | (mask >> 1);
    

    Good Luck!

  • If you have the money (and the time), grab a copy of Hackers Delight. It is probably the best bit shifting guide around. It will take you through simple shifts (and other manipulation techniques) all the way through gray codes and more...

  • Let's go through one exercise, for a sample.

    Exercise 2-6: Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

    Let's keep in ind that the least significant bit is bit 0 (is at position 0)

    Here is the pseudocode:

    1. move the bits p to p+n in x to position 0 to n. That's where you right-shift.
    2. prepare a bit mask that will turn anything from bit n to the highest bit into 0s. You can use a lookup array for this (e.g. 0xFF for n=8, 0x7F for 7 and so on), or you can use a combination of setting bit 0 and lef-shifting in a loop.
    3. apply the bit mask to x using & . All the bits we don't care about in x are now 0
    4. invert the bit mask. We now have a bunch of 1s at the high end, and a bunch of 0s at the low end. The bits we want to change in y all have 0s in bit mask.
    5. apply the bit mask to y using & . All the bits in y that we will replace with bits in x are now set to 0, and the bits that we don't want to change are unchanged.
    6. set the bits we want to change in y by combining x and y using | . This is the crucial point - go over what's happening with a pen and paper. The bits in x that were set to 0 in (3) will not affect the corresponding bits in y. The bits in x that were not affected by (3) will combine with 0s in y (0s because of step5), setting the resulting bit to the value it had in x.
    A. Rex : For step 2, you can avoid lookup tables and looping by and-ing with the mask (1 << n)-1
    Arkadiy : Right you are, thanks.
  • Keep in mind that nearly all of those exercises have a straightforward solution that can be written with functions int IsBitSet(int i, int n); int SetBit(int i, int n); and combinations of << and >>. The straightforward solutions are nearly all worst case, but are far easier to implement and read. This is kind of like implementing multiplication in terms of addition or addition in terms of increment.

  • edit: just saw someone else already posted my suggestion to buy a copy of hacker's delight. :)

  • Let's try 2-6, to give you a taste of how bit operations work, and then see if it makes sense.

    int setbits( int x, int p, int n, int y )
    {
        int bitmask = ~0, y_right = 0; 
    
        /* Ok, first let's get y's rightmost bits.
         * Take our bitmask, shift it left by n bits, leaving the least significant
         * n bits as 0. Then, flip the bitmask so the rightmost n bits become 1, and the
         * leftmost n bits become 0.
         *
         * Then, AND this bitmask with y, to yield y's n rightmost bits.
         */
        bitmask = ~( bitmask << n );
        y_right = bitmask & y;
    
        /*
         * Ok, now let's use y_right as our bitmask for x.
         * Shift y_right to the left to *begin* at position p.
         */
         y_right <<= p - n;
         x |= y_right;
    
         return x;
    }
    

    Note: the above may be completely incorrect as I haven't tested it, but it should give you a decent idea to start with.

  • There's a great introduction to bitwise operators right here on stack overflow already: Here

  • Write the bits on paper and think about erasing them from one end and adding more on the other. Not unlike elementary school and moving the decimal point around when multiplying by 10.

    All of your C functions are going to shift zeros in.

    So

    x = y << 3;

    means shift left three bits and the new bits on the right are all zeros, the three bits that were on the left go into the "bit bucket"

    x = z >> 2

    lose the two bits on the right and add two zeros on the left.

    What you will find and what the K&R exercises are about are the missing functions, among the processor types out there you have far more shifting capabilities than you do in C or any other high level language.

    You have rotate functions where the bit shifted off of one end gets shifted in the other,

    So the number 0xD rotated 1 bit to the right in this manner would be an 0xE, because the lsbit was a 1 so shift 1101 to the right the 1 on the right becomes a 1 on the left 1110

    Sometimes you rotate through the carry bit in the alu. Lets say the carry bit had a zero in it and you rotated 0xD one bit 0 1101 leaves 1 0110 a 0x6. rotate that one more 0 1011 and you get a 0xB and so on.

    Why would you ever rotate through the carry bit you ask? For bigger numbers, say you have four bit registers and want to do an 8 bit shift, lets say each of the letters are bits a bcde fghi where a is the carry bit and the other two groups of four are four bit registers, start by rotating the left register through the carry e abcd fghi then rotate the right register through the carry i abcd efgh, pretty cool we just did an 8 bit shift with a 4 bit shift function. if you had cleared the carry bit before starting (often there is an instruction for this or you can always do something like add 0+0 or something else guaranteed to clear that bit) you would have i 0bcd efgh which is not unlike what a C shift function would do if you are say on a 32 bit instruction set operating on a 64 bit number.

    The processors often have the C like shifts where a zero is shifted in, shift abcd left one gives bcd0 shift abcd right two gives 00ab.

    And this leads to some problems, the younger folks with modern processors dont think about such things because an integer divide is both supported on their processor and can operate in a single clock cycle, back before we had divide or when divide was dozens to hundreds of clocks but a shift was a single clock you would do all of your power of 2 divides or multiplies using shifting intead. take the number 0x0D shift that left two you get 0b00001101 << 2 = 0b00110100 or 0x34 0xD is 13 decimal and 0x34 is 52 decimal. 52 is four times more than 13. four is 2 to the power 2. shifting by two is the same as multiplying by four. This works both ways, 0x34 shifted right 2 is 0xD, but here is the problem, when you get into negative numbers, take the number minus 4 0xFC, now divide that by two. Using C 0xFC >> 1 would give 0x7E but 0x7E is +126 decimal how does -4/2 = 126? the problem is that C shifts in zeros. You will find some processors have an arithmetic shift which is different than a logical shift, the arithmetic shift keeps the upper most bit, so if you are working with a signed number like 0bQWER and you arithmetically shifted that right one bit you get 0bQQwe, the upper most bit both shifts into the next bit and stays where it was. shift again 0bQQQW, and so on. Now an arithmetic shift left will shift in zeros and not the lsbit so 0bQWER shifted left one is 0bWER0. And that makes sense -4 shifted left one is 0xF8 which is -8, -4 times two is -8 so that is right. So you will find that some processors only have an arithmetic shift right but not a left, some allow you to specify an asl but when they assemble it replace it with an lsl (logical shift left) and who knows some may actually have a separate opcode even though it is the same function. I assume there may be some that have an asl and an asr and lsr but no lsl.

    Just use paper and pencil and figure things out, start with real numbers as examples, then go abstract. Want to rotate 0x1234 to the right one bit lets say?

    0001001000110100 write out the bits x0001001000110100 shift right one 0000100100011010 because this is a rotate fill in the new bit with the bit that fell off on the prior operation want to now shift two bits to the right 0000100100011010 xx0000100100011010 1000001001000110

    How would I do a single bit rotate in C?

    unsigned int rotate_right_one ( unsigned int x ) { unsigned int y; y = x & 1; //save the bit that is about to fall off the right x >> = 1; //logical rotate one bit x |= y<<31; //this assumes that unsigned int is 32 bits. return(x); }

    To rotate more you can simply call this function multiple times or think about the mask and shift above and how would that work for more than one bit.

    Also note that some processors only have one rotate function, for example think about this I have a four bit register and I rotate 5 bits what do I get?

    abcd bcda first rotate cdab second dabc third abcd fourth bcda fifth

    what does a single rotate left look like? abcd bcda one bit left.

    five right on a four bit register is the same as one left 5-4=1. Like the asl some processors will let you code the operation but the assembler replaces that operation with the other rotate using nbits-shift as the rotate amount.

    For some people logical bit operations are as tough as pointers to understand, but it is a fundamental and if you learn it and use it you will be way out ahead of your competition or those around you.

    here is an example that counts the number of bits in some variable:

    for(count=0,r=1;r;r<<=1) if(r&some_variable) count++;

    understand that line of code and you are well on your way to both learning C and the logical bit operations.

  • Bit Twiddling Hacks

  • Here is a basic guide that I found some time back at AVRFreaks. That will show you the fundamentals, and then you can go on with the other tutorials.

ASCX files

I have a web application project that contains only .ascx files. I build it to create a dll and then reference the dll from another web app project. Do I need to copy over the .ascx files over the the site as well. If i need to copy them over, where do i need to place them?

EDIT: I was able to fix the cause of this problem.

The web application containing the ascx files was a website project that was converted to a web application. During this conversion some namespaces got mangled and as a result we had namespace like: SmartDev.SmartDev instead of just SmartDev.

I had to modify the tag prefix entry in the web.config file to use "SmartDev.SmartDev" and it worked. I had to go to every single location in html and change the modified class file names though...

From stackoverflow
  • Yes you'll need the .ascx files. Place them in the directory structure somewhere logical that you can reference from wherever you are instantiating the controls.

    Nick : How do I reference them?
    Neil D : You could use fully qualified names.

What's the best way to specify a proxy with username and password for an **https** connection in python?

I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it . Please help me.

Thanks.

From stackoverflow
  • You can use httplib2, which solves some of the limitations of urllib2 including this one. There is an example here of how to do Basic Authentication on a https connection.

  • "urllib2 doesn't support authenticated https connection" False.

        # Build Handler to support HTTP Basic Authentication...
        basic_handler = urllib2.HTTPBasicAuthHandler()
        basic_handler.add_password(realm, self.urlBase, username, password)
        # Get cookies, also, to handle login
        self.cookies= cookielib.CookieJar()
        cookie_handler= urllib2.HTTPCookieProcessor( self.cookies )
        # Assemble the final opener
        opener = urllib2.build_opener(basic_handler,cookie_handler)