答:
objectResource is an array not an object. Just do it like </p>

```<code>{{objectResource[0].name}}
</code>```

<p>Please consider add checking before printing it because angular will throw an error if the array is undefined </p>

Title: Angular 2 fill variable with return JSON info from HTTP Request

Body:
objectResource is an array not an object. Just do it like

{{objectResource[0].name}}

Please consider add checking before printing it because angular will throw an error if the array is undefined


来源: stackexchange

问:
Cannot resolve method 'map' Java 8 Lambda
I have a set of Objects. I want to filter it based on certain criteria, the ones which meet the criteria, I want to perform some action & then do some more mapping.

```<code>Set<Tasks> v1;
Map<V, Long> vC = v1.stream()
                .filter(t -> someCondition(t))
                //for these filtered operations perform some action
                .forEach(t -> t.performAction(summation(t))
                .map(t->summation(t))
                .collect(groupingBy(identity(), counting()));
</code>```

I get an error at the map Cannot resolve method 'map'. If I remove forEach it works. I know forEach is a terminal operation, but I can't think of alternative.

答:
EDIT: Today (November 2019) I'm not happy with this answer.

The issue is that the Stream.peek method is not being used correctly. In fact, peek is to be used only for debugging purposes.

And, as @Holger states in the comments section, the summation method is being called twice, which clearly indicates this is not a good answer.

I'm keeping my original answer below as a reminder for myself and others, that sometimes streams are not the best fit.

You could use the peek operation to achieve what you want:

```<code>Map<V, Long> vC = v1.stream()
    .filter(t -> someCondition(t))
    .peek(t -> t.performAction(summation(t))
    .map(t->summation(t))
    .collect(groupingBy(identity(), counting()));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a set of Objects. I want to filter it based on certain criteria, the ones which meet the criteria, I want to perform some action & then do some more mapping.

Set<Tasks> v1;
Map<V, Long> vC = v1.stream()
                .filter(t -> someCondition(t))
                //for these filtered operations perform some action
                .forEach(t -> t.performAction(summation(t))
                .map(t->summation(t))
                .collect(groupingBy(identity(), counting()));

I get an error at the map Cannot resolve method 'map'. If I remove forEach it works. I know forEach is a terminal operation, but I can't think of alternative.

Body:
EDIT: Today (November 2019) I'm not happy with this answer.

The issue is that the Stream.peek method is not being used correctly. In fact, peek is to be used only for debugging purposes.

And, as @Holger states in the comments section, the summation method is being called twice, which clearly indicates this is not a good answer.

I'm keeping my original answer below as a reminder for myself and others, that sometimes streams are not the best fit.

You could use the peek operation to achieve what you want:

Map<V, Long> vC = v1.stream()
    .filter(t -> someCondition(t))
    .peek(t -> t.performAction(summation(t))
    .map(t->summation(t))
    .collect(groupingBy(identity(), counting()));

ContentLicense: CC BY-SA 4.0


问:
Python Timeseries interpolation
I have a time series that looks like:

```<code>timeseries1 = [{'price': 250, 'time': 1.52},
    {'price': 251, 'time': 3.65},
    {'price': 253, 'time': 10.1},
    {'price': 254, 'time': 10.99}]
</code>```

I want to be able to interpolate this data so that it moves forward in small timesteps, and have something like:

```<code>timeStep = 0.1
timeseries2 = [{'price': 250, 'time': 1.5},
    {'price': 250, 'time': 1.6},
    {'price': 250, 'time': 1.7},
    ...
    {'price': 250, 'time': 3.6},
    {'price': 251, 'time': 3.7},
    {'price': 251, 'time': 3.8},
    {'price': 251, 'time': 3.9},
    ...
    {'price': 251, 'time': 10.0},
    {'price': 253, 'time': 10.1},
    {'price': 253, 'time': 10.2},
    {'price': 253, 'time': 10.3},
    ...
    {'price': 253, 'time': 10.9},
    {'price': 254, 'time': 11.0}]
</code>```

I'm really unsure of how to do this efficiently and hope there will be a nice pythonic way to do so. What I've tried doing is iterating through timeseries1, with a while loop to append new values to the end of timeseries2, but this seems very inefficient having 2 nested loops.

Edit: Here is the code/algorithm currently being used to do this.

```<code>startTime = math.floor(timeseries1[0]['time'] / timeStep) * timeStep
oldPrice = timeseries1[0]['price']
timeseries3 = []
timeseries3.append(timeseries1[0])
timeseries3[0]['time'] = startTime
for x in timeseries1[1:]:
    while startTime < x['time']:
        timeseries3.append({'price': oldPrice, 'time': startTime})
        startTime += timeStep
    oldPrice = x['price']
</code>```

So that timeseries3 will be the same as timeseries2 in the end.

答:
...hope there will be a nice pythonic way to do so.

Here's a pythonic way of generating a list:  using a generator!  However, I must admit that the following code has issues:

```<code>def timeseries( t1, t2, p1, coeff, step ):
  t = t1
  while t <= t2:
    yield { 'price' :  int( p1 + ( t - t1 ) * coeff), 'time' : t }
    t += step

