Recursive function call 'CABM_READ_BOM'
Hi,
I need to do a recursive call to 'CABM_READ_BOM' using different matnr each time. Data will be stored in i_exp_bom_head and i_exp_bom_item. Since this is a recursive call to the same routine and iterations depend on the level of BOM how can I keep track of the internal tables returned by its level?
FORM READ_BOM using p_matnr.
CALL FUNCTION 'CABM_READ_BOM'
EXPORTING
i_matnr = p_matnr
i_werks = i_bom_select-werks
i_vbeln = i_bom_select-vbeln
i_vbpos = i_bom_select-posnr
i_stlal = i_bom_select-stlal
i_stlan = i_bom_select-stlan
i_datuv = i_bom_select-erdat
TABLES
exp_bom_data = i_exp_bom_head
exp_itm_data = i_exp_bom_item
EXCEPTIONS
no_record_found = 1
OTHERS = 2.
LOOP AT i_exp_bom_item WHERE postp = 'N'.
PERFORM READ_BOM using i_exp_bom_item-idnrk.
ENDLOOP.
ENDFORM.
Points will be awarded.
Thanks!
Hi Subramanian,
Thank you for your prompt reply.
I'm trying to create master BOM and sub BOM depending on how many levels it is.
IF i_exp_bom_item-POSTP = 'N' then I call the function module again to create sub BOM. I will call the function module recursively until i_exp_bom_item-POSTP <> 'N'. That will be the lowest level.
Message was edited by:
Alex Nguyen
Similar Messages
-
Validation of recursive function call fails
We want to use a call to a recursive function from a HTMLDB application. It should be used in a page region to generate a query string ("PL/SQL function body returning SQL query"). Everything works fine with a call to a non-recursive function. The recursive function also works fine when called from SQL+.
After pressing "Apply changes" on "HTML DB Home>Builder - Application 148>Page Definition>Edit Page Region"-page I get the following error message after a long delay:
Function returning SQL query: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing
(ORA-00600: internal error code, arguments: [kohdtf048], [], [], [], [], [], [], [])
I assume that the validation routine follows the recursion until the memory limit is reached.
Please give me a hint how to solve this problem.
DB version: 10.1.0.2.0
HTMLDB version: 1.5.0.00.33
running on Win2000 serverSince the original function is confidential, I have created a simple one showing the same behavior (and the same error). Termination does not depend on session state:
Called function (to replace spaces with #):
create or replace function MF_Test
p_querystring varchar2
return varchar2 is
v_position integer;
begin
v_position:=instr(p_querystring,' ');
if v_position=0 then /* termination condition */
return p_querystring;
else
return substr(p_querystring,1,v_position-1)||'#'||MF_Test(substr(p_querystring,v_position+1));
end if;
end MF_Test;
calling function (from the page region, to generate a query string):
declare
q varchar2(500);
begin
q:='select * from hardware where model=''';
q:=q||mf_test(:P3_SEARCH);
q:=q||'''';
end
Validation seems not to terminate in case of recursive function calls.
Thanks for your input. -
Help!! recursive function call
* The function which build the category tree
public String categoryTree(Statement stat, boolean isMore, int id) {
if(!isMore) {
return "";
else
String sql = " select t_category_relation.category_relation_id, t_category_relation.level_in, " +
" t_category_item.category_item_id, t_category_item.category_name_jpn_NV from " +
" t_category_item, t_category_relation " +
" where " +
" t_category_item.category_item_id = t_category_relation.category_item_id and " +
" t_category_relation.parent_id = " + id + " and t_category_relation.parent_id<>0";
// return sql;
try{
ResultSet res = stat.executeQuery(sql);
String spacer = "";
String input = "";
while(res.next()) {
int level = res.getInt(2);
id = res.getInt(1);
for(int i = 0; i < level; i ++) {
spacer +=" ";
input ="+ id: " +id + " NAME " + res.getString(4) + "\n</td>\n<td align=center>\n<input type=checkbox value=" +String.valueOf(id) + " name=categoryid>\n</td>\n</tr>\n";
return "\t\t<TR>\n\t\t\t<TD>" + spacer + input + categoryTree(stat, true, id);
if(spacer.equals("")){
return input+categoryTree(stat, false, id);
}catch(SQLException e) {
return "SQL Exception";
return categoryTree(stat, false, id);
}I am writing a menu generated base on a tree like relation ship that is store in a database. assume
vegetable has two child and one of the child has another child and so forth.
But I am getting a result like this:
vegetable-->
<1>childe
<1.1>childe
but missing <2>child
because the while loop doesn't continous looping after the 1.1.
please help me out
thanx in advance>
Re: help!! recursive function call
Author: DrClap Aug 3, 2001 1:15 PM
When you call the method recursively, the second call makes a second query to the database, before you have finished using the ResultSet from the first query. Since you are using the same Statement, executing the second query causes the first query to, um, disappear.
The API documentation for java.sql.Statement says this: "Only one ResultSet object per Statement object can be open at any point in time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All statement execute methods implicitly close a statment's current ResultSet object if an open one exists."
thanx for your reply!
public String categoryTree(int id) {
String sql = " select t_category_relation.category_relation_id, t_category_relation.level_in, " +
" t_category_item.category_item_id, t_category_item.category_name_jpn_NV from " +
" t_category_item, t_category_relation " +
" where " +
" t_category_item.category_item_id = t_category_relation.category_item_id and " +
" t_category_relation.parent_id = " + id;
try{
Connection con = DataSourceUtil.getConnection("name");
Statement stat = con.createStatement();
ResultSet res = stat.executeQuery(sql);
String spacer = "";
String row = "";
while(res.next()) {
int level = res.getInt(2);
id = res.getInt(1);
for(int i = 0; i < level; i++) {
spacer +=" ";
row = " \t\t<tr>\n " +
" \t\t\t<td colspan='2'>" + spacer + " <a href=inventory_edit_product.jsp?categoryid=" + id +">" + res.getString(4) + "</a></td>\n" +
" \t\t</tr>\n ";
return (row + categoryTree(id));
con.close();
}catch(SQLException e) {
return "<tr><td colspan=2>SQL Exception</td></tr>";
return "";
}New I think every recursive call will have it's own statement and resultSet but I am still getting same problem. The while loop stopped when calls reached first base case. Does anybody know why. I expect, assume that while loop will go next when a call reaches the base case which will return "".
Thanx for help -
How to collect returns from recursive function calls without a global var?
Usually global variables shouldnt be used, I was told. Ok. But:
How can I avoid using a global var when recursively using a function, when the function returns an object and when I want to have the collection of all these objects as the result?
For example, I think of determine the users of a group including group nesting. I would write a function that adds the direct group members to a collection as a global var and call itself recusively if a member is another group. This recursively called function
would do as well: Update the global var and if needed call itself.
I'm afraid this is no good programming style. What algorithm would be better, prettier? Please dont focus on the example, it is a more general question of how to do.
Thanks
WalterI rarely needed to create/use recursive functions. Here's one example I did:
function New-SBSeed {
<#
.Synopsis
Function to create files for disk performance testing. Files will have random numbers as content.
File name will have 'Seed' prefix and .txt extension.
.Description
Function will start with the smallest seed file of 10KB, and end with the Seed file specified in the -SeedSize parameter.
Function will create seed files in order of magnitude starting with 10KB and ending with 'SeedSize'.
Files will be created in the current folder.
.Parameter SeedSize
Size of the largest seed file generated. Accepted values are:
10KB
100KB
1MB
10MB
100MB
1GB
10GB
100GB
1TB
.Example
New-SBSeed -SeedSize 10MB -Verbose
This example creates seed files starting from the smallest seed 10KB to the seed size specified in the -SeedSize parameter 10MB.
To see the output you can type in:
Get-ChildItem -Path .\ -Filter *Seed*
Sample output:
Mode LastWriteTime Length Name
-a--- 8/6/2014 8:26 AM 102544 Seed100KB.txt
-a--- 8/6/2014 8:26 AM 10254 Seed10KB.txt
-a--- 8/6/2014 8:39 AM 10254444 Seed10MB.txt
-a--- 8/6/2014 8:26 AM 1025444 Seed1MB.txt
.Link
https://superwidgets.wordpress.com/category/powershell/
.Notes
Function by Sam Boutros
v1.0 - 08/01/2014
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Low')]
Param(
[Parameter(Mandatory=$true,
ValueFromPipeLine=$true,
ValueFromPipeLineByPropertyName=$true,
Position=0)]
[Alias('Seed')]
[ValidateSet(10KB,100KB,1MB,10MB,100MB,1GB,10GB,100GB,1TB)]
[Int64]$SeedSize
$Acceptable = @(10KB,100KB,1MB,10MB,100MB,1GB,10GB,100GB,1TB)
$Strings = @("10KB","100KB","1MB","10MB","100MB","1GB","10GB","100GB","1TB")
for ($i=0; $i -lt $Acceptable.Count; $i++) {
if ($SeedSize -eq $Acceptable[$i]) { $Seed = $i }
$SeedName = "Seed" + $Strings[$Seed] + ".txt"
if ($Acceptable[$Seed] -eq 10KB) { # Smallest seed starts from scratch
$Duration = Measure-Command {
do {Get-Random -Minimum 100000000 -Maximum 999999999 |
out-file -Filepath $SeedName -append} while ((Get-Item $SeedName).length -lt $Acceptable[$Seed])
} else { # Each subsequent seed depends on the prior one
$PriorSeed = "Seed" + $Strings[$Seed-1] + ".txt"
if ( -not (Test-Path $PriorSeed)) { New-SBSeed $Acceptable[$Seed-1] } # Recursive function :)
$Duration = Measure-Command {
$command = @'
cmd.exe /C copy $PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed+$PriorSeed $SeedName /y
Invoke-Expression -Command:$command
Get-Random -Minimum 100000000 -Maximum 999999999 | out-file -Filepath $SeedName -append
Write-Verbose ("Created " + $Strings[$Seed] + " seed $SeedName file in " + $Duration.TotalSeconds + " seconds")
This is part of the SBTools module and is used by the
Test-SBDisk function.
Example use:
New-SBSeed 10GB -Verbose
Test-SBDisk is a multi-threaded function that puts IO load on target disk subsystem and can be used to simulate workloads from multiple machines hitting the same SAN at the same time, and measure disk IO and performance.
Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) _________________________________________________________________________________
Powershell: Learn it before it's an emergency http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx -
Please help me on recursive function call
* The function which build the category tree
public String categoryTree(Statement stat, boolean isMore, int id) {
if(!isMore) {
return "";
else
String sql = " select t_category_relation.category_relation_id, t_category_relation.level_in, " +
" t_category_item.category_item_id, t_category_item.category_name_jpn_NV from " +
" t_category_item, t_category_relation " +
" where " +
" t_category_item.category_item_id = t_category_relation.category_item_id and " +
" t_category_relation.parent_id = " + id + " and t_category_relation.parent_id<>0";
// return sql;
try{
ResultSet res = stat.executeQuery(sql);
String spacer = "";
String input = "";
while(res.next()) {
int level = res.getInt(2);
id = res.getInt(1);
for(int i = 0; i < level; i ++) {
spacer +=" ";
input ="+ id: " +id + " NAME " + res.getString(4) + "\n</td>\n<td align=center>\n<input type=checkbox value=" +String.valueOf(id) + " name=categoryid>\n</td>\n</tr>\n";
return "\t\t<TR>\n\t\t\t<TD>" + spacer + input + categoryTree(stat, true, id);
if(spacer.equals("")){
return input+categoryTree(stat, false, id);
}catch(SQLException e) {
return "SQL Exception";
return categoryTree(stat, false, id);
} I am writing a recusive function which can generate a tree like category tree for customer navigation purpose.I don't know why my will loop only return once which means if category "vegetable" has two child and one of child has another child but the result will only display vegetable-->child-->grand child instead of vegetable-> 2 child -> one grand child of one of the child.Please help exam the codethax inDidn't I already answer this?
-
Calling Recursive function in a transaction
Hello All
I have a requirement calling Recursive function in Transaction.Means inside a transaction, i want to call the same transaction.Is it possible to do like this?
Because when i am calling like this,transaction is running contineously without stop.
Any help would be highly appreciated.
Thanks,
ManishaManisha,
take a look on this thread:
Does xMII support recursive Business Logic Modules
Hope Ricks solution can help you.
Regards
Pedro
Edited by: Pedro Iglesias on Dec 19, 2008 9:56 AM -
Skipping to a specific place in a recursive function
I wrote a recursive function that recurses Adding times, then calls go (). The entire function will call go () billions of times. When I call this function, I want to only run go () 5,000,000 times. It should run the first 5,000,000 go's if the Part variable is set to 1, the 2nd 5,000,000 go's if Part is 2, etc. The bolded code below is my attempt at implementing this. This code runs the correct 5,000,000-part pieces, but it takes too long because it is still recursing through every part, it's just not calling go () for the other ones. How can I only run the specific piece without recursing through all of the other ones?
Add (int X, int Y, int Adding)
int Tile;
while (Y < 12)
while (X < 16)
if (aRoom [nRoom] [Y] [X] == 0)
Changes [Adding - 1] [1] = X;
Changes [Adding - 1] [2] = Y;
for (Tile = 0; aTiles [nRoom] [Tile] [0] != 0; Tile++)
if (aTiles [nRoom] [Tile] [1] > 0)
aTiles [nRoom] [Tile] [1]--;
aRoom [nRoom] [Y] [X] = aTiles [nRoom] [Tile] [0];
Changes [Adding - 1] [0] = aTiles [nRoom] [Tile] [0];
if (Adding > 1)
Add (X + 1, Y, Adding - 1);
else
PartTests++;
if (Part == 0 || Part == Parts)
go ();*}*
if (PartTests == 5000000)
Parts++;
PartTests = 0;
aTiles [nRoom] [Tile] [1]++;
aRoom [nRoom] [Y] [X] = 0;
X++;
X = 0;
Y++;
}what go()?
here's a cleaned up version of the code ( not a soln. ):
Add( int X, int Y, int Adding )
int Tile;
while ( Y < 12 )
while ( X < 16 )
if ( aRoom [nRoom][Y][X] == 0 )
Changes[Adding - 1][1] = X;
Changes[Adding - 1][2] = Y;
for ( Tile = 0; aTiles [nRoom][Tile][0] != 0; Tile++ )
if ( aTiles[nRoom][Tile][1] > 0 )
aTiles[nRoom][Tile][1]--;
aRoom[nRoom][Y][X] = aTiles [nRoom] [Tile] [0];
Changes[Adding - 1][0] = aTiles[nRoom][Tile][0];
if ( Adding > 1 )
Add ( X + 1, Y, Adding-1 );
else
PartTests++;
if ( Part == 0 || Part == Parts )
go();
if ( PartTests == 5000000 )
Parts++;
PartTests = 0;
aTiles[nRoom][Tile][1]++;
} // end of if
} // end of for
aRoom[nRoom][Y][X] = 0;
} // end of if
X++;
} // end of inner while
X = 0;
Y++;
} // end of outer while
}Edited by: scphan on Apr 4, 2009 1:13 PM -
Problem with recursive function & Exception in thread "AWT-EventQueue-0"
I hope that title doesn't put everyone off :)
I have a recursive function that takes in a list of words, and a reference to my current best board. I am kludging the escape function +(tryWords.size() == 0 || mTotalBlankBlocks < 200)+ atm, but eventually it will escape based on whether the current bestBoard meets certain requirements. The function makes iterates through a list of words, and finds all the spaces that the word would fit into the puzzle: getValidSpacedPositions(currentWord); - it then iterates through each of these; placing a word, removing that word from the iterator and the relevant arrayLists and then recurses the function and tries to do the same with the next word etc.
private void computeBoards(ArrayList<Word> tryWords, Board bestBoard) {
if (tryWords.size() == 0 || mTotalBlankBlocks < 200)
return;
for(Iterator<Word> iter = tryWords.iterator(); iter.hasNext(); ){
Word currentWord = new Word();
currentWord = iter.next();
ArrayList<Position> positions = new ArrayList<Position>();
positions = getValidSpacedPositions(currentWord);
if (positions.size() != 0)
iter.remove();
System.out.println();
int placedWordsIndex = tryWords.indexOf(currentWord);
System.out.print(placedWordsIndex+". "+currentWord.getString()+" with "+positions.size()+" positions / ");
for (Position position : positions) {
System.out.println("Pos:"+(positions.indexOf(position)+1)+" of "+positions.size()+" "+position.getX()+","+position.getY()+","+position.getZ());
int blankBlocksLeft = placeWord(currentWord, position);
if(blankBlocksLeft != 0)
mPlacedWords.add(currentWord);
// TODO: Kludge! Fix this.
mUnplacedWords.remove(placedWordsIndex+1);
System.out.println("adding "+currentWord.getString()+" to added words list");
Board compareBoard = new Board(blankBlocksLeft, mPlacedWords.size());
if (compareBoard.getPercFilled() > bestBoard.getPercFilled())
bestBoard = new Board(blankBlocksLeft, mPlacedWords.size());
//**RECURSE**//
computeBoards(tryWords, bestBoard);
mUnplacedWords.add(currentWord);
removeWord(currentWord);
System.out.println("removing "+currentWord.getString()+" from added words list");
else
System.out.println("strange error, spaces are there but word cannot place");
System.out.println("**FINISHED ITERATING POSITIONS");
System.out.println("**FINISHED ITERATING TRYWORDS");
}This all seems to work fine, but I add it in for completeness because I am not sure if I have done this right. The Exception occurs in the placeWord function which is called from the recursive loop, on the line bolded. For some reason the Arraylist Words seems to initialise with size 1 even though it is a null's when I look at it, (hence all the redundant code here) and I can't seem to test for null either, it seems to works fine for a while until the recursive funciton above has to back up a few iterations, then it crashes with the exception below.
private int placeWord(Word word, Position originPosition) {
ArrayList<Word> words = new ArrayList<Word>();
switch (originPosition.getAxis().getCurrInChar()) {
case 'x':
// TODO: This is returning ONE!!!s
words = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords();
int tempword1 = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords().size();
for (int i = 0; i < word.getLength(); i++) {
*if (words.get(0) == null)*
mBlockCube[originPosition.getX() + i][originPosition.getY()][originPosition.getZ()] = new Block(word, word.getChar(i));
else
mBlockCube[originPosition.getX() + i][originPosition.getY()][originPosition.getZ()].addWord(word);
break;
case 'y':
words = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords();
int tempword2 = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords().size();
for (int i = 0; i < word.getLength(); i++) {
*if (words.get(0) == null)*
mBlockCube[originPosition.getX()][originPosition.getY() + i][originPosition.getZ()] = new Block(word, word.getChar(i));
else
mBlockCube[originPosition.getX()][originPosition.getY() + i][originPosition.getZ()].addWord(word);
break;
case 'z':
words = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords();
int tempword3 = mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ()].getWords().size();
for (int i = 0; i < word.getLength(); i++) {
*if (words.get(0) == null)*
mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ() + i] = new Block(word, word.getChar(i));
else
mBlockCube[originPosition.getX()][originPosition.getY()][originPosition.getZ() + i].addWord(word);
break;
mTotalBlankBlocks -= word.getLength();
word.place(originPosition);
String wordStr = new String(word.getWord());
System.out.println("Word Placed: " + wordStr + " on Axis: " + originPosition.getAxis().getCurrInChar() + " at pos: "
+ originPosition.getX() + "," + originPosition.getY() + "," + originPosition.getZ());
return mTotalBlankBlocks;
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.edzillion.crossword.GameCube.placeWord(GameCube.java:189)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:740)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.computeBoards(GameCube.java:763)
at com.edzillion.crossword.GameCube.generateGameCube2(GameCube.java:667)
at com.edzillion.crossword.GameCube.<init>(GameCube.java:42)
at com.edzillion.crossword.Crossword.actionPerformed(Crossword.java:205)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
Any ideas? I've looked up this exception which didn't shed any light...ArrayList<Word> words = new ArrayList<Word>();See the API Javadoc for ArrayList: this creates an empty ArrayList.
if (words.get(0) == null)This tries to read the first element of the (still empty) array list -> throws IndexOutOFBoundsException
If you want to stick to that logic (I am too lazy to proof-read your whole algorithm, but that should at least unblock you), you should first check whether the list actually contains at least one element:
if (!words.isEmpty()) {...} -
Help with recursive function to print number patterns
I'm sorry for having to ask for homework help - I'm badly stuck on this! Can someone give me a kick in the right direction with this?
need a recursive function with a single positive int parameter n. the function should write (2^n - 1) integers and should be in the following pattern...
n = 1, Output: 1
n = 2, Output: 1 2 1
n = 3, Output: 1 2 1 3 1 2 1
n = 4, Output: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
n = 5, Output: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
function should valid for all positive integer values of n
This was tagged as a 'short' problem...so it shouldnt take too much code...I am hung on on the following:
*Do I keep track of the numbers printed, if so how? I only have a single parameter to call with so I am confused as to how I could get an entire pattern without keeping track of the history
*I had initially thought it would be necessary to cut it in half and do the 2nd half backwards (ie: for n=3, I would take care of the 1 2 1 - then 3 - then 1 2 1...but even then it seems like I could cut 1 2 1 in half the same way and therefor I should be able to do ALL of it in single parts...
Can someone veer me in the right direction here? I'm really lost with this.This was tagged as a 'short' problem...so it shouldnt
take too much code...Yeah, the method body could be done in a few lines.
I am hung on on the following:
*Do I keep track of the numbers printed, if so how?Not explicitly. Use the call stack. That is, use the fact that when you're recursing, the previous values of numbers are preserved in the previous method invocation.
I only have a single parameter to call with so I am
confused as to how I could get an entire pattern
without keeping track of the historyYou don't have to store anything across method invocations.
I had initially thought it would be necessary to cut
it in half and do the 2nd half backwards (ie: for
n=3, I would take care of the 1 2 1 - then 3 - then 1
2 1...but even then it seems like I could cut 1 2 1
in half the same way and therefor I should be able to
do ALL of it in single parts...No, it's MUCH simpler than that. It's easier than yo uthink.
Can someone veer me in the right direction here? I'm
really lost with this.Try this simpler version of the problem:
Write a recursive method that creates this output:
n = 1: 1
n = 2: 1 2
n = 3: 1 2 3
And try this simpler version:
n = 1: 1
n = 2: 2 1
n = 3: 3 2 1 -
How to define recursive functions in JSP
Hi,
If anybody knows, how to to define recursive functions pls help. I am using an XML file for the creation of a tree menu. In order to display the menu, i have to use recursive functions...Also out.println throwing error in the function..
Thanks,
PhilipsI do not have my Java book at work with me today so you'll have to bear with me. The following routine assumes that you can get some sort of branch object from your tree menu object (also assuming you have something like this). Furthermore, it assumes that the branch object can return some sort of collection of all leaves and branches on a particular branch through a made-up getLeaves() method call.
<%!
public void displayLeaves(Branch branch)
Iterator branches = null;
branches = branch.getLeaves().getIterator();
Object leaf = null;
while( branches.hasMoreItems() )
leaf = branches.nextItem();
if(leaf instanceof branch)
displayLeaves((Branch) leaf);
else
out.println( ((Leaf)leaf).getValue() );
%>This code fragment should be just the logic you need to expand a tree as JSP output. To invoke this method all you have to do is pass the root branch element to the method from within your JSP. Please let me know if you need additional info. -
Function sequence error / Recursive functions error
Hi! I've a little problem over here. I have an application (servlet) that makes recursive functions with DB access. This function contains a resultset that calls the same function again until no more data is found. The problem, is that I'm using JDBC-ODBC bridge (because this must work in SQL Server, Informix, Sybase, Access and Oracle), so I need to make commit of the connection in every resultset. If I make the commit inside the resultset, I got a "Function Sequence error" exception. Of course, I can't close every statement inside the resultset (or at least I don't know how). My code looks like this:
public void myfunction(String odbc,String data1,String data2) throws SQLException,Exception{
//this class, myclassDB, just return a established connection with the DB
Connection connection = myclassDB.connect(odbc);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("query");
while(rs.next()){
//do something with the information
//make recursive
connection.commit();
myfunction(odbc,data1,data2);
statement.close();
connection.close();
}Hope you can help me!
Feel free to email me at [email protected]
Regards!I am not really sure what the question is but...
Presuming that there isn't something wrong with your design (which recursive calls suggest) then you need to extract all of the data, close the resultset/statement then do the recursive calls. If you do processing first then you can still commit on the connection. -
I've used recursive functions with other programming
languages but I seem to be having a problem using it with a UDF in
a cfc file. I'm reading an XSD file, parsing the XSD and populating
an array with the details of any import tags using XMLSearch,
looping through the array and recursively calling the same UDF to
process the child XSD file, so on an so forth. My issue happens
when the UDF gets to the bottom of the recursive call and is going
back up one level to loop to the next item in the array of the
parent UDF call. When the code returns back it gives me an error
saying "The element at position 2 cannot be found." After some
trouble finding out what is happening, it seems the values
contained in the array have been purged. In my experience with
recursive functions, the values of any past calls will still be
available in memory once the process returns back to it. I'm a
litte green using UDFs but I would think it should work the same
way. Is there an issue with the scope of the array variable I am
using? I've attached my code. Any help is appreciated.
Thanks!If I wanted to keep track of which XSD files I have already
processed,
would I be able to insert the file names into an array or
list across
recursive calls? Would I need to declare it within the
cfcomponent tag
before the cffunction tag? Thanks again.
Yes you can. You would create an array an either the global
THIS
(unfortunately the default) or the more preferred VARIABLES
scope. The
this scope is public, the variables scope is private to the
component.
You can declare this global variable in the "pseudo
constructor" space
at the head of the component - which is the space between the
opening
<cfcomponent> tag and the first opening
<cffunction> tag. You could
also declare this global variable in another initialization
style
function that is called before your iteration function is
called
initially.
You would then access and update the values in the global
variable
inside your iteration function just by calling it as
this.aVariable or
variables.aVariable. -
Finder can't continue recursive function
I'm trying to write a recursive function that returns a nested list representing the directory structure (including files) below a starting path. When I run my function, I get an error: "Applescript Error: Finder got an error: Can't continue getDirectoryStructure." This error appears at the first subfolder encountered.
This is one of those "spot my mistake" kind of posts, because I am completely lost. I don't see why it shouldn't be able to continue with my recursive function. Here's the code:
on getDirectoryStructure(startPath)
tell application "Finder"
set dirList to {}
set tempDirList to (get items of folder startPath)
repeat with curItem in tempDirList
if (class of curItem is folder) then
set end of dirList to getDirectoryStructure(startPath & ":" & name of curItem)
else
set end of dirList to curItem
end if
end repeat
end tell
return dirList
end getDirectoryStructure
getDirectoryStructure("Filibuster II:Users:ryos:Documents")I didn't realize I could display this a little better, I'm new to the list, and slowly getting it figured out.
This is a re-post of my previous message...
on script_title()
Filename : minimaldirtraversal.scpt (Script Debugger)
Author : Bill Hernandez
Version : 1.0.0
Updated : Saturday, December 16, 2006 ( 3:18 PM )
end script_title
-- ---------+---------+---------+------------------
on script_notes()
I took one of my directory traversal routines, and took a bunch of stuff
out of it, to create this for you...
Hope it helps,
Bill Hernandez
end script_notes
-- ---------+---------+---------+------------------
property gtimestart : ""
property gtimeend : ""
-- ---------+---------+---------+------------------
-- PROPERTIES REQUIRED FOR PROCESSING TRAVERSAL
-- ---------+---------+---------+------------------
property aFound : {}
property aIgnored : {}
property aFileTypes : {"TEXT"}
property aExtensions : {"txt", "text", "applescript", "html", "php"}
-- ---------+---------+---------+------------------
-- SYSTEM PATHS
-- ---------+---------+---------+------------------
property gdirpathhome : ""
property gdirpathdesktop : ""
property gdirpathdocs : ""
property gdirpathprefs : ""
property gdirpathtemp : ""
-- ---------+---------+---------+------------------
property gtextdelim : ":"
property g_Divider : "--------------------------------------------------" & return
-- ---------+---------+---------+------------------
property aErrors : {} -- list of errors
property gshow_errormessages : true -- set to false to prevent error messages from displaying
property gsend_error_messages_tolog : true
property g_continue : true -- use this instead of [if (not(g_abort)) then]
-- ---------+---------+---------+------------------
on run
set w_props to {contents:""}
--set w_id to my bb_CkWindowExists("Dummy Work Document", "", w_props) -- REMOVE THIS LINE, USED FOR TESTING
tell me
InitGlobals()
set which to "selectchoosefolder" -- aChoices -> { "selectcurrentdocument", "selectopendocuments", "selectchoosefolder"}
main(which) -- place your code in [main]
end tell
end run
-- ---------+---------+---------+------------------
on main(whichAction) -- This is the [main handler] called by [on run]
-- THIS IS A BASIC SHELL FOR ANY SCRIPT
my ProcessRequest(whichAction)
if (g_continue) then
set str to "" -- If this set to "", the following will be used "Would you like to continue processing now?"
-- REMOVE NEXT LINE, USED FOR TESTING
set str to str & "Found : ( " & (count items in aFound) & " ) files..." & return & "Time to process : " & (gtimeend - gtimestart) & " seconds..." & return & return
if (my ConfirmRequest(str)) then
repeat with thisItem in aFound
-- PROCESS EACH (FILE, WINDOW, or DOCUMENT) HERE
-- ******* DO THE WORK HERE
end repeat
end if
end if
set error_title to "Problem Found:" & return & "NOTIFY APPLE COMPUTER"
my error_HandleErrors(aErrors, error_title, gshow_errormessages, gsend_error_messages_tolog)
tell application "BBEdit" to activate
end main
-- ---------+---------+---------+------------------
on ProcessRequest(whichAction)
-- Having "if (whichAction..." here is redundant, instead of having it below, but makes it easier not having to repeat "set gtimestart..." several times
if (whichAction = "selectchoosefolder") then
set startFolder to my ChooseFolder("Select the folder where the files you want to combine are stored?")
end if
-- MAKE SURE "set gtimestart..." COMES AFTER "ChooseFolder(...)"
set gtimestart to (current date) -- REMOVE THIS LINE, USED FOR TESTING
if (g_continue) then
if (whichAction = "selectopendocuments") then
else if (whichAction = "selectchoosefolder") then
my processDirectory(startFolder)
else if (whichAction = "selectcurrentdocument") then
else
set aFound to {}
end if
end if
set gtimeend to (current date) -- REMOVE THIS LINE, USED FOR TESTING
end ProcessRequest
-- ---------+---------+---------+------------------
on InitGlobals()
set aErrors to {} -- list of errors
set gdirpathhome to (path to home folder from user domain as text)
set gdirpathdesktop to (path to desktop from user domain as text)
set gdirpathdocs to (path to documents folder from user domain as text)
set gdirpathprefs to (path to preferences folder from user domain as text)
set gdirpathtemp to (path to temporary items folder from user domain as text)
set g_continue to true
set aFound to {}
set aIgnored to {}
end InitGlobals
-- ---------+---------+---------+------------------
on ChooseFolder(s)
tell application "Finder"
activate
if (s = "") then
set str to "Select the folder you wish to traverse?"
else
set str to s
end if
try
return choose folder with prompt str
on error
set g_continue to false
tell application "BBEdit" to activate
end try
end tell
end ChooseFolder
-- ---------+---------+---------+------------------
on ConfirmRequest(s)
tell application "BBEdit"
activate
set b1 to "Go Ahead..."
set b2 to "Forget It!"
set str to s & "Would you like to continue processing now?"
set aResult to display dialog str buttons {b1, b2} default button {b1}
if ((button returned of aResult) = b1) then
return true
else
return false
end if
end tell
end ConfirmRequest
-- ---------+---------+---------+------------------
on date_GetFullDate(theDate)
set ds to date string of (theDate)
set TS to time string of (theDate)
tell application "Finder"
set TS to ((get characters 1 thru -7 of TS) & (get characters -3 thru -1 of TS)) as string
end tell
set FD to (ds & " (" & TS & ")")
return FD
end date_GetFullDate
-- ---------+---------+---------+------------------
on processDirectory(thisFolder)
tell application "Finder"
set aItems to (get every item of folder thisFolder)
end tell
repeat with I from 1 to the count of aItems
set thisItem to (item I of aItems as alias)
set itemInfo to info for thisItem
set itemName to (name of itemInfo)
if ((folder of itemInfo) is true) then
my processDirectory(thisItem) -- It is a FOLDER
else if ((visible of itemInfo is true) and (alias of itemInfo is false)) then
if (((file type) of itemInfo) is in aFileTypes) then
set aFound to aFound & thisItem -- It is a valid file
else if (((name extension) of itemInfo) is in aExtensions) then
set aFound to aFound & thisItem -- It is a valid file
else
set aIgnored to aIgnored & thisItem -- It is NOT a valid file
end if
else
set aIgnored to aIgnored & thisItem -- It is NOT a valid file
end if
end repeat
end processDirectory
-- ---------+---------+---------+------------------
on error_HandleErrors(aErrorList, header_str, display_error, send2log)
if (header_str = "") then
set myheaderstr to "Errors were encountered during script execution..."
else
set myheaderstr to header_str
end if
if ((count of aErrorList) > 0) then
set s to ""
repeat with my_error in aErrorList
set s to s & my_error & return & return
end repeat
set s to header_str & return & return & s
if (display_error) then
display dialog s buttons {"OK"} default button {"OK"} with icon stop giving up after 15
end if
if (send2log) then
-- NEED TO INCLUDE ROUTINE TO SEND ERRORS TO THE LOG
-- next line is normally enabled
-- my writetofile(s, gfilepathlog, true) -- { (true -> append_data), (false -> overwrite) }
end if
end if
end error_HandleErrors
-- ---------+---------+---------+------------------ -
Revision: 3045
Author: [email protected]
Date: 2008-08-29 10:59:25 -0700 (Fri, 29 Aug 2008)
Log Message:
Fix FB-13900: Expression Evaluator: 'is' and 'as' expressions return 'Target player does not support function calls'
Ticket Links:
http://bugs.adobe.com/jira/browse/FB-13900
Modified Paths:
flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/BinaryOp.java
flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/PlayerSession.javaRevision: 3045
Author: [email protected]
Date: 2008-08-29 10:59:25 -0700 (Fri, 29 Aug 2008)
Log Message:
Fix FB-13900: Expression Evaluator: 'is' and 'as' expressions return 'Target player does not support function calls'
Ticket Links:
http://bugs.adobe.com/jira/browse/FB-13900
Modified Paths:
flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/BinaryOp.java
flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/PlayerSession.java -
How to call a C function calling a Java Method from another C function ?
Hi everyone,
I'm just starting to learn JNI and my problem is that I don't know if it is possible to call a C function calling a Java Method (or doing anything else with JNI) from another C function.
In fact, after receiving datas in a socket made by a C function, I would like to create a class instance (and I don't know how to do it too ; ) ) and init this instance with the strings I received in the socket.
Is all that possible ?
Thank you very much for your help !Hard to understand the question, but by most interpretations the answer is going to be yes.
You do of course understand that JNI is the "API" that sits between Java and C and that every call between the two must go through that. You can't call it directly.
Maybe you are looking for
-
I have songs with ratings in my 'Unrated' playlist
I have songs with ratings in my 'Unrated' plylist. I have 650 songs in my "Unrated' playlists, however 73 of these songs do have ratings. I trid to shift the 5 and 4 star rated into 'My top rated', but they will not shift. Can anybody help? Keep smil
-
Slide size issues with copy from another project
Working with Captivate 4. I have a completed project where I have a slide I would like to re-use in a new project. The recording options for each project are the same - full screen recording. The image is being cut off all the way around the when
-
Insert or update via ViewObjectImpl or ApplicationModuleImpl
How can I insert or update a database from java code? I am attempting to do this in a subclass of ApplicationModuleImpl? The code below throws RowValException: JBO-27024: Failed to validate a row with key ConcUserLoginViewImpl culv =(ConcUserLoginVie
-
I know how to program in java(Should I learn c, c++?)
I know how to program in java. I want to be able to communicate with the hardware on my pc. I also hear that C, C++ is a lower level than java. Lower level meaning it can communicate with the hardware. I know java is very portable could do interfacin
-
Install Flash player 11 and how to enable it in CS5
I just installed flash player 11 in Mac Lion OS and in my browser/visit Adobe player test page; I can see I have flash player 11 installed. However, in Flash CS 5.5, I don't see flash 11 show up in the publish option. How do I need to configure to se