print list(timeseries( 1.5, 11 , 250 , 0.43 , 0.1 ) )
</code>```

So, the generator might be a "fun" way to create your time series.  However, it needs work due to the floating arithmetic problems I'm seeing when I run it:

```<code>[{'price': 250, 'time': 1.5}, {'price': 250, 'time': 1.6}, {'price': 250, 'time': 1.7000000000000002}, {'price': 250, 'time': 1.8000000000000003}, {'price': 250, 'time': 1.9000000000000004}, {'price': 250, 'time': 2.0000000000000004}, {'price': 250, 'time': 2.1000000000000005}, {'price': 250, 'time': 2.2000000000000006}, {'price': 250, 't...
</code>```

While I think that the above code is easy to read ( well, the variable names could have been more descriptive and perhaps maybe a comment or two would have been nice ) here is an even tighter piece of python code that accomplishes the same thing.  Instead of declaring a generator function, it uses an anonymous generator to accomplish the same thing.

For completeness, I've added a line to figure out the slope of the data to perform the interpolation.

```<code>(t1,p1,t2,p2) = ( 1.52 , 250.0 , 10.99, 254.0 )
coeff = ( p2 - p1) / ( t2  - t1 )
print  list( { 'time' : i/10.0, 'price' :  int (i/10.0*coeff * 100 ) / 100   + p1  } for i in range(int( t1 * 10 ) , int( t2 * 10 )))
</code>```

The code could be generalized even further.  The 10.0 and 100 values are in there to perform integer math and keep only the significant digits that we care about.  This is cleaner than the previous code that had the time value get very wonky just by adding the step of 0.1 to the current time t ( t += step ).   This site talks about using an frange generator built on decimal.Decimal.  In my 2.7 python environment, I couldn't get that to work properly, so I just hard coded the scale/significant digits into the formula ( again, not very general ).

Title: Python Timeseries interpolation

Body:
I have a time series that looks like:

timeseries1 = [{'price': 250, 'time': 1.52},
    {'price': 251, 'time': 3.65},
    {'price': 253, 'time': 10.1},
    {'price': 254, 'time': 10.99}]

I want to be able to interpolate this data so that it moves forward in small timesteps, and have something like:

timeStep = 0.1
timeseries2 = [{'price': 250, 'time': 1.5},
    {'price': 250, 'time': 1.6},
    {'price': 250, 'time': 1.7},
    ...
    {'price': 250, 'time': 3.6},
    {'price': 251, 'time': 3.7},
    {'price': 251, 'time': 3.8},
    {'price': 251, 'time': 3.9},
    ...
    {'price': 251, 'time': 10.0},
    {'price': 253, 'time': 10.1},
    {'price': 253, 'time': 10.2},
    {'price': 253, 'time': 10.3},
    ...
    {'price': 253, 'time': 10.9},
    {'price': 254, 'time': 11.0}]

I'm really unsure of how to do this efficiently and hope there will be a nice pythonic way to do so. What I've tried doing is iterating through timeseries1, with a while loop to append new values to the end of timeseries2, but this seems very inefficient having 2 nested loops.

Edit: Here is the code/algorithm currently being used to do this.

startTime = math.floor(timeseries1[0]['time'] / timeStep) * timeStep
oldPrice = timeseries1[0]['price']
timeseries3 = []
timeseries3.append(timeseries1[0])
timeseries3[0]['time'] = startTime
for x in timeseries1[1:]:
    while startTime < x['time']:
        timeseries3.append({'price': oldPrice, 'time': startTime})
        startTime += timeStep
    oldPrice = x['price']

So that timeseries3 will be the same as timeseries2 in the end.

Body:
...hope there will be a nice pythonic way to do so.

Here's a pythonic way of generating a list:  using a generator!  However, I must admit that the following code has issues:

def timeseries( t1, t2, p1, coeff, step ):
  t = t1
  while t <= t2:
    yield { 'price' :  int( p1 + ( t - t1 ) * coeff), 'time' : t }
    t += step

print list(timeseries( 1.5, 11 , 250 , 0.43 , 0.1 ) )

So, the generator might be a "fun" way to create your time series.  However, it needs work due to the floating arithmetic problems I'm seeing when I run it:

[{'price': 250, 'time': 1.5}, {'price': 250, 'time': 1.6}, {'price': 250, 'time': 1.7000000000000002}, {'price': 250, 'time': 1.8000000000000003}, {'price': 250, 'time': 1.9000000000000004}, {'price': 250, 'time': 2.0000000000000004}, {'price': 250, 'time': 2.1000000000000005}, {'price': 250, 'time': 2.2000000000000006}, {'price': 250, 't...

While I think that the above code is easy to read ( well, the variable names could have been more descriptive and perhaps maybe a comment or two would have been nice ) here is an even tighter piece of python code that accomplishes the same thing.  Instead of declaring a generator function, it uses an anonymous generator to accomplish the same thing.

For completeness, I've added a line to figure out the slope of the data to perform the interpolation.

(t1,p1,t2,p2) = ( 1.52 , 250.0 , 10.99, 254.0 )
coeff = ( p2 - p1) / ( t2  - t1 )
print  list( { 'time' : i/10.0, 'price' :  int (i/10.0*coeff * 100 ) / 100   + p1  } for i in range(int( t1 * 10 ) , int( t2 * 10 )))

The code could be generalized even further.  The 10.0 and 100 values are in there to perform integer math and keep only the significant digits that we care about.  This is cleaner than the previous code that had the time value get very wonky just by adding the step of 0.1 to the current time t ( t += step ).   This site talks about using an frange generator built on decimal.Decimal.  In my 2.7 python environment, I couldn't get that to work properly, so I just hard coded the scale/significant digits into the formula ( again, not very general ).


问:
C# string with decimal into formatted int
I'm looking to try to change a string like 10.00% into an int like 1000.

I've been trying different things but I keep getting FormatException errors.

Here's what I've done to work around it:

```<code>string text = "10.00%";
string s = text.TrimEnd(new char[] {'%'});
float f = float.Parse (s);
int i = (int)f;
i = i*100;
</code>```

Is there a better way?

Per comment - for 10.10% and 12.345% I would want the results of 1010 and 12345

However, for my uses, I would never parse 12.345% as it wouldn't exist in my string value, instead it would be 12.34%

always 2 decimals

答:
Do this:

```<code>var possibleNum = text.Replace(".", "").Replace("%","");
int num;
If(int.TryParse(possibleNum, out num)
{
     // it's an int and the value is in num
}
else
{
    // not int so what do you want to do
}
</code>```

EDIT

In the comments the OP said the string will always be parse-able to a number, so in that case, just do this:

```<code>int num = int.Parse(text.Replace(".", "").Replace("%",""));
</code>```

Body:
I'm looking to try to change a string like 10.00% into an int like 1000.

I've been trying different things but I keep getting FormatException errors.

Here's what I've done to work around it:

string text = "10.00%";
string s = text.TrimEnd(new char[] {'%'});
float f = float.Parse (s);
int i = (int)f;
i = i*100;

Is there a better way?

Per comment - for 10.10% and 12.345% I would want the results of 1010 and 12345

However, for my uses, I would never parse 12.345% as it wouldn't exist in my string value, instead it would be 12.34%

always 2 decimals

Body:
Do this:

var possibleNum = text.Replace(".", "").Replace("%","");
int num;
If(int.TryParse(possibleNum, out num)
{
     // it's an int and the value is in num
}
else
{
    // not int so what do you want to do
}

EDIT

In the comments the OP said the string will always be parse-able to a number, so in that case, just do this:

int num = int.Parse(text.Replace(".", "").Replace("%",""));


问:
Is there a sleep() function for Android NDK?
Under Android NDK, is there a sleep() function which sleeps for X miliseconds, but do not block the event loop?

We are writing API tests to work on Mac, Windows, and Android. So far, we have implemented some sort of sleep() for Mac and Windows, but we are all new to Android NDK and need some help there. Thank you in advance.

答:
You can use [Handler.postDelayed][1] to schedule a Runnable to run after a set time, the event loop will continue to work in the meantime.

[1]: http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long)

ContentLicense: CC BY-SA 2.5


问:
Need assistance with VBA
I have an import code that works perfectly on my 2013 64bit excel; however, I have users that are using 2010 Excel with 32bit and the code does not work.  I would be very grateful if someone would look at the below code and tell me what I need to change in order for my 2010 32bit users to be able to use it:</p>

```<code>Sub TransferData()
''<<<<unprotect code
Dim i As Integer
For i = 1 To Sheets.Count
Sheets(i).Unprotect password:="ADMIN"
Next i
'
''<<<<<main code
'
Application.ScreenUpdating = False
Sheets("Dashboard").Activate
Sheets("DASF Data").Range("DASF_Range").ClearContents
'
Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = ActiveWorkbook

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")

If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)

For Each Sheet In wb2.Sheets
    If Sheet.Visible = True Then
      Range("A2:Y10000").Select
Selection.Copy
Windows("DASF MANAGEMENT TOOL (CONUS Ver 1.0).XLSB").Activate
Sheets("DASF Data").Select
Range("A2").Select
ActiveSheet.Paste
Application.CutCopyMode = False

Sheets("Dashboard").Activate

End If
Next Sheet
End If
Workbooks("DASF.XLS").Close SaveChanges:=False

End Sub
</code>```

答:
That error number does not necessarily have anything specifically to do with your listed code. It could be an error anywhere in your modules: or it could be corrupt code in the compiled version of one of your modules. It could even be a broken library reference.

To exclude the first possibility, do a manual "compile all' of your code.

To fix the second possibility, create a new spreadsheet, and copy the text from your old spreadsheet into new modules in your new spreadsheet. Or download and use an Excel 'decompiler'.

Title: Need assistance with VBA

Body:
I have an import code that works perfectly on my 2013 64bit excel; however, I have users that are using 2010 Excel with 32bit and the code does not work.  I would be very grateful if someone would look at the below code and tell me what I need to change in order for my 2010 32bit users to be able to use it:

Sub TransferData()
''<<<<unprotect code
Dim i As Integer
For i = 1 To Sheets.Count
Sheets(i).Unprotect password:="ADMIN"
Next i
'
''<<<<<main code
'
Application.ScreenUpdating = False
Sheets("Dashboard").Activate
Sheets("DASF Data").Range("DASF_Range").ClearContents
'
Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = ActiveWorkbook

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")

If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)

For Each Sheet In wb2.Sheets
    If Sheet.Visible = True Then
      Range("A2:Y10000").Select
Selection.Copy
Windows("DASF MANAGEMENT TOOL (CONUS Ver 1.0).XLSB").Activate
Sheets("DASF Data").Select
Range("A2").Select
ActiveSheet.Paste
Application.CutCopyMode = False

Sheets("Dashboard").Activate

End If
Next Sheet
End If
Workbooks("DASF.XLS").Close SaveChanges:=False

End Sub


问:
How to execute promises sequentially, passing the parameters from an array?
```<code>var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))
</code>```

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

答:
I would use babel and do it this way:

    let args = [1, 2, 3];

    const myPromise = async x => console.log('arg:',x);

    const test = async () => {
      for (let task of args.map(myPromise))
        await task;
    }

    test().then(console.log('Done'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/babel-standalone@6.24.0/babel.min.js"></script></code>```

Body:
var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

Body:
I would use babel and do it this way:

    let args = [1, 2, 3];

    const myPromise = async x => console.log('arg:',x);

    const test = async () => {
      for (let task of args.map(myPromise))
        await task;
    }

    test().then(console.log('Done'));

<script src="https://unpkg.com/babel-standalone@6.24.0/babel.min.js"></script>


问:
Using aldeed:autoform with iron:router
I added aldeed:autoform for my meteor project by including following packages.

```<code>aldeed:collection2
aldeed:autoform
</code>```

After the inclusion, the routing of the application is crashed. For every route it says that the routes are not defined.

And after I remove the above aldeed:autoform packages from the project, the routing worked as expected. I want to know whether these two packages are incompatible or how to get the project working with these packages?

答:
I'm fairly certain that IronRouter and Autoform are compatible with each other (it is a common combination).  I'm wondering if you are having issues because of how you installed collection2.  Per the latest Autoform README.md...

AutoForm 6.0 is now available and requires switching your app to using the SimpleSchema package from NPM and aldeed:collection2-core package.

I have not tested this but perhaps try following these instructions instead.

Title: Using aldeed:autoform with iron:router

Body:
I added aldeed:autoform for my meteor project by including following packages.

aldeed:collection2
aldeed:autoform

After the inclusion, the routing of the application is crashed. For every route it says that the routes are not defined.

And after I remove the above aldeed:autoform packages from the project, the routing worked as expected. I want to know whether these two packages are incompatible or how to get the project working with these packages?


问:
How can I make Drupal server small bits of content via AJAX?
If you want to make Drupal server (themed) pages, it is pretty straight forward, but what if you want it to serve small chunks of data (e.g. as JSON).

I'd like to have parts of my page load asynchronously, e.g. a block that refreshes every 10' with the active users.

What is the proper way to go about it in Drupal?


问:
mysql get rollup value
I want to ask about mysql with rollup only get rollup value, this is my code

```<code>SELECT tbldept.CodeDept AS Dept,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
       CONCAT(ROUND(20), '%') AS TargetOT,
       round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
    ON tbldept.CodeDept = tblemp.CodeDept AND
       tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
      tbldept.CodeDept != 'HRT' AND
      tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP;
</code>```

result of rollup query:

how can i only get the rollup values? Thanks before

答:
If you just want the row of rollup, simply use having:

```<code>SELECT tbldept.CodeDept AS Dept,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
       CONCAT(ROUND(20), '%') AS TargetOT,
       round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
    ON tbldept.CodeDept = tblemp.CodeDept AND
       tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
      tbldept.CodeDept != 'HRT' AND
      tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP
HAVING Dept IS NULL;
</code>```

Edit:

having should work, check if there are some other reasons exist or not.

Or just wrap your query with a subquery:

```<code>SELECT *
FROM (
    SELECT tbldept.CodeDept AS Dept,
           SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
           SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
           CONCAT(ROUND(20), '%') AS TargetOT,
           round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
    FROM tbldept
    LEFT JOIN tblemp
        ON tbldept.CodeDept = tblemp.CodeDept AND
           tblemp.class = "DIR"
    WHERE tbldept.CodeDept != 'FIN' AND
          tbldept.CodeDept != 'HRT' AND
          tbldept.CodeDept != 'ISD'
    GROUP BY tbldept.CodeDept with ROLLUP
) t
WHERE Dept IS NULL;
</code>```

Title: mysql get rollup value

Body:
I want to ask about mysql with rollup only get rollup value, this is my code

SELECT tbldept.CodeDept AS Dept,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
       CONCAT(ROUND(20), '%') AS TargetOT,
       round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
    ON tbldept.CodeDept = tblemp.CodeDept AND
       tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
      tbldept.CodeDept != 'HRT' AND
      tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP;

result of rollup query:

how can i only get the rollup values? Thanks before

Body:
If you just want the row of rollup, simply use having:

SELECT tbldept.CodeDept AS Dept,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
       SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
       CONCAT(ROUND(20), '%') AS TargetOT,
       round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
FROM tbldept
LEFT JOIN tblemp
    ON tbldept.CodeDept = tblemp.CodeDept AND
       tblemp.class = "DIR"
WHERE tbldept.CodeDept != 'FIN' AND
      tbldept.CodeDept != 'HRT' AND
      tbldept.CodeDept != 'ISD'
GROUP BY tbldept.CodeDept with ROLLUP
HAVING Dept IS NULL;

Edit:

having should work, check if there are some other reasons exist or not.

Or just wrap your query with a subquery:

SELECT *
FROM (
    SELECT tbldept.CodeDept AS Dept,
           SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) AS headcount,
           SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 AS RegHrsEst,
           CONCAT(ROUND(20), '%') AS TargetOT,
           round(SUM(CASE WHEN tblemp.Status = '1' THEN 1 ELSE 0 END) * 144 * 0.2) AS OTHrsBdgt
    FROM tbldept
    LEFT JOIN tblemp
        ON tbldept.CodeDept = tblemp.CodeDept AND
           tblemp.class = "DIR"
    WHERE tbldept.CodeDept != 'FIN' AND
          tbldept.CodeDept != 'HRT' AND
          tbldept.CodeDept != 'ISD'
    GROUP BY tbldept.CodeDept with ROLLUP
) t
WHERE Dept IS NULL;


问:
Retrieving data from database and increment by one
I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.

```<code>public Abstract() throws Exception {

    Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
    initComponents();

    Statement st = null;
    ResultSet rs;

    try {
        String sql = "SELECT ID from bidding_abstractofprices";
        st = cn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        while(rs.next()){
            int id = Integer.parseInt(rs.getString("ID")) + 1;
            lblTransacID.setText(String.valueOf(id));
        }
    }catch (Exception ex){
    }
}
</code>```

答:
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:

```<code>public Abstract() throws Exception {
    // Allow all your components to initialize first.
    initComponents();

    Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
    Statement st = null;
    ResultSet rs;

    try {
        String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
        st = cn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        int id = 0;
        while(rs.next()){
            id = rs.getInt("ID") + 1;
        }
        lblTransacID.setText(String.valueOf(id));
        rs.close();
        st.close();
        cn.close();
    } catch (SQLException ex) {
         ex.printStackTrace();
    }
}
</code>```

Body:
I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.

public Abstract() throws Exception {

    Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
    initComponents();

    Statement st = null;
    ResultSet rs;

    try {
        String sql = "SELECT ID from bidding_abstractofprices";
        st = cn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        while(rs.next()){
            int id = Integer.parseInt(rs.getString("ID")) + 1;
            lblTransacID.setText(String.valueOf(id));
        }
    }catch (Exception ex){
    }
}

Body:
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:

public Abstract() throws Exception {
    // Allow all your components to initialize first.
    initComponents();

    Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
    Statement st = null;
    ResultSet rs;

    try {
        String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
        st = cn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        int id = 0;
        while(rs.next()){
            id = rs.getInt("ID") + 1;
        }
        lblTransacID.setText(String.valueOf(id));
        rs.close();
        st.close();
        cn.close();
    } catch (SQLException ex) {
         ex.printStackTrace();
    }
}


问:
Xml Deserialize missing strings
I am deserializing an object from xml, but the strings in KeywordList and ResponseList always end up empty.

Tried lots of things and can't seem to get it right. If I loop through it with a reader then the values show up.

```<code>using System;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ElizaResponses));
            using (XmlReader reader = XmlReader.Create("eliza.xml"))
            {
                ElizaResponses responses = (ElizaResponses)serializer.Deserialize(reader);
                reader.Close();

                // This reads in all data
                //StreamReader reader = new StreamReader("eliza.xml");
                //reader.ReadToEnd();
                //reader.MoveToContent();
                //while (reader.Read())
                //{
                //    if(reader.NodeType == XmlNodeType.Text)
                //    {
                //        Console.WriteLine("{0}, {1}", reader.NodeType, reader.Value);
                //    }
                //    else
                //    {
                //    Console.WriteLine("{0}, {1}", reader.NodeType, reader.Name);
                //    }
                //}

            }

            Console.ReadLine();
        }
    }

    [Serializable]
    [XmlRoot("ElizaResponses")]
    [XmlType("ElizaResponses")]
    public sealed class ElizaResponses
    {
        ElizaConversation[] chatList;

        public ElizaConversation[] ChatList
        {
            get { return this.chatList; }
            set { this.chatList = value; }
        }
    }

    [Serializable]
    public sealed class ElizaConversation
    {
        // Tried List<string>, string[], StringCollection
        StringCollection keywordList = new StringCollection();
        StringCollection responseList = new StringCollection();

        // Tried [XmlArray], [XmlElement]
        [XmlElement("KeywordList")]
        [XmlArrayItem("string", typeof(string))]
        StringCollection KeywordList
        {
            get { return this.keywordList; }
            set { this.keywordList = value; }
        }

        [XmlArray("ResponseList")]
        [XmlArrayItem("string", typeof(string))]
        StringCollection ResponseList
        {
            get { return this.responseList; }
            set { this.responseList = value; }
        }
    }
}
</code>```

Here is the example xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ElizaResponses>
  <ChatList>
    <ElizaConversation>
      <KeywordList>
        <string>ok</string>
      </KeywordList>
      <ResponseList>
        <string>cool.</string>
        <string>great.</string>
        <string>:)</string>
      </ResponseList>
    </ElizaConversation>
    <ElizaConversation>
      <KeywordList>
        <string>shutup</string>
        <string>shut up</string>
      </KeywordList>
      <ResponseList>
        <string>make me.</string>
        <string>no I won't.</string>
      </ResponseList>
    </ElizaConversation>
  </ChatList>
</ElizaResponses>
</code>```

Should add I get no exceptions and have turned up the error messaging in the app.config file

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <system.diagnostics>
    <switches>
      <add name="XmlSerialization.Compilation" value="4" />
    </switches>
  </system.diagnostics>
</configuration>
</code>```

答: Found the answer. The properties can't be set because they are not public.</p>

Title: Xml Deserialize missing strings

Body:
I am deserializing an object from xml, but the strings in KeywordList and ResponseList always end up empty.

Tried lots of things and can't seem to get it right. If I loop through it with a reader then the values show up.

using System;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ElizaResponses));
            using (XmlReader reader = XmlReader.Create("eliza.xml"))
            {
                ElizaResponses responses = (ElizaResponses)serializer.Deserialize(reader);
                reader.Close();

                // This reads in all data
                //StreamReader reader = new StreamReader("eliza.xml");
                //reader.ReadToEnd();
                //reader.MoveToContent();
                //while (reader.Read())
                //{
                //    if(reader.NodeType == XmlNodeType.Text)
                //    {
                //        Console.WriteLine("{0}, {1}", reader.NodeType, reader.Value);
                //    }
                //    else
                //    {
                //    Console.WriteLine("{0}, {1}", reader.NodeType, reader.Name);
                //    }
                //}

            }

            Console.ReadLine();
        }
    }

    [Serializable]
    [XmlRoot("ElizaResponses")]
    [XmlType("ElizaResponses")]
    public sealed class ElizaResponses
    {
        ElizaConversation[] chatList;

        public ElizaConversation[] ChatList
        {
            get { return this.chatList; }
            set { this.chatList = value; }
        }
    }

    [Serializable]
    public sealed class ElizaConversation
    {
        // Tried List<string>, string[], StringCollection
        StringCollection keywordList = new StringCollection();
        StringCollection responseList = new StringCollection();

        // Tried [XmlArray], [XmlElement]
        [XmlElement("KeywordList")]
        [XmlArrayItem("string", typeof(string))]
        StringCollection KeywordList
        {
            get { return this.keywordList; }
            set { this.keywordList = value; }
        }

        [XmlArray("ResponseList")]
        [XmlArrayItem("string", typeof(string))]
        StringCollection ResponseList
        {
            get { return this.responseList; }
            set { this.responseList = value; }
        }
    }
}

Here is the example xml

<?xml version="1.0" encoding="utf-8"?>
<ElizaResponses>
  <ChatList>
    <ElizaConversation>
      <KeywordList>
        <string>ok</string>
      </KeywordList>
      <ResponseList>
        <string>cool.</string>
        <string>great.</string>
        <string>:)</string>
      </ResponseList>
    </ElizaConversation>
    <ElizaConversation>
      <KeywordList>
        <string>shutup</string>
        <string>shut up</string>
      </KeywordList>
      <ResponseList>
        <string>make me.</string>
        <string>no I won't.</string>
      </ResponseList>
    </ElizaConversation>
  </ChatList>
</ElizaResponses>

Should add I get no exceptions and have turned up the error messaging in the app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <system.diagnostics>
    <switches>
      <add name="XmlSerialization.Compilation" value="4" />
    </switches>
  </system.diagnostics>
</configuration>


问:
What is the best way to get the Date object for the timestamp 1224642020?
In Ruby, what's the best way to get the Date object for the timestamp 1224642020?

答:
```<code>Time.at(122...)
</code>```

Not sure how to convert it to Date.

Body:
Time.at(122...)

Not sure how to convert it to Date.


答:
Rather than continuing to attempt to hand-generate your types, you should start by auto-generating them and verifying the auto-generated types work.  Only then, simplify as needed.  If you post your XML to https://xmltocsharp.azurewebsites.net/, you can generate classes that will deserialize your XML:

```<code>[XmlRoot(ElementName = "KeywordList")]
public class KeywordList
{
    [XmlElement(ElementName = "string")]
    public List<string> String { get; set; }
}

[XmlRoot(ElementName = "ResponseList")]
public class ResponseList
{
    [XmlElement(ElementName = "string")]
    public List<string> String { get; set; }
}

[XmlRoot(ElementName = "ElizaConversation")]
public class ElizaConversation
{
    [XmlElement(ElementName = "KeywordList")]
    public KeywordList KeywordList { get; set; }
    [XmlElement(ElementName = "ResponseList")]
    public ResponseList ResponseList { get; set; }
}

[XmlRoot(ElementName = "ChatList")]
public class ChatList
{
    [XmlElement(ElementName = "ElizaConversation")]
    public List<ElizaConversation> ElizaConversation { get; set; }
}

[XmlRoot(ElementName = "ElizaResponses")]
public class ElizaResponses
{
    [XmlElement(ElementName = "ChatList")]
    public ChatList ChatList { get; set; }
}
</code>```

You can verify using your code above that this version of ElizaResponses will deserialize your XML.  However, these can be simplified.

Firstly, merge KeywordList and ResponseList into StringList:

```<code>public class StringList
{
    [XmlElement(ElementName = "string")]
    public List<string> String { get; set; }
}

[XmlRoot(ElementName = "ElizaConversation")]
public class ElizaConversation
{
    [XmlElement(ElementName = "KeywordList")]
    public StringList KeywordList { get; set; }
    [XmlElement(ElementName = "ResponseList")]
    public StringList ResponseList { get; set; }
}
</code>```

Next, eliminate StringList entirely replacing it with List<string<>.  Since an extra level of container class is being eliminated, the two [XmlElement] attributes will need to replaced with [XmlArray] and [XmlArrayItem] resulting in the following final versions:

```<code>[XmlRoot(ElementName = "ElizaConversation")]
public class ElizaConversation
{
    [XmlArray(ElementName = "KeywordList")]
    [XmlArrayItem(ElementName = "string")]
    public List<string> KeywordList { get; set; }
    [XmlArray(ElementName = "ResponseList")]
    [XmlArrayItem(ElementName = "string")]
    public List<string> ResponseList { get; set; }
}

[XmlRoot(ElementName = "ChatList")]
public class ChatList
{
    [XmlElement(ElementName = "ElizaConversation")]
    public List<ElizaConversation> ElizaConversation { get; set; }
}

[XmlRoot(ElementName = "ElizaResponses")]
public class ElizaResponses
{
    [XmlElement(ElementName = "ChatList")]
    public ChatList ChatList { get; set; }
}
</code>```

Your initial attempt included the following problems:

The non-generic, obsolete StringCollection should be avoided.

In the [XmlArrayItem("Item", typeof(string))] declarations, the name "Item" is wrong.  It should have been "string".

[XmlElement] cannot be combined with [XmlArrayItem].

The properties KeywordList and ResponseList are not public.  XmlSerializer only serializes public members.

Sample fiddle.

Title: Xml Deserialize missing strings

Body:
Rather than continuing to attempt to hand-generate your types, you should start by auto-generating them and verifying the auto-generated types work.  Only then, simplify as needed.  If you post your XML to https://xmltocsharp.azurewebsites.net/, you can generate classes that will deserialize your XML:

[XmlRoot(ElementName = "KeywordList")]
public class KeywordList
{
    [XmlElement(ElementName = "string")]
    public List<string> String { get; set; }
}

[XmlRoot(ElementName = "ResponseList")]
public class ResponseList
{
    [XmlElement(ElementName = "string")]
    public List<string> String { get; set; }
}

[XmlRoot(ElementName = "ElizaConversation")]
public class ElizaConversation
{
    [XmlElement(ElementName = "KeywordList")]
    public KeywordList KeywordList { get; set; }
    [XmlElement(ElementName = "ResponseList")]
    public ResponseList ResponseList { get; set; }
}

[XmlRoot(ElementName = "ChatList")]
public class ChatList
{
    [XmlElement(ElementName = "ElizaConversation")]
    public List<ElizaConversation> ElizaConversation { get; set; }
}

[XmlRoot(ElementName = "ElizaResponses")]
public class ElizaResponses
{
    [XmlElement(ElementName = "ChatList")]
    public ChatList ChatList { get; set; }
}

You can verify using your code above that this version of ElizaResponses will deserialize your XML.  However, these can be simplified.

Firstly, merge KeywordList and ResponseList into StringList:

public class StringList
{
    [XmlElement(ElementName = "string")]
    public List<string> String { get; set; }
}

[XmlRoot(ElementName = "ElizaConversation")]
public class ElizaConversation
{
    [XmlElement(ElementName = "KeywordList")]
    public StringList KeywordList { get; set; }
    [XmlElement(ElementName = "ResponseList")]
    public StringList ResponseList { get; set; }
}

Next, eliminate StringList entirely replacing it with List<string<>.  Since an extra level of container class is being eliminated, the two [XmlElement] attributes will need to replaced with [XmlArray] and [XmlArrayItem] resulting in the following final versions:

[XmlRoot(ElementName = "ElizaConversation")]
public class ElizaConversation
{
    [XmlArray(ElementName = "KeywordList")]
    [XmlArrayItem(ElementName = "string")]
    public List<string> KeywordList { get; set; }
    [XmlArray(ElementName = "ResponseList")]
    [XmlArrayItem(ElementName = "string")]
    public List<string> ResponseList { get; set; }
}

[XmlRoot(ElementName = "ChatList")]
public class ChatList
{
    [XmlElement(ElementName = "ElizaConversation")]
    public List<ElizaConversation> ElizaConversation { get; set; }
}

[XmlRoot(ElementName = "ElizaResponses")]
public class ElizaResponses
{
    [XmlElement(ElementName = "ChatList")]
    public ChatList ChatList { get; set; }
}

Your initial attempt included the following problems:

The non-generic, obsolete StringCollection should be avoided.

In the [XmlArrayItem("Item", typeof(string))] declarations, the name "Item" is wrong.  It should have been "string".

[XmlElement] cannot be combined with [XmlArrayItem].

The properties KeywordList and ResponseList are not public.  XmlSerializer only serializes public members.

Sample fiddle.


问:
SugarCRM 6.5 CE: how to remove button in detailview according to a condition
I'm trying to remove buttons in detail view of a Lead if it is alredy converted.

I saw a similar question and it use javascript to hide buttons. I'm trying to obtain same result via php.

This is my view.detail.php in custom\modules\Leads\views\ folder

```<code>class LeadsViewDetail extends ViewDetail {

    function __construct(){
        parent::__construct();
    }

    function preDisplay() {
        parent::preDisplay();

        if($this->bean->converted==1) {
            echo "hide";
            foreach ($this->dv->defs['templateMeta']['form']['buttons'] as $key => $value) {
                unset($this->dv->defs['templateMeta']['form']['buttons'][$key]);
            }
        } else {
            echo "show";
        }
    }
}
</code>```

Using this code, after a Quick Repair & Rebuilt, I see "hide" or "show" correctly according to the Lead status but buttons are not updated correctly.

If I open a converted Lead after QR&R, I will never see the buttons.

If I open a unconverted Lead after QR&R, I will see the buttons all times.

I'm stuck with this situation. Can anyone explain me where is the problem? How I can solve it?
Every help is very appreciated.

答:
You can probably handle this without extending the ViewDetail by using Smarty logic ("customCode") in custom/modules/Leads/metadata/detailviewdefs.php. It looks like the Convert button is already only rendered when the user has Edit privileges, so it's not a big deal to add one more condition to it...

```<code>$viewdefs['Leads']['DetailView']['templateMeta']['form]['buttons'][] = array('customCode' => '
{if $bean->aclAccess("edit") && $bean->converted}
<input title="{$MOD.LBL_CONVERTLEAD_TITLE}"
  accessKey="{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}"
  type="button"
  class="button"
  name="convert"
  value="{$MOD.LBL_CONVERTLEAD}"
  onClick="document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'" />
{/if}');
</code>```

Alternatively, if you do have several conditions and they'd get too messy or difficult for Smarty logic to be reasonable, we can combine a small amount of Smarty Logic with the extended ViewDetail.

This except of custom/modules/Leads/metadata/detailviewdefs.php is actually the out-of-the-box file from SugarCRM CE 6.5.24, where it looks like they've actually tried to make this customization easier by supplying a Smarty var $DISABLE_CONVERT_ACTION. For reference, it simply needs the global config variable disable_convert_lead to be set and enabled, but I suspect that this was a relatively new feature not included in earlier versions. Still, it's a good example of using the View to set a simple Smarty variable that we can pivot on:

```<code><?php
$viewdefs['Leads']['DetailView'] = array (
  'templateMeta' => array (
    'form' => array (
      'buttons' => array (
        'EDIT',
        'DUPLICATE',
        'DELETE',
        array (
          'customCode' => '{if $bean->aclAccess("edit") && !$DISABLE_CONVERT_ACTION}<input title="{$MOD.LBL_CONVERTLEAD_TITLE}" accessKey="{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}" type="button" class="button" onClick="document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'" name="convert" value="{$MOD.LBL_CONVERTLEAD}">{/if}',
          //Bug#51778: The custom code will be replaced with sugar_html. customCode will be deplicated.
          'sugar_html' => array(
            'type' => 'button',
            'value' => '{$MOD.LBL_CONVERTLEAD}',
            'htmlOptions' => array(
              'title' => '{$MOD.LBL_CONVERTLEAD_TITLE}',
              'accessKey' => '{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}',
              'class' => 'button',
              'onClick' => 'document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'',
              'name' => 'convert',
              'id' => 'convert_lead_button',
            ),
            'template' => '{if $bean->aclAccess("edit") && !$DISABLE_CONVERT_ACTION}[CONTENT]{/if}',
          ),
        ),
</code>```

We can combine this $DISABLE_CONVERT_ACTION reference with a custom/modules/Leads/views/view.detail.php like the following to set it based on whatever condition we want:

```<code><?php
require_once('modules/Leads/views/view.detail.php');
class CustomLeadsViewDetail extends LeadsViewDetail {

  /*
   * while we might normally like to call parent::display() in this method to
   * best emulate what the parnts will do, we instead here copy-and-paste the
   * parent methods' content because LeadsViewDetail::display() will set the
   * DISABLE_CONVERT_ACTION Smarty var differently than we want.
   */
  public function display(){
    global $sugar_config;

    // Example One: Disable Conversion when status is Converted
    $disableConvert = ($this->bean->status == 'Converted');

    // Example Two: Disable Conversion when there is at lead one related Call
    // where the status is Held
    $disableConvert = FALSE;
    $this->bean->load_relationships('calls');
    foreach($this->bean->calls->getBeans() as $call){
      if($call->status == 'Held'){
        $disableConvert = TRUE;
        break; // exit foreach()
      }
    }

    // Example Three: Disable Conversion if the User is in a specific Role, e.g.
    // Interns who are great for data entry in Leads but shouldn't be making
    // actual sales
    global $current_user;
    $disableConvert = $current_user->check_role_membership('No Lead Conversions');

    // In any of the above examples, once we have $disableConvert set up
    // as we want, let the Smarty template know.
    $this->ss->assign("DISABLE_CONVERT_ACTION", $disableConvert);

    // copied from ViewDetail::display();
    if(empty($this->bean->id)) {
      sugar_die($GLOBALS['app_strings']['ERROR_NO_RECORD']);
    }
    $this->dv->process();
    echo $this->dv->display();
  }
}
</code>```

Body:
I'm trying to remove buttons in detail view of a Lead if it is alredy converted.

I saw a similar question and it use javascript to hide buttons. I'm trying to obtain same result via php.

This is my view.detail.php in custom\modules\Leads\views\ folder

class LeadsViewDetail extends ViewDetail {

    function __construct(){
        parent::__construct();
    }

    function preDisplay() {
        parent::preDisplay();

        if($this->bean->converted==1) {
            echo "hide";
            foreach ($this->dv->defs['templateMeta']['form']['buttons'] as $key => $value) {
                unset($this->dv->defs['templateMeta']['form']['buttons'][$key]);
            }
        } else {
            echo "show";
        }
    }
}

Using this code, after a Quick Repair & Rebuilt, I see "hide" or "show" correctly according to the Lead status but buttons are not updated correctly.

If I open a converted Lead after QR&R, I will never see the buttons.

If I open a unconverted Lead after QR&R, I will see the buttons all times.

I'm stuck with this situation. Can anyone explain me where is the problem? How I can solve it?
Every help is very appreciated.

Body:
You can probably handle this without extending the ViewDetail by using Smarty logic ("customCode") in custom/modules/Leads/metadata/detailviewdefs.php. It looks like the Convert button is already only rendered when the user has Edit privileges, so it's not a big deal to add one more condition to it...

$viewdefs['Leads']['DetailView']['templateMeta']['form]['buttons'][] = array('customCode' => '
{if $bean->aclAccess("edit") && $bean->converted}
<input title="{$MOD.LBL_CONVERTLEAD_TITLE}"
  accessKey="{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}"
  type="button"
  class="button"
  name="convert"
  value="{$MOD.LBL_CONVERTLEAD}"
  onClick="document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'" />
{/if}');

Alternatively, if you do have several conditions and they'd get too messy or difficult for Smarty logic to be reasonable, we can combine a small amount of Smarty Logic with the extended ViewDetail.

This except of custom/modules/Leads/metadata/detailviewdefs.php is actually the out-of-the-box file from SugarCRM CE 6.5.24, where it looks like they've actually tried to make this customization easier by supplying a Smarty var $DISABLE_CONVERT_ACTION. For reference, it simply needs the global config variable disable_convert_lead to be set and enabled, but I suspect that this was a relatively new feature not included in earlier versions. Still, it's a good example of using the View to set a simple Smarty variable that we can pivot on:

<?php
$viewdefs['Leads']['DetailView'] = array (
  'templateMeta' => array (
    'form' => array (
      'buttons' => array (
        'EDIT',
        'DUPLICATE',
        'DELETE',
        array (
          'customCode' => '{if $bean->aclAccess("edit") && !$DISABLE_CONVERT_ACTION}<input title="{$MOD.LBL_CONVERTLEAD_TITLE}" accessKey="{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}" type="button" class="button" onClick="document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'" name="convert" value="{$MOD.LBL_CONVERTLEAD}">{/if}',
          //Bug#51778: The custom code will be replaced with sugar_html. customCode will be deplicated.
          'sugar_html' => array(
            'type' => 'button',
            'value' => '{$MOD.LBL_CONVERTLEAD}',
            'htmlOptions' => array(
              'title' => '{$MOD.LBL_CONVERTLEAD_TITLE}',
              'accessKey' => '{$MOD.LBL_CONVERTLEAD_BUTTON_KEY}',
              'class' => 'button',
              'onClick' => 'document.location=\'index.php?module=Leads&action=ConvertLead&record={$fields.id.value}\'',
              'name' => 'convert',
              'id' => 'convert_lead_button',
            ),
            'template' => '{if $bean->aclAccess("edit") && !$DISABLE_CONVERT_ACTION}[CONTENT]{/if}',
          ),
        ),

We can combine this $DISABLE_CONVERT_ACTION reference with a custom/modules/Leads/views/view.detail.php like the following to set it based on whatever condition we want:

<?php
require_once('modules/Leads/views/view.detail.php');
class CustomLeadsViewDetail extends LeadsViewDetail {

  /*
   * while we might normally like to call parent::display() in this method to
   * best emulate what the parnts will do, we instead here copy-and-paste the
   * parent methods' content because LeadsViewDetail::display() will set the
   * DISABLE_CONVERT_ACTION Smarty var differently than we want.
   */
  public function display(){
    global $sugar_config;

    // Example One: Disable Conversion when status is Converted
    $disableConvert = ($this->bean->status == 'Converted');

    // Example Two: Disable Conversion when there is at lead one related Call
    // where the status is Held
    $disableConvert = FALSE;
    $this->bean->load_relationships('calls');
    foreach($this->bean->calls->getBeans() as $call){
      if($call->status == 'Held'){
        $disableConvert = TRUE;
        break; // exit foreach()
      }
    }

    // Example Three: Disable Conversion if the User is in a specific Role, e.g.
    // Interns who are great for data entry in Leads but shouldn't be making
    // actual sales
    global $current_user;
    $disableConvert = $current_user->check_role_membership('No Lead Conversions');

    // In any of the above examples, once we have $disableConvert set up
    // as we want, let the Smarty template know.
    $this->ss->assign("DISABLE_CONVERT_ACTION", $disableConvert);

    // copied from ViewDetail::display();
    if(empty($this->bean->id)) {
      sugar_die($GLOBALS['app_strings']['ERROR_NO_RECORD']);
    }
    $this->dv->process();
    echo $this->dv->display();
  }
}


问:
better way to improve my code without many for loops
I'm trying to optimize my code. I have an array of JSON objects and I need to loop through the objects and see if they contain several words and keep track of the JSON objects if the contain all the worlds, not just one but all of them. I don't want to pass to the function an array of worlds because I feel I will have to add another for loop.Right now, my code goes through every input field and if it's not empty call the function and pass the world in the input field. My code works fine if I just check one word, but I need to check more than one and keep track of the objects that contain all the worlds

My code:
 workOrdersArray it's a global array.

```<code>function searchWO (workOrdersArray) {
            var filteredWO = [];

            for (var i=0; i < workOrdersArray.length; i++) {
                for (var prop in workOrdersArray[i]) {
                    if (myArray[i][prop] == nameKey) {
                            filteredWO.push(workOrdersArray[i]);
                    }
                }

            }
        }
</code>```

Example:
If one input field has the world "Hello" and another input field says "Bye"

```<code>var array = [
    { "x":"Bye","y":"Bye","z":"Hello"},
    { "x":"Bye","y":"Bye","z":"Hi"},
    { "x":"Bye","y":"Hello","z":"Hi"},
];
</code>```

I will store the JSON object inside of the array in an separate array. So the new array will have the obj1 and obj3

答:
I don't think your array is a valid JavaScript array, but if your array is of the form like

```<code>var array = [
    { "x":"Bye","y":"Bye","z":"Hello"},
    { "x":"Bye","y":"Bye","z":"Hi"},
    { "x":"Bye","y":"Hello","z":"Hi"},
];
</code>```

Then you may try this in ES6+:

var array =  [
  { "x":"Bye","y":"Bye","z":"Hello"},
  { "x":"Bye","y":"Bye","z":"Hi"},
  { "x":"Bye","y":"Hello","z":"Hi"},
];

var keyName = ["Hello", "Bye"];

function searchWO (nameKey, myArray) {
  for(var key of nameKey){
     myArray = myArray.filter(obj => JSON.stringify(obj).indexOf('"' + key + '"') != -1);
  }
  return myArray;
}

// Loop Haters Gonna Hate
function searchWO2 (nameKey, myArray) {
    return nameKey.reduce((ans, key) => ans.filter(obj => JSON.stringify(obj).indexOf('"' + key + '"') != -1) , myArray);
}

console.log(searchWO(keyName, array.slice()));
console.log(searchWO2(keyName, array.slice()));```

The .slice() is just a shallow copy as I don't want to modify the source array, you may omit it if you want.

Both function does the same job, choose one you like :)

EDITED:

To ensure the indexOf is searching the value instead of key, one can change to search

'"' + key + '",' and '"' + key + '"}'

Body:
I'm trying to optimize my code. I have an array of JSON objects and I need to loop through the objects and see if they contain several words and keep track of the JSON objects if the contain all the worlds, not just one but all of them. I don't want to pass to the function an array of worlds because I feel I will have to add another for loop.Right now, my code goes through every input field and if it's not empty call the function and pass the world in the input field. My code works fine if I just check one word, but I need to check more than one and keep track of the objects that contain all the worlds

My code:
 workOrdersArray it's a global array.

function searchWO (workOrdersArray) {
            var filteredWO = [];

            for (var i=0; i < workOrdersArray.length; i++) {
                for (var prop in workOrdersArray[i]) {
                    if (myArray[i][prop] == nameKey) {
                            filteredWO.push(workOrdersArray[i]);
                    }
                }

            }
        }

Example:
If one input field has the world "Hello" and another input field says "Bye"

var array = [
    { "x":"Bye","y":"Bye","z":"Hello"},
    { "x":"Bye","y":"Bye","z":"Hi"},
    { "x":"Bye","y":"Hello","z":"Hi"},
];

I will store the JSON object inside of the array in an separate array. So the new array will have the obj1 and obj3

Body:
I don't think your array is a valid JavaScript array, but if your array is of the form like

var array = [
    { "x":"Bye","y":"Bye","z":"Hello"},
    { "x":"Bye","y":"Bye","z":"Hi"},
    { "x":"Bye","y":"Hello","z":"Hi"},
];

Then you may try this in ES6+:

var array =  [
  { "x":"Bye","y":"Bye","z":"Hello"},
  { "x":"Bye","y":"Bye","z":"Hi"},
  { "x":"Bye","y":"Hello","z":"Hi"},
];

var keyName = ["Hello", "Bye"];

function searchWO (nameKey, myArray) {
  for(var key of nameKey){
     myArray = myArray.filter(obj => JSON.stringify(obj).indexOf('"' + key + '"') != -1);
  }
  return myArray;
}

// Loop Haters Gonna Hate
function searchWO2 (nameKey, myArray) {
    return nameKey.reduce((ans, key) => ans.filter(obj => JSON.stringify(obj).indexOf('"' + key + '"') != -1) , myArray);
}

console.log(searchWO(keyName, array.slice()));
console.log(searchWO2(keyName, array.slice()));

The .slice() is just a shallow copy as I don't want to modify the source array, you may omit it if you want.

Both function does the same job, choose one you like :)

EDITED:

To ensure the indexOf is searching the value instead of key, one can change to search

'"' + key + '",' and '"' + key + '"}'


问:
How to sum or add two values by using SQL command
How to add them together?
Need to be in vb.net

Two value statement as below:

```<code>(SELECT SUM(ChildName) FROM Child SA WHERE SA.Name=A.Name AND SA.Health_Status=1 AND SA.Parrent_ID IS NOT NULL) AS Present_CHILD

(SELECT SUM(LATE_COMING_CHILD) FROM LATE_COME SB WHERE SB.Name=A.Name) AS LATE_CHILD
</code>```

答:
You can use what is referred to as a "scalar subquery":</p>

```<code>select (select Name from table1) + (select Name from table2)
</code>```

Body:
How to add them together?
Need to be in vb.net

Two value statement as below:

(SELECT SUM(ChildName) FROM Child SA WHERE SA.Name=A.Name AND SA.Health_Status=1 AND SA.Parrent_ID IS NOT NULL) AS Present_CHILD

(SELECT SUM(LATE_COMING_CHILD) FROM LATE_COME SB WHERE SB.Name=A.Name) AS LATE_CHILD

Body:
You can use what is referred to as a "scalar subquery":

select (select Name from table1) + (select Name from table2)


问:
Jenkins Git Plugin not pulling latest changes before building job
I am working with Jenkins CI and am trying to properly configure my jobs to use git.

I have the git plugin installed and configured for one of my jobs. When I build the job, I expect it to pull the latest changes for the branch I specify and then continue with the rest of the build process (e.g., unit tests, etc.).

When I look at the console output, I see

```<code>> git fetch --tags --progress ssh://gerrit@git-dev/Util +refs/heads/*:refs/remotes/origin/*
 > git rev-parse origin/some_branch^{commit}
Checking out Revision <latest_SHA1> (origin/some_branch)
 > git config core.sparsecheckout
 > git checkout -f <latest_SHA1>
 > git rev-list <latest_SHA1>
</code>```

I see that the plugin fetches and checks out the proper commit hash, but when the tests run it seems as though the repo wasn't updated at all.
If I go into the repository in Jenkins, I see there that the latest changes were never pulled.

Shouldn't it pull before it tries to build?

I have git 1.8.5 installed on my Jenkins machine, which is a recommended version.
https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin

After checking other similar sounding questions on SO, their answers weren't helpful for my problem.

答:
I know the question is old, but there is another way to do this.  In the Build Environment section, select "Delete workspace before build starts"

See the screenshot below,

This will actually clean the workspace every time and hence you will get the updated code.

Body:
I am working with Jenkins CI and am trying to properly configure my jobs to use git.

I have the git plugin installed and configured for one of my jobs. When I build the job, I expect it to pull the latest changes for the branch I specify and then continue with the rest of the build process (e.g., unit tests, etc.).

When I look at the console output, I see

> git fetch --tags --progress ssh://gerrit@git-dev/Util +refs/heads/*:refs/remotes/origin/*
 > git rev-parse origin/some_branch^{commit}
Checking out Revision <latest_SHA1> (origin/some_branch)
 > git config core.sparsecheckout
 > git checkout -f <latest_SHA1>
 > git rev-list <latest_SHA1>

I see that the plugin fetches and checks out the proper commit hash, but when the tests run it seems as though the repo wasn't updated at all.
If I go into the repository in Jenkins, I see there that the latest changes were never pulled.

Shouldn't it pull before it tries to build?

I have git 1.8.5 installed on my Jenkins machine, which is a recommended version.
https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin

After checking other similar sounding questions on SO, their answers weren't helpful for my problem.


问:
Why is my instance variable changing indirectly?
I'm a starter at ruby, and I'm really stuck with this code... I can't understand why is @plays changing when a call test_code</p>

```<code>class Board
  attr_reader :plays

  def initialize(secret_code)
    @secret_code = secret_code
    @plays = []
  end

  def insert_code(code)
    @plays.push(code)
    p @plays         #-> [["red", "red", "red", "red"]]
    test_code(code)  #-> When i call this method the changes on 'code' make to '@plays' array...
    p @plays         #-> [["check", "red", "red", "red"]]
  end

  private

  def test_code(code)
    s_code = @secret_code  # made a copy of @secret_code to keep it intact but is changing just like @plays
    s_code.each_index do |i|
      if s_code[i] == code[i]
        s_code[i] = "O"
        code[i] = "check"  #in this line the @plays array is changed, and i can't figure out why
      end
    end
  end
end

board = Board.new(["red", "blue", "blue", "blue"])
board.insert_code(["red", "red", "red", "red"])
</code>```

答:
The assignment operator = does not make a copy of an object. It makes a new reference (i.e., pointer) to the object.

You can use clone to create a shallow copy of an object as follows:

```<code>...
s_code = @secret_code.clone
...
def test_code(code0)
  code = code0.clone
...
</code>```

Body:
I'm a starter at ruby, and I'm really stuck with this code... I can't understand why is @plays changing when a call test_code

class Board
  attr_reader :plays

  def initialize(secret_code)
    @secret_code = secret_code
    @plays = []
  end

  def insert_code(code)
    @plays.push(code)
    p @plays         #-> [["red", "red", "red", "red"]]
    test_code(code)  #-> When i call this method the changes on 'code' make to '@plays' array...
    p @plays         #-> [["check", "red", "red", "red"]]
  end

  private

  def test_code(code)
    s_code = @secret_code  # made a copy of @secret_code to keep it intact but is changing just like @plays
    s_code.each_index do |i|
      if s_code[i] == code[i]
        s_code[i] = "O"
        code[i] = "check"  #in this line the @plays array is changed, and i can't figure out why
      end
    end
  end
end

board = Board.new(["red", "blue", "blue", "blue"])
board.insert_code(["red", "red", "red", "red"])

Body:
The assignment operator = does not make a copy of an object. It makes a new reference (i.e., pointer) to the object.

You can use clone to create a shallow copy of an object as follows:

...
s_code = @secret_code.clone
...
def test_code(code0)
  code = code0.clone
...


问:
Performing a search through database for value
I'm trying to use a search bar, to search for values in my Firebase Database. For example:

```<code>---users---
     |
     | ---1412512351--
     |   |
     |   |- name: Nick
     |   |- age: 37
     |
     | ---5734739374--
     |   |
     |   |- name: John
     |   |- age: 19
</code>```

When the user finishes typing, and clicks done, I want to perform a search through the database and find the name that they are looking for. Instead of loading all of the users, which could take a while.

Also, I want to get all of the values close to the search. For example if it type "Nick", It should bring up a values close to that string, like Nicholas or Nathan etc.

Thanks in advance!

答:
To find a particular user (in JS):

```<code>var usersRef = new Firebase("https://yourdb.firebaseio.com/users/");
var theNameIAmAfter = usersRef.orderByChild("name").equalTo(SearchByThisName);
</code>```

Also, I want to get all of the values close to the search. For example
  if it type "Nick", It should bring up a values close to that string,
  like Nicholas or Nathan etc...

I'm not sure if that's doable with firebase.

Body:
I'm trying to use a search bar, to search for values in my Firebase Database. For example:

---users---
     |
     | ---1412512351--
     |   |
     |   |- name: Nick
     |   |- age: 37
     |
     | ---5734739374--
     |   |
     |   |- name: John
     |   |- age: 19

When the user finishes typing, and clicks done, I want to perform a search through the database and find the name that they are looking for. Instead of loading all of the users, which could take a while.

Also, I want to get all of the values close to the search. For example if it type "Nick", It should bring up a values close to that string, like Nicholas or Nathan etc.

Thanks in advance!

Body:
To find a particular user (in JS):

var usersRef = new Firebase("https://yourdb.firebaseio.com/users/");
var theNameIAmAfter = usersRef.orderByChild("name").equalTo(SearchByThisName);

Also, I want to get all of the values close to the search. For example
  if it type "Nick", It should bring up a values close to that string,
  like Nicholas or Nathan etc...

I'm not sure if that's doable with firebase.


问:
simple dynamic allocation question
What is the difference between this:-

```<code>width = new int;
</code>```

And this:-

```<code>int width;
</code>```

i.e. of what use is the dynamic allocation in the first code?

答:
It's very rare that dynamic allocation of one int would be "of use," though I wouldn't say "never."

Dynamic allocation is useful for large, complicated data structures whose lifetime and/or size is not known at compile time, or that are just plain too big to put on the stack.

Title: simple dynamic allocation question

Body:
What is the difference between this:-

width = new int;

And this:-

int width;

i.e. of what use is the dynamic allocation in the first code?


问:
Print a binary tree in a pretty way
Just wondering if I can get some tips on printing a pretty binary tree in the form of:

```<code>5
     10
          11
          7
               6
     3
          4
          2
</code>```

Right now what it prints is:

```<code>   2
    4
    3
    6
    7
    11
    10
    5
</code>```

I know that my example is upside down from what I'm currently printing, which it doesn't matter if I print from the root down as it currently prints. Any tips are very appreciated towards my full question:

How do I modify my prints to make the tree look like a tree?

```<code>    //Binary Search Tree Program

#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std;

int i = 0;

class BinarySearchTree
{
   private:
   struct tree_node
   {
      tree_node* left;
      tree_node* right;
      int data;
   };
   tree_node* root;

   public:
   BinarySearchTree()
   {
      root = NULL;
   }

   bool isEmpty() const { return root==NULL; }
   void print_inorder();
   void inorder(tree_node*);
   void print_preorder();
   void preorder(tree_node*);
   void print_postorder();
   void postorder(tree_node*);
   void insert(int);
   void remove(int);
};

// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d)
{
   tree_node* t = new tree_node;
   tree_node* parent;
   t->data = d;
   t->left = NULL;
   t->right = NULL;
   parent = NULL;

   // is this a new tree?
   if(isEmpty()) root = t;
   else
   {
      //Note: ALL insertions are as leaf nodes
      tree_node* curr;
      curr = root;
      // Find the Node's parent
      while(curr)
      {
         parent = curr;
         if(t->data > curr->data) curr = curr->right;
         else curr = curr->left;
      }

      if(t->data < parent->data)
      {
         parent->left = t;
      }
      else
      {
      parent->right = t;
      }
    }
}

void BinarySearchTree::remove(int d)
{
   //Locate the element
   bool found = false;
   if(isEmpty())
   {
      cout<<" This Tree is empty! "<<endl;
      return;
   }

   tree_node* curr;
   tree_node* parent;
   curr = root;

   while(curr != NULL)
   {
      if(curr->data == d)
      {
         found = true;
         break;
      }
      else
      {
         parent = curr;
         if(d>curr->data) curr = curr->right;
         else curr = curr->left;
      }
    }
    if(!found)
    {
      cout<<" Data not found! "<<endl;
      return;
    }

    // 3 cases :
    // 1. We're removing a leaf node
    // 2. We're removing a node with a single child
    // 3. we're removing a node with 2 children

    // Node with single child
    if((curr->left == NULL && curr->right != NULL) || (curr->left != NULL && curr->right == NULL))
    {
      if(curr->left == NULL && curr->right != NULL)
      {
         if(parent->left == curr)
         {
            parent->left = curr->right;
            delete curr;
         }
         else
         {
            parent->right = curr->left;
            delete curr;
         }
       }
       return;
    }

    //We're looking at a leaf node
    if( curr->left == NULL && curr->right == NULL)
    {
      if(parent->left == curr)
      {
         parent->left = NULL;
      }
      else
      {
         parent->right = NULL;
      }
      delete curr;
      return;
    }

    //Node with 2 children
    // replace node with smallest value in right subtree
    if (curr->left != NULL && curr->right != NULL)
    {
       tree_node* chkr;
       chkr = curr->right;
       if((chkr->left == NULL) && (chkr->right == NULL))
       {
         curr = chkr;
         delete chkr;
         curr->right = NULL;
       }
       else // right child has children
       {
         //if the node's right child has a left child
         // Move all the way down left to locate smallest element

         if((curr->right)->left != NULL)
         {
            tree_node* lcurr;
            tree_node* lcurrp;
            lcurrp = curr->right;
            lcurr = (curr->right)->left;
            while(lcurr->left != NULL)
            {
               lcurrp = lcurr;
               lcurr = lcurr->left;
            }
            curr->data = lcurr->data;
            delete lcurr;
            lcurrp->left = NULL;
         }
         else
         {
            tree_node* tmp;
            tmp = curr->right;
            curr->data = tmp->data;
            curr->right = tmp->right;
            delete tmp;
         }

      }
      return;
   }

}
void BinarySearchTree::print_postorder()
{
   postorder(root);
}

void BinarySearchTree::postorder(tree_node* p)
{
   if(p != NULL)
   {
      if(p->left) postorder(p->left);
      if(p->right) postorder(p->right);
      cout<<"     "<<p->data<<"\n ";
   }
   else return;
}

int main()
{
    BinarySearchTree b;
    int ch,tmp,tmp1;
    while(1)
    {
       cout<<endl<<endl;
       cout<<" Binary Search Tree Operations "<<endl;
       cout<<" ----------------------------- "<<endl;
       cout<<" 1. Insertion/Creation "<<endl;
       cout<<" 2. Printing "<<endl;
       cout<<" 3. Removal "<<endl;
       cout<<" 4. Exit "<<endl;
       cout<<" Enter your choice : ";
       cin>>ch;
       switch(ch)
       {
           case 1 : cout<<" Enter Number to be inserted : ";
                    cin>>tmp;
                    b.insert(tmp);
                    i++;
                    break;
           case 2 : cout<<endl;
                    cout<<" Printing "<<endl;
                    cout<<" --------------------"<<endl;
                    b.print_postorder();
                    break;
           case 3 : cout<<" Enter data to be deleted : ";
                    cin>>tmp1;
                    b.remove(tmp1);
                    break;
           case 4:
                    return 0;

       }
    }
}
</code>```

答:
i have a easier code..........
consider a tree made of nodes of structure

```<code> struct treeNode{
  treeNode *lc;
  element data;
  short int bf;
  treeNode *rc;
};
</code>```

Tree's depth can be found out using

```<code>int depth(treeNode *p){
    if(p==NULL) return 0;
    int l=depth(p->lc);
    int r=depth(p->rc);
    if(l>=r)
        return l+1;
    else
        return r+1;
}
</code>```

below gotoxy function moves your cursor to the desired position

```<code>void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}
</code>```

Then Printing a Tree can be done as:

```<code>void displayTreeUpDown(treeNode * root,int x,int y,int px=0){
if(root==NULL) return;
gotoxy(x,y);
int a=abs(px-x)/2;
cout<<root->data.key;
displayTreeUpDown(root->lc,x-a,y+1,x);
displayTreeUpDown(root->rc,x+a,y+1,x);
}
</code>```

which can be called using:

```<code>display(t,pow(2,depth(t)),1,1);
</code>```

Title: Print a binary tree in a pretty way

Body:
Just wondering if I can get some tips on printing a pretty binary tree in the form of:

5
     10
          11
          7
               6
     3
          4
          2

Right now what it prints is:

   2
    4
    3
    6
    7
    11
    10
    5

I know that my example is upside down from what I'm currently printing, which it doesn't matter if I print from the root down as it currently prints. Any tips are very appreciated towards my full question:

How do I modify my prints to make the tree look like a tree?

    //Binary Search Tree Program

#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std;

int i = 0;

class BinarySearchTree
{
   private:
   struct tree_node
   {
      tree_node* left;
      tree_node* right;
      int data;
   };
   tree_node* root;

   public:
   BinarySearchTree()
   {
      root = NULL;
   }

   bool isEmpty() const { return root==NULL; }
   void print_inorder();
   void inorder(tree_node*);
   void print_preorder();
   void preorder(tree_node*);
   void print_postorder();
   void postorder(tree_node*);
   void insert(int);
   void remove(int);
};

// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d)
{
   tree_node* t = new tree_node;
   tree_node* parent;
   t->data = d;
   t->left = NULL;
   t->right = NULL;
   parent = NULL;

   // is this a new tree?
   if(isEmpty()) root = t;
   else
   {
      //Note: ALL insertions are as leaf nodes
      tree_node* curr;
      curr = root;
      // Find the Node's parent
      while(curr)
      {
         parent = curr;
         if(t->data > curr->data) curr = curr->right;
         else curr = curr->left;
      }

      if(t->data < parent->data)
      {
         parent->left = t;
      }
      else
      {
      parent->right = t;
      }
    }
}

void BinarySearchTree::remove(int d)
{
   //Locate the element
   bool found = false;
   if(isEmpty())
   {
      cout<<" This Tree is empty! "<<endl;
      return;
   }

   tree_node* curr;
   tree_node* parent;
   curr = root;

   while(curr != NULL)
   {
      if(curr->data == d)
      {
         found = true;
         break;
      }
      else
      {
         parent = curr;
         if(d>curr->data) curr = curr->right;
         else curr = curr->left;
      }
    }
    if(!found)
    {
      cout<<" Data not found! "<<endl;
      return;
    }

    // 3 cases :
    // 1. We're removing a leaf node
    // 2. We're removing a node with a single child
    // 3. we're removing a node with 2 children

    // Node with single child
    if((curr->left == NULL && curr->right != NULL) || (curr->left != NULL && curr->right == NULL))
    {
      if(curr->left == NULL && curr->right != NULL)
      {
         if(parent->left == curr)
         {
            parent->left = curr->right;
            delete curr;
         }
         else
         {
            parent->right = curr->left;
            delete curr;
         }
       }
       return;
    }

    //We're looking at a leaf node
    if( curr->left == NULL && curr->right == NULL)
    {
      if(parent->left == curr)
      {
         parent->left = NULL;
      }
      else
      {
         parent->right = NULL;
      }
      delete curr;
      return;
    }

    //Node with 2 children
    // replace node with smallest value in right subtree
    if (curr->left != NULL && curr->right != NULL)
    {
       tree_node* chkr;
       chkr = curr->right;
       if((chkr->left == NULL) && (chkr->right == NULL))
       {
         curr = chkr;
         delete chkr;
         curr->right = NULL;
       }
       else // right child has children
       {
         //if the node's right child has a left child
         // Move all the way down left to locate smallest element

         if((curr->right)->left != NULL)
         {
            tree_node* lcurr;
            tree_node* lcurrp;
            lcurrp = curr->right;
            lcurr = (curr->right)->left;
            while(lcurr->left != NULL)
            {
               lcurrp = lcurr;
               lcurr = lcurr->left;
            }
            curr->data = lcurr->data;
            delete lcurr;
            lcurrp->left = NULL;
         }
         else
         {
            tree_node* tmp;
            tmp = curr->right;
            curr->data = tmp->data;
            curr->right = tmp->right;
            delete tmp;
         }

      }
      return;
   }

}
void BinarySearchTree::print_postorder()
{
   postorder(root);
}

void BinarySearchTree::postorder(tree_node* p)
{
   if(p != NULL)
   {
      if(p->left) postorder(p->left);
      if(p->right) postorder(p->right);
      cout<<"     "<
data<<"\n ";
   }
   else return;
}

int main()
{
    BinarySearchTree b;
    int ch,tmp,tmp1;
    while(1)
    {
       cout<<endl<<endl;
       cout<<" Binary Search Tree Operations "<<endl;
       cout<<" ----------------------------- "<<endl;
       cout<<" 1. Insertion/Creation "<<endl;
       cout<<" 2. Printing "<<endl;
       cout<<" 3. Removal "<<endl;
       cout<<" 4. Exit "<<endl;
       cout<<" Enter your choice : ";
       cin>>ch;
       switch(ch)
       {
           case 1 : cout<<" Enter Number to be inserted : ";
                    cin>>tmp;
                    b.insert(tmp);
                    i++;
                    break;
           case 2 : cout<<endl;
                    cout<<" Printing "<<endl;
                    cout<<" --------------------"<<endl;
                    b.print_postorder();
                    break;
           case 3 : cout<<" Enter data to be deleted : ";
                    cin>>tmp1;
                    b.remove(tmp1);
                    break;
           case 4:
                    return 0;

       }
    }
}

Body:
i have a easier code..........
consider a tree made of nodes of structure

 struct treeNode{
  treeNode *lc;
  element data;
  short int bf;
  treeNode *rc;
};

Tree's depth can be found out using

int depth(treeNode *p){
    if(p==NULL) return 0;
    int l=depth(p->lc);
    int r=depth(p->rc);
    if(l>=r)
        return l+1;
    else
        return r+1;
}

below gotoxy function moves your cursor to the desired position

void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}

Then Printing a Tree can be done as:

void displayTreeUpDown(treeNode * root,int x,int y,int px=0){
if(root==NULL) return;
gotoxy(x,y);
int a=abs(px-x)/2;
cout<<root->data.key;
displayTreeUpDown(root->lc,x-a,y+1,x);
displayTreeUpDown(root->rc,x+a,y+1,x);
}

which can be called using:

display(t,pow(2,depth(t)),1,1);


问:
Admob Error: Not enough space to show ad. Needs 320x50 dp, but only has 309x0 dp
I am trying to ad smart banner ads to my fragment layout and all I am getting incesantly is "Not enough space to show ad. Needs 320x50 dp, but only has 309x0 dp".

This is my fragment layout.

```<code><android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:scrollbars="vertical"
    android:fillViewport="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/details_layout"
    android:background="@android:color/white"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.app.bookng.DetailsFragment">

    <RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/details_relat"
        android:padding="5dp">

        <com.google.android.gms.ads.AdView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            android:id="@+id/banner_id"
            ads:adSize="SMART_BANNER"
            ads:adUnitId="XXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>

        <ProgressBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:indeterminate="true"
            android:id="@+id/progress_circle"
            android:visibility="gone"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_centerInParent="true"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:hint="@string/title"
            android:id="@+id/dbook_title"
            android:visibility="gone"
            android:layout_margin="5dp"
            android:textStyle="bold"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="30dp"
            android:layout_marginTop="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"
            android:layout_below="@+id/dbook_title"
            android:id="@+id/rootauthor_date"
            android:gravity="center_vertical">

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginLeft="10dp"
                android:visibility="gone"
                android:background="#d1d1d1"
                android:layout_alignParentTop="true"
                android:id="@+id/dviewtop"
                android:layout_marginTop="15dp"
                android:layout_toRightOf="@+id/author_img"/>

            <com.app.bookng.CircularNetworkImageView
                android:layout_width="90dp"
                android:layout_height="90dp"
                android:visibility="gone"
                android:padding="3dp"
                android:layout_alignParentLeft="true"
                android:id="@+id/author_img"
                android:scaleType="centerCrop"
                android:background="@drawable/round_button"/>

            <TextView
                android:layout_width="wrap_content"
                android:visibility="gone"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/author_img"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_centerVertical="true"
                android:layout_below="@+id/dviewtop"
                android:id="@+id/author_date"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginLeft="10dp"
                android:visibility="gone"
                android:background="#d1d1d1"
                android:id="@+id/dviewbottom"
                android:layout_marginTop="10dp"
                android:layout_below="@+id/author_date"
                android:layout_toRightOf="@+id/author_img"/>
        </RelativeLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/rootauthor_date"
            android:hint="@string/main_body"
            android:textColorLink="@color/textlink"
            android:visibility="gone"
            android:id="@+id/dbook_content"
            android:layout_margin="5dp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gad_title"
            android:textStyle="bold"
            android:visibility="gone"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gad_pic"
            android:visibility="gone"
            android:layout_below="@+id/gad_title"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gad_feat"
            android:visibility="gone"
            android:layout_below="@+id/gad_pic"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:layout_below="@+id/gad_feat"
            android:id="@+id/gad_content"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:visibility="gone"
            android:background="#d1d1d1"
            android:id="@+id/viewtop_share"
            android:layout_below="@+id/dbook_content"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/viewtop_share"
            android:id="@+id/comment_container"/>

    </RelativeLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

And this is the acivity layout

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

     //Container for toolbar
    <include layout="@layout/post_toolbar"/>

    //Container for fragment
    <include layout="@layout/share_layout"/>

</FrameLayout>
</code>```

I really can't figure out why the height is 0dp. Please can you help me?

答: Replace SMART_BANNER for BANNER. Can't get easier. </p>

Body:
I am trying to ad smart banner ads to my fragment layout and all I am getting incesantly is "Not enough space to show ad. Needs 320x50 dp, but only has 309x0 dp".

This is my fragment layout.

<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:scrollbars="vertical"
    android:fillViewport="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/details_layout"
    android:background="@android:color/white"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.app.bookng.DetailsFragment">

    <RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/details_relat"
        android:padding="5dp">

        <com.google.android.gms.ads.AdView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            android:id="@+id/banner_id"
            ads:adSize="SMART_BANNER"
            ads:adUnitId="XXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>

        <ProgressBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:indeterminate="true"
            android:id="@+id/progress_circle"
            android:visibility="gone"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_centerInParent="true"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:hint="@string/title"
            android:id="@+id/dbook_title"
            android:visibility="gone"
            android:layout_margin="5dp"
            android:textStyle="bold"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="30dp"
            android:layout_marginTop="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"
            android:layout_below="@+id/dbook_title"
            android:id="@+id/rootauthor_date"
            android:gravity="center_vertical">

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginLeft="10dp"
                android:visibility="gone"
                android:background="#d1d1d1"
                android:layout_alignParentTop="true"
                android:id="@+id/dviewtop"
                android:layout_marginTop="15dp"
                android:layout_toRightOf="@+id/author_img"/>

            <com.app.bookng.CircularNetworkImageView
                android:layout_width="90dp"
                android:layout_height="90dp"
                android:visibility="gone"
                android:padding="3dp"
                android:layout_alignParentLeft="true"
                android:id="@+id/author_img"
                android:scaleType="centerCrop"
                android:background="@drawable/round_button"/>

            <TextView
                android:layout_width="wrap_content"
                android:visibility="gone"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/author_img"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_centerVertical="true"
                android:layout_below="@+id/dviewtop"
                android:id="@+id/author_date"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginLeft="10dp"
                android:visibility="gone"
                android:background="#d1d1d1"
                android:id="@+id/dviewbottom"
                android:layout_marginTop="10dp"
                android:layout_below="@+id/author_date"
                android:layout_toRightOf="@+id/author_img"/>
        </RelativeLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/rootauthor_date"
            android:hint="@string/main_body"
            android:textColorLink="@color/textlink"
            android:visibility="gone"
            android:id="@+id/dbook_content"
            android:layout_margin="5dp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gad_title"
            android:textStyle="bold"
            android:visibility="gone"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gad_pic"
            android:visibility="gone"
            android:layout_below="@+id/gad_title"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gad_feat"
            android:visibility="gone"
            android:layout_below="@+id/gad_pic"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:layout_below="@+id/gad_feat"
            android:id="@+id/gad_content"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:visibility="gone"
            android:background="#d1d1d1"
            android:id="@+id/viewtop_share"
            android:layout_below="@+id/dbook_content"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/viewtop_share"
            android:id="@+id/comment_container"/>

    </RelativeLayout>

</android.support.v4.widget.NestedScrollView>

And this is the acivity layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

     //Container for toolbar
    <include layout="@layout/post_toolbar"/>

    //Container for fragment
    <include layout="@layout/share_layout"/>

</FrameLayout>

I really can't figure out why the height is 0dp. Please can you help me?