问:
High & Low of previous periods indicator, how to plot on chart just the last period?
I have an indicator that plot on chart, using lines, previous periods High and Low, it works properly for daily and weekly periods.

Screenshot of my working indicator

On the chart it shows every previous period while I need only the last period, for example just last week or just last day.

```<code>    study(title="Previous Day High and Low + OPENS", shorttitle="HLO", overlay=true)

D_High = security(tickerid, 'D', high[1])
D_Low = security(tickerid, 'D', low[1])
D_Close =  security(tickerid, 'D', close[1])
D_Open =  security(tickerid, 'D', open[1])
W_High =  security(tickerid, 'W', high[1])
W_Low =  security(tickerid, 'W', low[1])

plot(isintraday ? D_High : na, title="Daily High",style=line, color=black,linewidth=1)
plot(isintraday ? D_Low : na, title="Daily Low",style=line, color=black,linewidth=1)

plot(isintraday ? W_High : na, title="Weekly High",style=line, color=black,linewidth=1)
plot(isintraday ? W_Low : na, title="Weekly Low",style=line, color=black,linewidth=1)

openPriceD = security(tickerid, 'D', open)

openPriceW = security(tickerid, 'W', open)

openPriceM = security(tickerid, 'M', open)

plot(openPriceD ? openPriceD : na, title="Daily Open", style=circles, linewidth=2, color=purple)

plot(openPriceW ? openPriceW : na, title="Weekly Open", style=circles, linewidth=2, color=green)

plot(openPriceM ? openPriceM : na, title="Monthly Open", style=circles, linewidth=2, color=red)
</code>```

I tried to add the "show_last=" function to the plot string but it doesn't work.

Any help would be much appreciated
Thanks!

答:
This will plot the high of the previous day on today's candles.

```<code>//@version=4
study("Q62089672", overlay=true)

D_High = security(syminfo.tickerid, "D", high)

isSaturday = dayofweek(timenow) == dayofweek.saturday
isSunday   = dayofweek(timenow) == dayofweek.sunday
offSetDays = isSaturday ? 1 : isSunday ? 2 : 0

showFromDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow)-offSetDays, 0, 0, 0)

canShow = timeframe.isintraday and time >= showFromDate

plot(canShow ? D_High[1] : na, title="Previous day high", style=plot.style_line, color=color.yellow, linewidth=1)
</code>```

Which yields this output

The times at which the lines start may be off because of time zone differences.

Each ticker has its own time zone in which it trades.

You can also specify a timezone in the security() function.

For more details and examples, see

A closer look at TradingView's syminfo.timezone variable

How to set a TradingView chart to the instrument's ‘Exchange’ time
zone?.

Body:
I have an indicator that plot on chart, using lines, previous periods High and Low, it works properly for daily and weekly periods.

Screenshot of my working indicator

On the chart it shows every previous period while I need only the last period, for example just last week or just last day.

    study(title="Previous Day High and Low + OPENS", shorttitle="HLO", overlay=true)

D_High = security(tickerid, 'D', high[1])
D_Low = security(tickerid, 'D', low[1])
D_Close =  security(tickerid, 'D', close[1])
D_Open =  security(tickerid, 'D', open[1])
W_High =  security(tickerid, 'W', high[1])
W_Low =  security(tickerid, 'W', low[1])

plot(isintraday ? D_High : na, title="Daily High",style=line, color=black,linewidth=1)
plot(isintraday ? D_Low : na, title="Daily Low",style=line, color=black,linewidth=1)

plot(isintraday ? W_High : na, title="Weekly High",style=line, color=black,linewidth=1)
plot(isintraday ? W_Low : na, title="Weekly Low",style=line, color=black,linewidth=1)

openPriceD = security(tickerid, 'D', open)

openPriceW = security(tickerid, 'W', open)

openPriceM = security(tickerid, 'M', open)

plot(openPriceD ? openPriceD : na, title="Daily Open", style=circles, linewidth=2, color=purple)

plot(openPriceW ? openPriceW : na, title="Weekly Open", style=circles, linewidth=2, color=green)

plot(openPriceM ? openPriceM : na, title="Monthly Open", style=circles, linewidth=2, color=red)

I tried to add the "show_last=" function to the plot string but it doesn't work.

Any help would be much appreciated
Thanks!

Body:
This will plot the high of the previous day on today's candles.

//@version=4
study("Q62089672", overlay=true)

D_High = security(syminfo.tickerid, "D", high)

isSaturday = dayofweek(timenow) == dayofweek.saturday
isSunday   = dayofweek(timenow) == dayofweek.sunday
offSetDays = isSaturday ? 1 : isSunday ? 2 : 0

showFromDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow)-offSetDays, 0, 0, 0)

canShow = timeframe.isintraday and time >= showFromDate

plot(canShow ? D_High[1] : na, title="Previous day high", style=plot.style_line, color=color.yellow, linewidth=1)

Which yields this output

The times at which the lines start may be off because of time zone differences.

Each ticker has its own time zone in which it trades.

You can also specify a timezone in the security() function.

For more details and examples, see

A closer look at TradingView's syminfo.timezone variable

How to set a TradingView chart to the instrument's ‘Exchange’ time
zone?.


来源: stackexchange

问:
How to pull variables out of a string
I'm looking for a Java class that for a given string "the ${animal} jumped over the ${target}." is able to pull out the variable names, ie 'animal' and 'target'.

I had hoped StrSubstitutor in Commons Lang had a method

getVariables(String str) : List<String>

... but no such luck.

Yes I could write this myself, but I'm certain there must be a 3rd party library that exists out there that does this.

答:
Actually I was also looking for a similar library while developing DSL Adapter for my GenericFixture.

After looking at some libraries and template based framework I eventually decided to write code by myself. Feel free to check the code I used for this purpose in DSLAdapter class from GenericFixture available on sourceforge.

ContentLicense: CC BY-SA 3.0

Title: How to pull variables out of a string


问:
Why is border collapse and spacing not working when you target only the Table Head (TH) inside a Table?
My HTML:

```<code><table style="width:100%">

    <tr>
        <th>First name</th>
        <th>Last name</th>
        <th>Age</th>

    </tr>

    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>

    </tr>

    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>

    </tr>

</table>
</code>```

My CSS:

```<code>table, th, td {
margin-top:150px;
margin-bottom:150px;
border:1px solid black;

}

th, td {
    padding:15px;
}

th {

    text-align:left;
    border-collapse:collapse;

}
</code>```

I want to collapse the borders of the TH only, but it's not working. Border collapse and border spacing aren't working when i target only the TH. I can change the background color and the padding and do other changes to TH only, but border changes seems to not work. Why is that?

Note: Before you tell me how it can be done using other ways, please tell me why THIS way isn't working.

答:
Because border-collapse is a style rule of the table and not of the single cells (td or th). This means that you set it on the table element and all the borders in the table will collapse or separate.

You can mimic the behavior of border-collapse: separate only in td by doing something "hacky" like inserting a div inside tds. Check out the fiddle below:

table {
  border-collapse: collapse;
}

th {
  border: 1px solid black;
}

td {
  padding: 2px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

td > div {
  height: 100%;
  width: 100%;
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><div>Cell 1</div></td>
      <td><div>cell 2</div></td>
    </tr>
    <tr>
      <td><div>Cell 3</div></td>
      <td><div>Cell 4</div></td>
    </tr>
  </tbody>
</table></code>```

ContentLicense: CC BY-SA 4.0

Body:
My HTML:

        First name
        Last name
        Age

        Jill
        Smith
        50

        Eve
        Jackson
        94

My CSS:

table, th, td {
margin-top:150px;
margin-bottom:150px;
border:1px solid black;

}

th, td {
    padding:15px;
}

th {

    text-align:left;
    border-collapse:collapse;

}

I want to collapse the borders of the TH only, but it's not working. Border collapse and border spacing aren't working when i target only the TH. I can change the background color and the padding and do other changes to TH only, but border changes seems to not work. Why is that?

Note: Before you tell me how it can be done using other ways, please tell me why THIS way isn't working.

Body:
Because border-collapse is a style rule of the table and not of the single cells (td or th). This means that you set it on the table element and all the borders in the table will collapse or separate.

You can mimic the behavior of border-collapse: separate only in td by doing something "hacky" like inserting a div inside tds. Check out the fiddle below:

table {
  border-collapse: collapse;
}

th {
  border: 1px solid black;
}

td {
  padding: 2px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

td > div {
  height: 100%;
  width: 100%;
  border: 1px solid black;
}

<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><div>Cell 1</div></td>
      <td><div>cell 2</div></td>
    </tr>
    <tr>
      <td><div>Cell 3</div></td>
      <td><div>Cell 4</div></td>
    </tr>
  </tbody>
</table>


问:
Run a Java application in a web browser
I am relatively new to Java and have a Java application consisting of a couple of packages and a number of classes. I want to be able to run this application in a web browser. How do I go about doing this?</p>

答:
I've written some kind of JVM which precompiles Java classes to native JavaScript. Here is an HelloWorld example which runs java programm in the browser:

https://github.com/neo-expert/jsjvm_helloworld

it has also a WebGL demo which renders a 3D cube.

Title: Run a Java application in a web browser


答:
You have a few choices:

keep training and see what happens

if the val_loss become worse, you're overfitting -- check out how to deal with that -- increase the amount of the data, make a simpler network or do whatever seems to work in your particular case.

if the val_loss gets better back again, you're on the right path.

And, yeah, share results with us, what happens if you run training for a couple more epochs?

Title: Validation accuracy increases then suddenly decreases

Body:
I am training an LSTM model on the SemEval 2017 task 4A dataset. I observe that first validation accuracy increases along with training accuracy but then suddenly decreases by a significant amount. The loss decreases but validation loss increases by a signifcant amount.

Here is the code of my model

model = Sequential()
model.add(Embedding(max_words, 30, input_length=max_len))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.3))
model.add(Bidirectional(LSTM(32)))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()

And here is the model summary

Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
embedding_2 (Embedding)      (None, 300, 30)           60000
_________________________________________________________________
batch_normalization_3 (Batch (None, 300, 30)           120
_________________________________________________________________
activation_3 (Activation)    (None, 300, 30)           0
_________________________________________________________________
dropout_3 (Dropout)          (None, 300, 30)           0
_________________________________________________________________
bidirectional_2 (Bidirection (None, 64)                16128
_________________________________________________________________
batch_normalization_4 (Batch (None, 64)                256
_________________________________________________________________
activation_4 (Activation)    (None, 64)                0
_________________________________________________________________
dropout_4 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 65
=================================================================
Total params: 76,569
Trainable params: 76,381
Non-trainable params: 188

I am using GloVe for word embeddings, Adam optimizer, Binary Crossentropy loss function.


问:
About infinite loop and memory crash
When I made a program using Visual Studio, I accidentally caught an infinite loop several times. I was embarrassed to see the same sentence being printed very quickly, so I just closed the console. However, when I searched it, it is said that if I get an infinite loop, I need to shut down the processor with ctrl + c.

What I'm worried about is the memory crash. In the microprocessor class, I learned that if I don't exit the infinite loop program properly, it will crash in memory. Is it true that the infinite loop keeps running even if I close the console? If so, is there a workaround?

答:
Once you terminate the program, the infinite loop just stops there. If it keeps running for sometime, it will eventually crash.

Even if your loop is infinite, it will keep running and once it runs out of memory, it will crash and automatically get terminated. You could just as easily terminate a loop using ctrl+C.

Your PC will most probably be Fine

If you are worried if something would happen to your computer/laptop, in most cases  the answer would be NO . Your program will keep running for sometime( time will depend on what the type of loop you are running and process happening inside the loop) and afterwards, you will probably see slowdown of your computer and unresponsiveness. After consuming several GBs of your memory, the process will eventually run out of memory space and would crash and terminate. Once the process terminates, the system will claim back all the memory hogged by the process and everything will be back to normal as it was originally.

Title: About infinite loop and memory crash


问:
Python Regex if there is a brace in string
```<code>the co[njuring](media_title)
</code>```

I want a regex to detect if a pattern like above exist.

Currently I have a regex that turns

```<code>line = Can I please eat at[  warunk upnormal](restaurant_name)

line = re.sub('\[\s*(.*?)\s*\]', r'[\1]', line)
line = re.sub(r'(\w)\[', r'\1 [', line)

Can I please eat at [warunk upnormal](restaurant_name)
</code>```

Notice how there aren't any spaces which is good, and it creates a space char and brace ex. x[ to x [

What I want, is to change the above to regexes to not perform the change if there is a sentences like this

```<code>the co[njuring](media_title)
the co[njuring](media_title) and che[ese dog]s(food)
</code>```

Notice how there is a brace in there. Basically, I want to know how can I improve these regexes to take this into account.

```<code>line = re.sub('\[\s*(.*?)\s*\]', r'[\1]', line)
line = re.sub(r'(\w)\[', r'\1 [', line)
</code>```

答:
For the 2 patterns that you use, you could also use a single pattern with 2 capturing groups.

```<code>(\w)\[\s*(.*?)\s*\]
</code>```

Regex demo and a Python demo

In the replacement use the 2 capturing groups \1 [\2]

Example code

```<code>line = re.sub('(\w)\[\s*(.*?)\s*\]', r'\1 [\2]', line)
</code>```

The different in the given format that I see is that there is an underscore present (instead of a brace) between the parenthesis (restaurant_name) and (media_title) vs (food)

If that is the  case, you can use a third capturing group, matching the value in parenthesis with at least a single underscore present, not at the start and not at the end.

```<code>(\w)\[\s*(.*?)\s*\](\([^_\s()]+(?:_[^_\s()]+)+\))
</code>```

Explanation

(\w) Capture group 1, match a word char

\[\s* Match [ and 0+ whitespace chars

(.*?) Capture group 2, match any char except a newline non greedy

\s*\]  Match 0+ whitespace chars and ]

( Capture group 3

\( Match (

[^_\s()]+ Match 1+ times any char except an underscore, whitespace char or parenthesis

(?:_[^_\s()]+)+ Repeat 1+ times the previous pattern with an underscore prepended

\) Match )

) Close group

In the replacement use the 3 capturing groups \1 [\2]\3

Regex demo and a Python demo

Example code

```<code>import re

regex = r"(\w)\[\s*(.*?)\s*\](\([^_\s()]+(?:_[^_\s()]+)+\))"

test_str = ("Can I please eat at[  warunk upnormal](restaurant_name)\n"
    "Can I please eat at[  warunk upnormal   ](restaurant_name)\n"
    "the co[njuring](media_title)\n"
    "the co[njuring](media_title) and che[ese dog]s(food)")

result = re.sub(regex, r"\1 [\2]\3", test_str)

if result:
    print (result)
</code>```

Output

```<code>Can I please eat at [warunk upnormal](restaurant_name)
Can I please eat at [warunk upnormal](restaurant_name)
the co [njuring](media_title)
the co [njuring](media_title) and che[ese dog]s(food)
</code>```

Body:
the co[njuring](media_title)

I want a regex to detect if a pattern like above exist.

Currently I have a regex that turns

line = Can I please eat at[  warunk upnormal](restaurant_name)

line = re.sub('\[\s*(.*?)\s*\]', r'[\1]', line)
line = re.sub(r'(\w)\[', r'\1 [', line)

Can I please eat at [warunk upnormal](restaurant_name)

Notice how there aren't any spaces which is good, and it creates a space char and brace ex. x[ to x [

What I want, is to change the above to regexes to not perform the change if there is a sentences like this

the co[njuring](media_title)
the co[njuring](media_title) and che[ese dog]s(food)

Notice how there is a brace in there. Basically, I want to know how can I improve these regexes to take this into account.

line = re.sub('\[\s*(.*?)\s*\]', r'[\1]', line)
line = re.sub(r'(\w)\[', r'\1 [', line)

Body:
For the 2 patterns that you use, you could also use a single pattern with 2 capturing groups.

(\w)\[\s*(.*?)\s*\]

Regex demo and a Python demo

In the replacement use the 2 capturing groups \1 [\2]

Example code

line = re.sub('(\w)\[\s*(.*?)\s*\]', r'\1 [\2]', line)

The different in the given format that I see is that there is an underscore present (instead of a brace) between the parenthesis (restaurant_name) and (media_title) vs (food)

If that is the  case, you can use a third capturing group, matching the value in parenthesis with at least a single underscore present, not at the start and not at the end.

(\w)\[\s*(.*?)\s*\](\([^_\s()]+(?:_[^_\s()]+)+\))

Explanation

(\w) Capture group 1, match a word char

\[\s* Match [ and 0+ whitespace chars

(.*?) Capture group 2, match any char except a newline non greedy

\s*\]  Match 0+ whitespace chars and ]

( Capture group 3

\( Match (

[^_\s()]+ Match 1+ times any char except an underscore, whitespace char or parenthesis

(?:_[^_\s()]+)+ Repeat 1+ times the previous pattern with an underscore prepended

\) Match )

) Close group

In the replacement use the 3 capturing groups \1 [\2]\3

Regex demo and a Python demo

Example code

import re

regex = r"(\w)\[\s*(.*?)\s*\](\([^_\s()]+(?:_[^_\s()]+)+\))"

test_str = ("Can I please eat at[  warunk upnormal](restaurant_name)\n"
    "Can I please eat at[  warunk upnormal   ](restaurant_name)\n"
    "the co[njuring](media_title)\n"
    "the co[njuring](media_title) and che[ese dog]s(food)")

result = re.sub(regex, r"\1 [\2]\3", test_str)

if result:
    print (result)

Output

Can I please eat at [warunk upnormal](restaurant_name)
Can I please eat at [warunk upnormal](restaurant_name)
the co [njuring](media_title)
the co [njuring](media_title) and che[ese dog]s(food)


问:
Check if value is false, true or null
I want to check if variable is false, true or null. If null or undefined assign array to the variable by default. In other languages this syntax would be just fine to use. In js however when value is false then it assign array to myBool

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)```
</div>
</div>
</p>

<p>I managed to do it with this syntax where I only check for null value</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);</code>```

Is there any better way to do it in js?

答:
There is an alternative to the other answer that ensures backwards compatibility (it's supported even by IE6) because it doesn't make use of the nullish coalescing operator. It's more verbose but also more convenient and accessible if you aren't using babel.
Hope it helps!

const boolFromBody = null;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const boolFromBody = undefined;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);</code>```

const boolFromBody = false;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);```

Title: Check if value is false, true or null

Body:
I want to check if variable is false, true or null. If null or undefined assign array to the variable by default. In other languages this syntax would be just fine to use. In js however when value is false then it assign array to myBool

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)

I managed to do it with this syntax where I only check for null value

const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);

Is there any better way to do it in js?

Body:
There is an alternative to the other answer that ensures backwards compatibility (it's supported even by IE6) because it doesn't make use of the nullish coalescing operator. It's more verbose but also more convenient and accessible if you aren't using babel.
Hope it helps!

const boolFromBody = null;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = undefined;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = false;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);


问:
Array of filtered data to populate ListBox
Okay so I am filtering a sheet ("Data") by a criteria:

```<code>Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

</code>```

Then, I want to put the Filtered Table to populate a Listbox
My problem here is, that the amount of rows can vary, so I thought i could try and list where the filtered table "ends" by doing this cells.find routine:

```<code>Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1
</code>```

This unfotunatly also counts "hidden" rows, so in my example it doesnt count 2 but 7..
I've used .Range.SpecialCells(xlCellTypeVisible)before, but It doesn't seem to function with the cells.find above.
Does someone have an Idea on how I can count the visible (=filtered) Table, and then put it in a Listbox?

EDIT: I populate the listbox (unfiltered) like this:

```<code>Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With
</code>```

But this won't work with filtered Data.

答:
Try, please the next code, if you want to use a continuous (built) array. It is possible to build it from the discontinuous range address, too:</p>

```<code>    Sub Filter_Offene()
      Dim sh As Worksheet, lastRow As Long, rngFilt As Range, arrFin As Variant

      Set sh = Sheets("Data")
      lastRow = sh.Range("R" & Rows.count).End(xlUp).Row
        rngFilt.AutoFilter field:=18, Criteria1:="WAHR"

        Set rngFilt = rngFilt.Offset(1).SpecialCells(xlCellTypeVisible)

        arrFin = ContinuousArray(rngFilt, sh, "R:R")

        With ComboBox1
            .list = arrFin
            .ListIndex = 0
        End With
    End Sub

    Private Function ContinuousArray(rngFilt As Range, sh As Worksheet, colLet As String) As Variant
        Dim arrFilt As Variant, El As Variant, arFin As Variant
        Dim rowsNo As Long, k As Long, i As Long, j As Long, arrInt As Variant

        arrFilt = Split(rngFilt.address, ",")' Obtain an array of areas addresses
        'real number of rows of the visible cells range:
        For Each El In arrFilt
             rowsNo = rowsNo + Range(El).Rows.count
        Next
        'redim the final array at the number of rows
        ReDim arFin(1 To rowsNo, 1 To rngFilt.Columns.count)

        rowsNo = 1
        For Each El In arrFilt            'Iterate between the areas addresses
            rowsNo = Range(El).Rows.count 'number of rows of the area
            arrInt = ActiveSheet.Range(El).value' put the area range in an array
            For i = 1 To UBound(arrInt, 1) 'fill the final array
                k = k + 1
                For j = 1 To rngFilt.Columns.count
                     arFin(k, j) = arrInt(i, j)
                Next j
            Next i
        Next
    ContinuousArray = arFin
End Function
</code>```

Body:
Okay so I am filtering a sheet ("Data") by a criteria:

Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

Then, I want to put the Filtered Table to populate a Listbox
My problem here is, that the amount of rows can vary, so I thought i could try and list where the filtered table "ends" by doing this cells.find routine:

Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1

This unfotunatly also counts "hidden" rows, so in my example it doesnt count 2 but 7..
I've used .Range.SpecialCells(xlCellTypeVisible)before, but It doesn't seem to function with the cells.find above.
Does someone have an Idea on how I can count the visible (=filtered) Table, and then put it in a Listbox?

EDIT: I populate the listbox (unfiltered) like this:

Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With

But this won't work with filtered Data.

Body:
Try, please the next code, if you want to use a continuous (built) array. It is possible to build it from the discontinuous range address, too:

    Sub Filter_Offene()
      Dim sh As Worksheet, lastRow As Long, rngFilt As Range, arrFin As Variant

      Set sh = Sheets("Data")
      lastRow = sh.Range("R" & Rows.count).End(xlUp).Row
        rngFilt.AutoFilter field:=18, Criteria1:="WAHR"

        Set rngFilt = rngFilt.Offset(1).SpecialCells(xlCellTypeVisible)

        arrFin = ContinuousArray(rngFilt, sh, "R:R")

        With ComboBox1
            .list = arrFin
            .ListIndex = 0
        End With
    End Sub

    Private Function ContinuousArray(rngFilt As Range, sh As Worksheet, colLet As String) As Variant
        Dim arrFilt As Variant, El As Variant, arFin As Variant
        Dim rowsNo As Long, k As Long, i As Long, j As Long, arrInt As Variant

        arrFilt = Split(rngFilt.address, ",")' Obtain an array of areas addresses
        'real number of rows of the visible cells range:
        For Each El In arrFilt
             rowsNo = rowsNo + Range(El).Rows.count
        Next
        'redim the final array at the number of rows
        ReDim arFin(1 To rowsNo, 1 To rngFilt.Columns.count)

        rowsNo = 1
        For Each El In arrFilt            'Iterate between the areas addresses
            rowsNo = Range(El).Rows.count 'number of rows of the area
            arrInt = ActiveSheet.Range(El).value' put the area range in an array
            For i = 1 To UBound(arrInt, 1) 'fill the final array
                k = k + 1
                For j = 1 To rngFilt.Columns.count
                     arFin(k, j) = arrInt(i, j)
                Next j
            Next i
        Next
    ContinuousArray = arFin
End Function


问:
C# implementation of facebook's new "batches" functionality
So I'm trying to use the new "batches" functionality to the graph API, which is described here. I'm think the problem is with the way I'm using POST to submit the data, and I'm having difficulty debugging it. It could be a JSON issue, but I don't think so.
Here's the c#

```<code>        HttpWebRequest httpRequest =(HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] bytedata = Encoding.UTF8.GetBytes(o.ToString());
        httpRequest.ContentLength = bytedata.Length;

        Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytedata, 0, bytedata.Length);
        requestStream.Close();

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
        Stream responseStream = httpWebResponse.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

        string APIData = reader.ReadToEnd();
        JObject MyApiData = JObject.Parse(APIData);
</code>```

And the variables "o" contains the following JSON:

```<code>{
  "access_token": "[my real token]",
  "batch": [
    {
      "method": "get",
      "relative_url": "me"
    },
    {
      "method": "get",
      "relative_url": "me/friends"
    }
  ]
}
</code>```

Any ideas what I'm doing wrong? It actually outputs the facebook's developer website documentation....so I think that's a clue that it's messed up ;-)

答:
Try this out:
               private void PostBatch(string _token)
        {</p>

```<code>        string p1 = "access_token=" + Server.UrlEncode(_token);
        string p2  = "&batch=" + Server.UrlEncode(" [ { \"method\": \"get\", \"relative_url\": \"me\" }, { \"method\": \"get\", \"relative_url\": \"me/friends\" } ]");

        try
        {

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/x-www-form-urlencoded";

            byte[] bytedata = Encoding.UTF8.GetBytes(p1 + p2);
            httpRequest.ContentLength = bytedata.Length;

            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(bytedata, 0, bytedata.Length);
            requestStream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

            string APIData = reader.ReadToEnd();
            Response.Write(APIData);
        }
        catch (Exception ex)
        { Response.Write(ex.Message.ToString() + "<br>"); }
       // JObject MyApiData = JObject.Parse(APIData);

    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I'm trying to use the new "batches" functionality to the graph API, which is described here. I'm think the problem is with the way I'm using POST to submit the data, and I'm having difficulty debugging it. It could be a JSON issue, but I don't think so.
Here's the c#

        HttpWebRequest httpRequest =(HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] bytedata = Encoding.UTF8.GetBytes(o.ToString());
        httpRequest.ContentLength = bytedata.Length;

        Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytedata, 0, bytedata.Length);
        requestStream.Close();

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
        Stream responseStream = httpWebResponse.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

        string APIData = reader.ReadToEnd();
        JObject MyApiData = JObject.Parse(APIData);

And the variables "o" contains the following JSON:

{
  "access_token": "[my real token]",
  "batch": [
    {
      "method": "get",
      "relative_url": "me"
    },
    {
      "method": "get",
      "relative_url": "me/friends"
    }
  ]
}

Any ideas what I'm doing wrong? It actually outputs the facebook's developer website documentation....so I think that's a clue that it's messed up ;-)

Body:
Try this out:
               private void PostBatch(string _token)
        {

        string p1 = "access_token=" + Server.UrlEncode(_token);
        string p2  = "&batch=" + Server.UrlEncode(" [ { \"method\": \"get\", \"relative_url\": \"me\" }, { \"method\": \"get\", \"relative_url\": \"me/friends\" } ]");

        try
        {

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/x-www-form-urlencoded";

            byte[] bytedata = Encoding.UTF8.GetBytes(p1 + p2);
            httpRequest.ContentLength = bytedata.Length;

            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(bytedata, 0, bytedata.Length);
            requestStream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

            string APIData = reader.ReadToEnd();
            Response.Write(APIData);
        }
        catch (Exception ex)
        { Response.Write(ex.Message.ToString() + "<br>"); }
       // JObject MyApiData = JObject.Parse(APIData);

    }


问:
Python list does not append correctly (IndexError: list index out of range)
I tried different approaches for 3 hours now and I just don't get why this does not work.

```<code>current_stock_dict = db.execute("SELECT * FROM current_stocks WHERE c_user_id=:user_id ", user_id=session["user_id"])

    # make a list for the mainpage
    mainpage_list = [[],[]]

    # save the lengh of the dict
    lengh_dict = len(current_stock_dict)
    price_sum = 0
    share_sum = 0

    # iterate over all rows in the dict
    for i in range(0, (lengh_dict - 1)):

        # lookup the symbol in the current stocks
        c_symbol = current_stock_dict[i]["c_symbol"]
        lookup_symbol = lookup(c_symbol)

        # append the symbol to the list for the mainpage
        mainpage_list[i].append(c_symbol)

        # append the name of the share
        share_name = lookup_symbol["name"]
        mainpage_list[i].append(share_name)

        # append the count of shares for mainpage
        c_count = current_stock_dict[i]["c_count"]
        mainpage_list[i].append(c_count)

        # append the current price
        share_price = lookup_symbol["price"]
        mainpage_list[i].append("$" + str(share_price))

        # append the total price of all shares
        total_price = float(share_price) * int(c_count)
        mainpage_list[i].append("$" + str(total_price))

        # count up the price and shares
        price_sum += total_price
        share_sum += c_count
</code>```

When i run my website via Flask i get an error message saying:
IndexError: list index out of range
in the line:
 mainpage_list[i].append(c_symbol)
(and i guess if it did not allready fail there i'd get it for the rest of the lines too).

As long as lengh_dict = len(current_stock_dict) is 3 or less (So the SQL db has 3 rows or less) the error message does not appear and the code works fine. I do not really understand lists (and multidimensional lists) in python yet so i would be happy if somebody could explain my mistake to me.

Normally i would print out a lot of things and just try out where the mistake is but i just began using flask and i can't print out lists, dicts or anything if the code stops before reaching the bug.

Thanks allready for your help!!!

答:
The issue here is that the list mainpage_list is a two element list, and you're trying to access the third element of it.

Generally, when processing lists of indeterminate size, I prefer to iterate and append rather than indexing into the list.

This gives you something like:

```<code>source = ["abc", "def", "ghi"]  # List of data to process
target = []  # The processed data

for row in source:  # For every row of data
    value = []  # Empty list to accumate result in
    value.append(row[2])
    value.append(row[1])
    value.append(row[0])
    target.append(value)

print(target)
</code>```

which will work for any size of source list.

Applying this to your code gives you:

```<code># current_stock is a list of dictionaries.
current_stock = db.execute("SELECT * FROM current_stocks WHERE c_user_id=:user_id ", user_id=session["user_id"])

# make a list for the mainpage
mainpage_list = []

price_sum = 0
share_sum = 0

# iterate over all rows in current_stock
for row in current_stock:
    value = []

    # lookup the symbol in the current stocks
    c_symbol = row["c_symbol"]
    lookup_symbol = lookup(c_symbol)

    # append the symbol to the list for the mainpage
    value.append(c_symbol)

    # append the name of the share
    share_name = lookup_symbol["name"]
    value.append(share_name)

    # append the count of shares for mainpage
    c_count = row["c_count"]
    value.append(c_count)

    # deleted code

    # count up the price and shares
    price_sum += total_price
    share_sum += c_count

    mainpage_list.append(value)
</code>```

Body:
I tried different approaches for 3 hours now and I just don't get why this does not work.

current_stock_dict = db.execute("SELECT * FROM current_stocks WHERE c_user_id=:user_id ", user_id=session["user_id"])

    # make a list for the mainpage
    mainpage_list = [[],[]]

    # save the lengh of the dict
    lengh_dict = len(current_stock_dict)
    price_sum = 0
    share_sum = 0

    # iterate over all rows in the dict
    for i in range(0, (lengh_dict - 1)):

        # lookup the symbol in the current stocks
        c_symbol = current_stock_dict[i]["c_symbol"]
        lookup_symbol = lookup(c_symbol)

        # append the symbol to the list for the mainpage
        mainpage_list[i].append(c_symbol)

        # append the name of the share
        share_name = lookup_symbol["name"]
        mainpage_list[i].append(share_name)

        # append the count of shares for mainpage
        c_count = current_stock_dict[i]["c_count"]
        mainpage_list[i].append(c_count)

        # append the current price
        share_price = lookup_symbol["price"]
        mainpage_list[i].append("$" + str(share_price))

        # append the total price of all shares
        total_price = float(share_price) * int(c_count)
        mainpage_list[i].append("$" + str(total_price))

        # count up the price and shares
        price_sum += total_price
        share_sum += c_count

When i run my website via Flask i get an error message saying:
IndexError: list index out of range
in the line:
 mainpage_list[i].append(c_symbol)
(and i guess if it did not allready fail there i'd get it for the rest of the lines too).

As long as lengh_dict = len(current_stock_dict) is 3 or less (So the SQL db has 3 rows or less) the error message does not appear and the code works fine. I do not really understand lists (and multidimensional lists) in python yet so i would be happy if somebody could explain my mistake to me.

Normally i would print out a lot of things and just try out where the mistake is but i just began using flask and i can't print out lists, dicts or anything if the code stops before reaching the bug.

Thanks allready for your help!!!

Body:
The issue here is that the list mainpage_list is a two element list, and you're trying to access the third element of it.

Generally, when processing lists of indeterminate size, I prefer to iterate and append rather than indexing into the list.

This gives you something like:

source = ["abc", "def", "ghi"]  # List of data to process
target = []  # The processed data

for row in source:  # For every row of data
    value = []  # Empty list to accumate result in
    value.append(row[2])
    value.append(row[1])
    value.append(row[0])
    target.append(value)

print(target)

which will work for any size of source list.

Applying this to your code gives you:

# current_stock is a list of dictionaries.
current_stock = db.execute("SELECT * FROM current_stocks WHERE c_user_id=:user_id ", user_id=session["user_id"])

# make a list for the mainpage
mainpage_list = []

price_sum = 0
share_sum = 0

# iterate over all rows in current_stock
for row in current_stock:
    value = []

    # lookup the symbol in the current stocks
    c_symbol = row["c_symbol"]
    lookup_symbol = lookup(c_symbol)

    # append the symbol to the list for the mainpage
    value.append(c_symbol)

    # append the name of the share
    share_name = lookup_symbol["name"]
    value.append(share_name)

    # append the count of shares for mainpage
    c_count = row["c_count"]
    value.append(c_count)

    # deleted code

    # count up the price and shares
    price_sum += total_price
    share_sum += c_count

    mainpage_list.append(value)


问:
How to get rid of redundancy in a mysql table with lists in an efficient way
Some time ago I made a fast MVP that now has become a more realistic project. Now I'm refactoring and improving it. I have a table like this

```<code>CREATE TABLE `records` (
  `id` int(11) NOT NULL,
  `type` int(11) NOT NULL,
  .....
  `ref` int(11) DEFAULT NULL,
  `enabled` tinyint(1) NOT NULL DEFAULT '1',
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `mrecord`
  ADD PRIMARY KEY (`id`),
  ADD KEY `type` (`type`);
  ADD KEY `ref` (`ref`);
</code>```

ref is a reference to a previous id or null if none and enabled lets me know if this item is the last version of the type. The point is that when an item type X is replaced for a new one, the old one will be disabled (enabled = 0) and the new one will set ref to the old one id.

For example, we have this table with 3 types of items:

```<code> --------------------------------------------
| ID | type | other columns | ref  | enabled |
|--------------------------------------------|
| 1  |   1  |               | null |    1    |
| 2  |   2  |               | null |    1    |
| 3  |   3  |               | null |    1    |
 --------------------------------------------
</code>```

and now we add a new item version that replaces item type 2:

```<code> --------------------------------------------
| ID | type | other columns | ref  | enabled |
|--------------------------------------------|
| 1  |   1  |               | null |    1    |
| 2  |   2  |               | null |    0    |
| 3  |   3  |               | null |    1    |
| 4  |   2  |               |  2   |    1    |
 --------------------------------------------
</code>```

and if we update the brand new item we have:

```<code> --------------------------------------------
| ID | type | other columns | ref  | enabled |
|--------------------------------------------|
| 1  |   1  |               | null |    1    |
| 2  |   2  |               | null |    0    |
| 3  |   3  |               | null |    1    |
| 4  |   2  |               |  2   |    0    |
| 5  |   2  |               |  4   |    1    |
 --------------------------------------------
</code>```

What we have here are lists of item types with only last versions enabled.

But here enabled column is redundant because an enabled item is just an item that has not a new version.

So my problem is how to do a SQL query equivalent to:

```<code>SELECT * FROM `records` WHERE type='2' AND enabled='1'
</code>```

without using enabled and in an efficient way (this query is <1ms).

答:
For this query, you need an index on both columns that appear in the where clause:

```<code>create index myidx on records(type, enabled);
</code>```

With the index, the database should be able to execute the query efficiently. You may also want to try inverting the columns order and see if it increases performance.

Body:
Some time ago I made a fast MVP that now has become a more realistic project. Now I'm refactoring and improving it. I have a table like this

CREATE TABLE `records` (
  `id` int(11) NOT NULL,
  `type` int(11) NOT NULL,
  .....
  `ref` int(11) DEFAULT NULL,
  `enabled` tinyint(1) NOT NULL DEFAULT '1',
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `mrecord`
  ADD PRIMARY KEY (`id`),
  ADD KEY `type` (`type`);
  ADD KEY `ref` (`ref`);

ref is a reference to a previous id or null if none and enabled lets me know if this item is the last version of the type. The point is that when an item type X is replaced for a new one, the old one will be disabled (enabled = 0) and the new one will set ref to the old one id.

For example, we have this table with 3 types of items:

 --------------------------------------------
| ID | type | other columns | ref  | enabled |
|--------------------------------------------|
| 1  |   1  |               | null |    1    |
| 2  |   2  |               | null |    1    |
| 3  |   3  |               | null |    1    |
 --------------------------------------------

and now we add a new item version that replaces item type 2:

 --------------------------------------------
| ID | type | other columns | ref  | enabled |
|--------------------------------------------|
| 1  |   1  |               | null |    1    |
| 2  |   2  |               | null |    0    |
| 3  |   3  |               | null |    1    |
| 4  |   2  |               |  2   |    1    |
 --------------------------------------------

and if we update the brand new item we have:

 --------------------------------------------
| ID | type | other columns | ref  | enabled |
|--------------------------------------------|
| 1  |   1  |               | null |    1    |
| 2  |   2  |               | null |    0    |
| 3  |   3  |               | null |    1    |
| 4  |   2  |               |  2   |    0    |
| 5  |   2  |               |  4   |    1    |
 --------------------------------------------

What we have here are lists of item types with only last versions enabled.

But here enabled column is redundant because an enabled item is just an item that has not a new version.

So my problem is how to do a SQL query equivalent to:

SELECT * FROM `records` WHERE type='2' AND enabled='1'

without using enabled and in an efficient way (this query is <1ms).

Body:
For this query, you need an index on both columns that appear in the where clause:

create index myidx on records(type, enabled);

With the index, the database should be able to execute the query efficiently. You may also want to try inverting the columns order and see if it increases performance.


答:
Let's look at the relevant part of your code.

```<code>mainpage_list = [[],[]]
for i in range(0, (lengh_dict - 1)):
    mainpage_list[i].append(c_symbol)
</code>```

mainpage_list is a list that contains two elements, both of which are empty lists. So, accessing mainpage_list[0] is the first list inside mainpage_list, and mainpage_list[1] is the second empty list. Any index above that will result in an IndexError.

It is not exactly clear what you are trying to achieve, but you could initialize mainpage_list with the correct number of empty lists inside if that is what you need, e.g. for the case where you want as many empty lists as the length of current_stock_dict, you could do

```<code>mainpage_list = [ [] for _ in range(length_dict) ]
</code>```

Title: Python list does not append correctly (IndexError: list index out of range)

Body:
Let's look at the relevant part of your code.

mainpage_list = [[],[]]
for i in range(0, (lengh_dict - 1)):
    mainpage_list[i].append(c_symbol)

mainpage_list is a list that contains two elements, both of which are empty lists. So, accessing mainpage_list[0] is the first list inside mainpage_list, and mainpage_list[1] is the second empty list. Any index above that will result in an IndexError.

It is not exactly clear what you are trying to achieve, but you could initialize mainpage_list with the correct number of empty lists inside if that is what you need, e.g. for the case where you want as many empty lists as the length of current_stock_dict, you could do

mainpage_list = [ [] for _ in range(length_dict) ]


问:
Plotly Dash: How to generate html components with a for loop?
I'm want to create multiple dbc.Button by passing a list of strings to a constructor that generates these buttons, in the following way:

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import plotly.express as px

from functools import lru_cache

import dash_bootstrap_components as dbc

from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State

import pandas as pd

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

def generate_team_button(team_shortName):
    return dbc.Button(
                str(team_shortName),
                color="primary",
                className="mr-1",
                id=str(team_shortName),

            ),

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

colors = {
    'background': '#111111',
    'text': '#7FDBFF'
}

app.layout = html.Div(
    [

        dbc.Row([
            dbc.Col(
               [generate_team_button(i) for i in df_teams.iterrows()]
            )
        ]),

    ],
)

if __name__ == '__main__':
    app.run_server(debug=True)
```

<p>But I'm getting the following error for all the generated buttons when trying to do above:</p>

<pre class="lang-py prettyprint-override"><code>
The children property of a component is a list of lists,
instead of just a list. Check the component that has the
following contents, and remove one of the levels of nesting:
[
  {
    "props": {
      "children": "(0, 0    team1\nName: 0, dtype: object)",
      "id": "(0, 0    team1\nName: 0, dtype: object)",
      "className": "mr-1",
      "color": "primary"
    },
    "type": "Button",
    "namespace": "dash_bootstrap_components"
  }
]
</code>```

What do I have to do to generate the buttons?

答:
There is a small bug in your code, if you delete the comma after the generate_team_button() function you will not get the error anymore. You may also want to replace df_teams.iterrows() with df_teams['teams'], see the example below.

```<code>import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

def generate_team_button(team_shortName):

    return dbc.Button(children=str(team_shortName),
                      color="primary",
                      className="mr-1",
                      id=str(team_shortName))

app.layout = html.Div([

        dbc.Row([

            dbc.Col(children=[generate_team_button(i) for i in df_teams['teams']])

        ])

])

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

Body:
I'm want to create multiple dbc.Button by passing a list of strings to a constructor that generates these buttons, in the following way:

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import plotly.express as px

from functools import lru_cache

import dash_bootstrap_components as dbc

from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State

import pandas as pd

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

def generate_team_button(team_shortName):
    return dbc.Button(
                str(team_shortName),
                color="primary",
                className="mr-1",
                id=str(team_shortName),

            ),

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

colors = {
    'background': '#111111',
    'text': '#7FDBFF'
}

app.layout = html.Div(
    [

        dbc.Row([
            dbc.Col(
               [generate_team_button(i) for i in df_teams.iterrows()]
            )
        ]),

    ],
)

if __name__ == '__main__':
    app.run_server(debug=True)

But I'm getting the following error for all the generated buttons when trying to do above:

The children property of a component is a list of lists,
instead of just a list. Check the component that has the
following contents, and remove one of the levels of nesting:
[
  {
    "props": {
      "children": "(0, 0    team1\nName: 0, dtype: object)",
      "id": "(0, 0    team1\nName: 0, dtype: object)",
      "className": "mr-1",
      "color": "primary"
    },
    "type": "Button",
    "namespace": "dash_bootstrap_components"
  }
]

What do I have to do to generate the buttons?

Body:
There is a small bug in your code, if you delete the comma after the generate_team_button() function you will not get the error anymore. You may also want to replace df_teams.iterrows() with df_teams['teams'], see the example below.

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

def generate_team_button(team_shortName):

    return dbc.Button(children=str(team_shortName),
                      color="primary",
                      className="mr-1",
                      id=str(team_shortName))

app.layout = html.Div([

        dbc.Row([

            dbc.Col(children=[generate_team_button(i) for i in df_teams['teams']])

        ])

])

if __name__ == '__main__':
    app.run_server(debug=True)


问:
Verilog cannot synthesize when using external counter inside generate block
I cannot synthesize the Verilog code in Vivado, simulation runs correctly. I declare an array localparam, use an external counting variable cnt1 inside a generate block to get the desired address for parameter. When I remove the cnt1 variable inside module1, it could be synthesized. Please guys give me some suggestion to solve this problem. I really appreciate that.

```<code>module multiply_s1(
input clk,
input rst,
input [9:0]in,
input ena,

output [9:0]out);

localparam [0:24] pi_values = {5'h4, 5'h5, 5'h6, 5'h7, 5'h8};
reg [1:0] cnt1;//count CC times of GG coeffcient

always@(posedge clk or negedge rst) begin
    if(rst == 0) begin
        cnt1 <= 0;
    end
    else if(ena == 0) begin
        cnt1 <= 0;
    end
    else begin
        if (cnt1 == 3)
            cnt1 <= 0;
        else
            cnt1 <= cnt1 + 1;
    end
end

genvar i;
generate
    for (i=0; i<2; i=i+1)
    begin: mod1
        module1 mod1(.clk(clk),
                     .rst(rst),
                     .multiplier(in[i*5 +: 5]),
                     .multiplicand(pi_values[(i + cnt1)*5 +: 5]),
                     .result(out[i*5 +: 5]));
   end
endgenerate
</code>```

endmodule

答:
Without knowing what Vivado told you, I guess the error may be here:

```<code>[(i + cnt1)*5 +: 5]
</code>```

cnt1 is a register whose value is only known at "runtime", therefore, Vivado cannot know which value to use to bitslicing the pi_values vector.

You would need something like this:

```<code>localparam [0:24] pi_values = {5'h4, 5'h5, 5'h6, 5'h7, 5'h8};
reg [1:0] cnt1;//count CC times of GG coeffcient

always@(posedge clk or negedge rst) begin
    if(rst == 0)
        cnt1 <= 0;
    else if(ena == 0)
        cnt1 <= 0;
    else
        cnt1 <= cnt1 + 1;
end

reg [0:24] pi_values_rotated;
always @* begin
  case (cnt1)
    0: pi_values_rotated = pi_values;
    1: pi_values_rotated = {pi_values[5:24], pi_values[0:4]};
    2: pi_values_rotated = {pi_values[10:24], pi_values[0:9]};
    3: pi_values_rotated = {pi_values[15:24], pi_values[0:14]};
    default: pi_values_rotated = pi_values;
  endcase
end

genvar i;
generate
    for (i=0; i<2; i=i+1)
    begin: mod1
        module1 mod1(.clk(clk),
                     .rst(rst),
                     .multiplier(in[i]),
                     .multiplicand(pi_values_rotated[i*5 +: 5]),
                     .result(out[i]));
   end
endgenerate
</code>```

pi_values_rotated would be the pi_values vector, as seen after the current value of cnt1 is applied. Then, you can use i as the sole value to generate your instances, which should be accepted now.

Body:
I cannot synthesize the Verilog code in Vivado, simulation runs correctly. I declare an array localparam, use an external counting variable cnt1 inside a generate block to get the desired address for parameter. When I remove the cnt1 variable inside module1, it could be synthesized. Please guys give me some suggestion to solve this problem. I really appreciate that.

module multiply_s1(
input clk,
input rst,
input [9:0]in,
input ena,

output [9:0]out);

localparam [0:24] pi_values = {5'h4, 5'h5, 5'h6, 5'h7, 5'h8};
reg [1:0] cnt1;//count CC times of GG coeffcient

always@(posedge clk or negedge rst) begin
    if(rst == 0) begin
        cnt1 <= 0;
    end
    else if(ena == 0) begin
        cnt1 <= 0;
    end
    else begin
        if (cnt1 == 3)
            cnt1 <= 0;
        else
            cnt1 <= cnt1 + 1;
    end
end

genvar i;
generate
    for (i=0; i<2; i=i+1)
    begin: mod1
        module1 mod1(.clk(clk),
                     .rst(rst),
                     .multiplier(in[i*5 +: 5]),
                     .multiplicand(pi_values[(i + cnt1)*5 +: 5]),
                     .result(out[i*5 +: 5]));
   end
endgenerate

endmodule

Body:
Without knowing what Vivado told you, I guess the error may be here:

[(i + cnt1)*5 +: 5]

cnt1 is a register whose value is only known at "runtime", therefore, Vivado cannot know which value to use to bitslicing the pi_values vector.

You would need something like this:

localparam [0:24] pi_values = {5'h4, 5'h5, 5'h6, 5'h7, 5'h8};
reg [1:0] cnt1;//count CC times of GG coeffcient

always@(posedge clk or negedge rst) begin
    if(rst == 0)
        cnt1 <= 0;
    else if(ena == 0)
        cnt1 <= 0;
    else
        cnt1 <= cnt1 + 1;
end

reg [0:24] pi_values_rotated;
always @* begin
  case (cnt1)
    0: pi_values_rotated = pi_values;
    1: pi_values_rotated = {pi_values[5:24], pi_values[0:4]};
    2: pi_values_rotated = {pi_values[10:24], pi_values[0:9]};
    3: pi_values_rotated = {pi_values[15:24], pi_values[0:14]};
    default: pi_values_rotated = pi_values;
  endcase
end

genvar i;
generate
    for (i=0; i<2; i=i+1)
    begin: mod1
        module1 mod1(.clk(clk),
                     .rst(rst),
                     .multiplier(in[i]),
                     .multiplicand(pi_values_rotated[i*5 +: 5]),
                     .result(out[i]));
   end
endgenerate

pi_values_rotated would be the pi_values vector, as seen after the current value of cnt1 is applied. Then, you can use i as the sole value to generate your instances, which should be accepted now.


问:
undefined is not an object (evaluating '_this3.props.navigation.navigate')
Problem with stack navigation between the screens.
I am displaying data on my 'SveKategorije' screen.
It's basically categories buttons, when i click on button i just want to show another screen for now, but it is not working for some reason.
When i put onPress={() => this.props.navigation.navigate('screenname')}
it gives me this
error
I am using (react-native - 0.57.7)

Here is router.js code  (where i declare my routes)

import React from 'react';
import { View, Text, Button } from "react-native";
import { createBottomTabNavigator, createStackNavigator } from "react-navigation";
import { Icon } from 'react-native-elements';

//TABS
import Categories from '../tabs/categories';
import Home from '../tabs/home';
import Me from '../tabs/me';

//screens for CATEGORIES
import ViceviPoKategoriji from '../components/Ispis/ViceviPoKategoriji';

//CATEGORIES STACK
export const categoriesFeedStack = createStackNavigator({

    SveKategorije: {
        screen: Categories,
        navigationOptions: {
            title: 'KATEGORIJE',
        },
    },

    ViceviPoKategoriji: {
        screen: ViceviPoKategoriji,
    }

});

//TABS
export const Tabs = createBottomTabNavigator({

    Categories: {
        screen: categoriesFeedStack,
        navigationOptions: {
            title: 'Kategorije',
            label: 'Kategorije',
            tabBarIcon: ({ tintColor }) => <Icon name="list" size={35} color={tintColor} />,
        }

    },
    Home: {
        screen: Home,
        navigationOptions: {
            title: 'Pocetna',
            label: 'Kategorije',
            tabBarIcon: ({ tintColor }) => <Icon name="home" size={35} color={tintColor} />,
        }

    },
    Me: {
        screen: Me,
        navigationOptions: {
            title: 'Profil',
            label: 'Kategorije',
            tabBarIcon: ({ tintColor }) => <Icon name="account-circle" size={35} color={tintColor} />,
        }
    },

},
    {
        initialRouteName: "Home",
        showIcon: true
    },

);```
</div>
</div>
</p>

<p>Here is 'SveKategorije' screen </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, ScrollView, Button } from 'react-native';
import { createStackNavigator, createAppContainer, StackNavigator, navigate } from 'react-navigation';

export default class SveKategorije extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: null
        }
    }

    componentDidMount() {
        return fetch('http://centarsmijeha.com/api/allCategories')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.data,
                })
            })
            .catch((error) => {
                console.log(error)
            });
    }
    render() {

        if (this.state.isLoading) {
            return (
                <View style={styles.container}>
                    <ActivityIndicator />
                </View>
            )
        } else {
            let data = this.state.dataSource.map((val, key) => {

                return (
                    <View key={key} style={styles.item}>

                        <Button
                            onPress={() => this.props.navigation.navigate('ViceviPoKategoriji')}
                            title={val.categoryName}
                        />
                    </View>
                );

            });
            return (
                <ScrollView>

                    {data}
                </ScrollView >
            );
        }
    }
}

//CSS
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%'
    },
    item: {
        flex: 1,
        alignSelf: 'stretch',
        width: '100%',
        textAlign: 'center',
        alignItems: 'center',
        justifyContent: 'center'
    }
});</code>```

and here is 'ViceviPoKategoriji' screen ( the screen that should be displayed on click of any buttons from 'SveKategorije' screen )

import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, ScrollView } from 'react-native';

export default class ViceviPoKategoriji extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: null,
        }
    }
    componentDidMount() {
        return fetch('http://centarsmijeha.com/api/jokesByCategory/16')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.data,
                })
            })
            .catch((error) => {
                console.log(error)
            });
    }
    render() {
        if (this.state.isLoading) {
            return (
                <View style={styles.container}>
                    <ActivityIndicator />
                </View>
            )
        } else {
            let data = this.state.dataSource.map((val, key) => {

                return <View key={key} style={styles.item}><Text>{val.jokeText}</Text></View>

            });
            return (
                <ScrollView>

                    {data}
                </ScrollView >
            );
        }
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
    item: {
        flex: 1,
        alignSelf: 'stretch',
        marginTop: 50,
        marginRight: '15%',
        marginLeft: '15%',
        width: '70%',
        textAlign: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#eee'
    }
});```

答: In my case I accidentally used this.props.navigation inside functional component. If any one made a mistake like this, will check u r code once again.</p>

Body:
Problem with stack navigation between the screens.
I am displaying data on my 'SveKategorije' screen.
It's basically categories buttons, when i click on button i just want to show another screen for now, but it is not working for some reason.
When i put onPress={() => this.props.navigation.navigate('screenname')}
it gives me this
error
I am using (react-native - 0.57.7)

Here is router.js code  (where i declare my routes)

import React from 'react';
import { View, Text, Button } from "react-native";
import { createBottomTabNavigator, createStackNavigator } from "react-navigation";
import { Icon } from 'react-native-elements';

//TABS
import Categories from '../tabs/categories';
import Home from '../tabs/home';
import Me from '../tabs/me';

//screens for CATEGORIES
import ViceviPoKategoriji from '../components/Ispis/ViceviPoKategoriji';

//CATEGORIES STACK
export const categoriesFeedStack = createStackNavigator({

    SveKategorije: {
        screen: Categories,
        navigationOptions: {
            title: 'KATEGORIJE',
        },
    },

    ViceviPoKategoriji: {
        screen: ViceviPoKategoriji,
    }

});

//TABS
export const Tabs = createBottomTabNavigator({

    Categories: {
        screen: categoriesFeedStack,
        navigationOptions: {
            title: 'Kategorije',
            label: 'Kategorije',
            tabBarIcon: ({ tintColor }) => <Icon name="list" size={35} color={tintColor} />,
        }

    },
    Home: {
        screen: Home,
        navigationOptions: {
            title: 'Pocetna',
            label: 'Kategorije',
            tabBarIcon: ({ tintColor }) => <Icon name="home" size={35} color={tintColor} />,
        }

    },
    Me: {
        screen: Me,
        navigationOptions: {
            title: 'Profil',
            label: 'Kategorije',
            tabBarIcon: ({ tintColor }) => <Icon name="account-circle" size={35} color={tintColor} />,
        }
    },

},
    {
        initialRouteName: "Home",
        showIcon: true
    },

);

Here is 'SveKategorije' screen

import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, ScrollView, Button } from 'react-native';
import { createStackNavigator, createAppContainer, StackNavigator, navigate } from 'react-navigation';

export default class SveKategorije extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: null
        }
    }

    componentDidMount() {
        return fetch('http://centarsmijeha.com/api/allCategories')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.data,
                })
            })
            .catch((error) => {
                console.log(error)
            });
    }
    render() {

        if (this.state.isLoading) {
            return (
                <View style={styles.container}>
                    <ActivityIndicator />
                </View>
            )
        } else {
            let data = this.state.dataSource.map((val, key) => {

                return (
                    <View key={key} style={styles.item}>

                        <Button
                            onPress={() => this.props.navigation.navigate('ViceviPoKategoriji')}
                            title={val.categoryName}
                        />
                    </View>
                );

            });
            return (
                <ScrollView>

                    {data}
                </ScrollView >
            );
        }
    }
}

//CSS
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%'
    },
    item: {
        flex: 1,
        alignSelf: 'stretch',
        width: '100%',
        textAlign: 'center',
        alignItems: 'center',
        justifyContent: 'center'
    }
});

and here is 'ViceviPoKategoriji' screen ( the screen that should be displayed on click of any buttons from 'SveKategorije' screen )

import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, ScrollView } from 'react-native';

export default class ViceviPoKategoriji extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: null,
        }
    }
    componentDidMount() {
        return fetch('http://centarsmijeha.com/api/jokesByCategory/16')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.data,
                })
            })
            .catch((error) => {
                console.log(error)
            });
    }
    render() {
        if (this.state.isLoading) {
            return (
                <View style={styles.container}>
                    <ActivityIndicator />
                </View>
            )
        } else {
            let data = this.state.dataSource.map((val, key) => {

                return <View key={key} style={styles.item}><Text>{val.jokeText}</Text></View>

            });
            return (
                <ScrollView>

                    {data}
                </ScrollView >
            );
        }
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
    item: {
        flex: 1,
        alignSelf: 'stretch',
        marginTop: 50,
        marginRight: '15%',
        marginLeft: '15%',
        width: '70%',
        textAlign: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#eee'
    }
});


问:
session.run() give different results for same input
I'm loading a tensorflow Saved  Model and try to infer with loaded model.

It takes a gray image as input and outputs a gray image of the same size.

```<code>import tensorflow as tf
import numpy as np
from PIL import Image

img_width=224
img_height=224

export_path='/path/to/my/saved/model'
with tf.compat.v1.Session(graph=tf.compat.v1.Graph()) as sess:
  # Load model
  tf.compat.v1.saved_model.loader.load(sess, ['serve'], export_path)

  # Load test image (grayscale)
  path = '/path/to/test/images/image.png'
  img = Image.open(path)
  img.show()
  img_data = np.array(img).reshape(1,img_width,img_height,1)

  # Infer output
  y_pred = sess.run('output:0', feed_dict={'input:0': img_data })
  print(y_pred.shape)

  # Show output image
  im1 = Image.fromarray(np.uint8(y_pred.reshape(img_width,img_height)*255), 'L')
  im1.show()

  # Infer output
  y_pred = sess.run('output:0', feed_dict={'input:0': img_data })

  # Show output image
  im2 = Image.fromarray(np.uint8(y_pred.reshape(img_width,img_height)*255), 'L')
  im2.show()
</code>```

Running this simple code, I got 2 different results. Im1 not exactly the same as Im2.

Am I doing something wrong ?

```<code>import tensorflow as tf
print(tf.__version__)
2.1.0
</code>```

答: I'm certainly not using the right way to reload de TF21 saved model.</p>

Body:
I'm loading a tensorflow Saved  Model and try to infer with loaded model.

It takes a gray image as input and outputs a gray image of the same size.

import tensorflow as tf
import numpy as np
from PIL import Image

img_width=224
img_height=224

export_path='/path/to/my/saved/model'
with tf.compat.v1.Session(graph=tf.compat.v1.Graph()) as sess:
  # Load model
  tf.compat.v1.saved_model.loader.load(sess, ['serve'], export_path)

  # Load test image (grayscale)
  path = '/path/to/test/images/image.png'
  img = Image.open(path)
  img.show()
  img_data = np.array(img).reshape(1,img_width,img_height,1)

  # Infer output
  y_pred = sess.run('output:0', feed_dict={'input:0': img_data })
  print(y_pred.shape)

  # Show output image
  im1 = Image.fromarray(np.uint8(y_pred.reshape(img_width,img_height)*255), 'L')
  im1.show()

  # Infer output
  y_pred = sess.run('output:0', feed_dict={'input:0': img_data })

  # Show output image
  im2 = Image.fromarray(np.uint8(y_pred.reshape(img_width,img_height)*255), 'L')
  im2.show()

Running this simple code, I got 2 different results. Im1 not exactly the same as Im2.

Am I doing something wrong ?

import tensorflow as tf
print(tf.__version__)
2.1.0


问:
How to write local image file path as a uri path
I want to convert the local image file path to the uri path so that in place of uri where a website is require i want to put the local image directory.
I am showing the code below..

```<code>state = {
        search: '',
        images: [
            '../../assets/assets/img/formula.png',  //***this  is not working
            'https://source.unsplash.com/1024x768/?water',
            'https://source.unsplash.com/1024x768/?girl',
            'https://source.unsplash.com/1024x768/?tree'
          ]
      };

//Image is used here..

<SliderBox images={this.state.images} />
</code>```

In image array i want the first image must include from my local file image.
Please someone tell how to do that so that in image I can include my local image file path

答:
A bit late but hopefully it can help someone. You can use resolveAssetSource from Image, so going back to your code it would look like this,

```<code>state = {
    search: '',
    images: [
        Image.resolveAssetSource(require("../../assets/assets/img/formula.png")).uri,
        'https://source.unsplash.com/1024x768/?water',
        'https://source.unsplash.com/1024x768/?girl',
        'https://source.unsplash.com/1024x768/?tree'
      ]
  };
</code>```

Of course you would need to import Image first,

```<code>import { Image } from "react-native";
</code>```

Body:
I want to convert the local image file path to the uri path so that in place of uri where a website is require i want to put the local image directory.
I am showing the code below..

state = {
        search: '',
        images: [
            '../../assets/assets/img/formula.png',  //***this  is not working
            'https://source.unsplash.com/1024x768/?water',
            'https://source.unsplash.com/1024x768/?girl',
            'https://source.unsplash.com/1024x768/?tree'
          ]
      };

//Image is used here..

<SliderBox images={this.state.images} />

In image array i want the first image must include from my local file image.
Please someone tell how to do that so that in image I can include my local image file path

Body:
A bit late but hopefully it can help someone. You can use resolveAssetSource from Image, so going back to your code it would look like this,

state = {
    search: '',
    images: [
        Image.resolveAssetSource(require("../../assets/assets/img/formula.png")).uri,
        'https://source.unsplash.com/1024x768/?water',
        'https://source.unsplash.com/1024x768/?girl',
        'https://source.unsplash.com/1024x768/?tree'
      ]
  };

Of course you would need to import Image first,

import { Image } from "react-native";


问:
How to get char[] to work with std::map
EDIT after answered:

< should be provided for std::map. For more information about best practice, go for James McNellis's answer.

The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but it turned out to be not fast enough.

Thank you.

I know I cannot use char[] directly with map, such as map<char[], int>. Thus I put it in a class. But it still can go through compilation. How to deal with that?

```<code>#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}
</code>```

```<code>/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’
</code>```

It seems it has something to do with comparison, but I am still in the dark.

答:
First things first:  never, ever use gets.  It cannot be used safely and any program that uses it has a security vulnerability.  There is no way to limit the number of characters that gets can write to the buffer that you provide it, so there is no way to prevent a buffer overflow.  If you do need to use the C I/O library, you should use fgets instead, which allows you to specify the maximum number of characters to be read.

The reason that you are seeing this error is that the key type that you use must be comparable somehow.  By default std::map uses operator<, which you do not define for id, hence the compilation error.  You either need to define operator< to compare two id objects or you need to write a comparator functor that can be used to compare the two objects.  Regardless which you choose, the comparator must provide a strict-weak ordering.

Since you are programming in C++, the ideal solution here is to use idiomatic C++:

```<code>std::map<std::string, int> m;
std::string s;
while (std::cin >> s) {
    m[s]++;
}
</code>```

std::string already provides operator< that provides a lexicographic ordering, so you don't need to define a comparator yourself.

Title: How to get char[] to work with std::map

Body:
EDIT after answered:

< should be provided for std::map. For more information about best practice, go for James McNellis's answer.

The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but it turned out to be not fast enough.

Thank you.

I know I cannot use char[] directly with map, such as map<char[], int>. Thus I put it in a class. But it still can go through compilation. How to deal with that?

#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}

/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’

It seems it has something to do with comparison, but I am still in the dark.

Body:
First things first:  never, ever use gets.  It cannot be used safely and any program that uses it has a security vulnerability.  There is no way to limit the number of characters that gets can write to the buffer that you provide it, so there is no way to prevent a buffer overflow.  If you do need to use the C I/O library, you should use fgets instead, which allows you to specify the maximum number of characters to be read.

The reason that you are seeing this error is that the key type that you use must be comparable somehow.  By default std::map uses operator<, which you do not define for id, hence the compilation error.  You either need to define operator< to compare two id objects or you need to write a comparator functor that can be used to compare the two objects.  Regardless which you choose, the comparator must provide a strict-weak ordering.

Since you are programming in C++, the ideal solution here is to use idiomatic C++:

std::map<std::string, int> m;
std::string s;
while (std::cin >> s) {
    m[s]++;
}

std::string already provides operator< that provides a lexicographic ordering, so you don't need to define a comparator yourself.


答:
You can use not exists:

```<code>select  r.*
from records r
where not exists (select 1
                  from records r2
                  where r2.ref = r.id
                 ) and
       r.type = 2;
</code>```

However, the use of enabled makes the code clearer, in my opinion.  An index on records(ref) is needed for performance.

If you assumes that the ids are always incrementing, you could also use the largest id.

Title: How to get rid of redundancy in a mysql table with lists in an efficient way

Body:
You can use not exists:

select  r.*
from records r
where not exists (select 1
                  from records r2
                  where r2.ref = r.id
                 ) and
       r.type = 2;

However, the use of enabled makes the code clearer, in my opinion.  An index on records(ref) is needed for performance.

If you assumes that the ids are always incrementing, you could also use the largest id.


问:
How to make 15px of free space under the picture?
Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/44/

body
{
    left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 0px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li
{
    display: flex;
    align-items: center;
}

.box3 > li span
{
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

    <div class="box3">

        <li>
            <img src="pictures/contact/skype.png" width="34px" height="34px" />
            <span>Skype name</span>
        </li>

        <li>
            <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
            <span>Gadu-Gadu number</span>
        </li>

        <li>
            <img src="pictures/contact/email.png" width="34px" height="34px" />
            <span>Email address</span>
        </li>

    </div>

</body></code>```

Unfortunately, these 2 variants are wrong!

Variant number 1:

.box3 > li img
{
    margin-bottom: 15px;
}```
</div>
</div>
</p>
<p>Variant number 2:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box3 > li img
{
    padding: 0px 0px 15px;
}</code>```

padding -> 15px (as the upper space), 40px (as the left space) and 0px (as the bottom space)

How to make 15px of free space under the picture?

I will be very grateful for effective help.

答:
First of all, you should never ever put position: absolute on your body element because that will make the element loose its box dimensions. Your body element is actually 0x0 px.

To address your issue, just remove the 0px in the padding, as I did in the code below.

[edit] OK, you wanted all images to have space beneath them, not just the single picture, which was asked in the OP. I added additional code below:

body
{
 left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
 background-color: #191919;
 position: absolute;
 /* padding: 15px 40px 0px; */
 padding: 15px 40px;
 font-size: 12px;
 color: #DDDDDD;
 font-family: Verdana;
 font-size: 12px;
 width: 400px;
}

.box3 > li
{
 display: flex;
 align-items: center;
}

.box3 > li span
{
 margin: 5px;
}

/* Added. select li that is followed by an li. */
.box3 > li ~ li {
  margin-top: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

 <div class="box3">

  <li>
   <img src="pictures/contact/skype.png" width="34px" height="34px" />
   <span>Skype name</span>
  </li>

  <li>
   <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
   <span>Gadu-Gadu number</span>
  </li>

  <li>
   <img src="pictures/contact/email.png" width="34px" height="34px" />
   <span>Email address</span>
  </li>

 </div>

</body></code>```

Body:
Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/44/

body
{
    left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 0px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li
{
    display: flex;
    align-items: center;
}

.box3 > li span
{
    margin: 5px;
}

            Skype name

            Gadu-Gadu number

            Email address

Unfortunately, these 2 variants are wrong!

Variant number 1:

.box3 > li img
{
    margin-bottom: 15px;
}

Variant number 2:

.box3 > li img
{
    padding: 0px 0px 15px;
}

padding -> 15px (as the upper space), 40px (as the left space) and 0px (as the bottom space)

How to make 15px of free space under the picture?

I will be very grateful for effective help.

Body:
First of all, you should never ever put position: absolute on your body element because that will make the element loose its box dimensions. Your body element is actually 0x0 px.

To address your issue, just remove the 0px in the padding, as I did in the code below.

[edit] OK, you wanted all images to have space beneath them, not just the single picture, which was asked in the OP. I added additional code below:

body
{
 left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
 background-color: #191919;
 position: absolute;
 /* padding: 15px 40px 0px; */
 padding: 15px 40px;
 font-size: 12px;
 color: #DDDDDD;
 font-family: Verdana;
 font-size: 12px;
 width: 400px;
}

.box3 > li
{
 display: flex;
 align-items: center;
}

.box3 > li span
{
 margin: 5px;
}

/* Added. select li that is followed by an li. */
.box3 > li ~ li {
  margin-top: 15px;
}

<body>

 <div class="box3">

  <li>
   <img src="pictures/contact/skype.png" width="34px" height="34px" />
   <span>Skype name</span>
  </li>

  <li>
   <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
   <span>Gadu-Gadu number</span>
  </li>

  <li>
   <img src="pictures/contact/email.png" width="34px" height="34px" />
   <span>Email address</span>
  </li>

 </div>

</body>


问:
Is there a modern way to run java applications in browser?
Is there a modern way to run java application on the web? As far as I know, java applets and java web start both are deprecated.

I have an android app, written in java, which I want to run on server (of course, altered in some way). While java is cross-platform there is no problem to transfer it to desktop (no matter, javafx, swing or etc.).

Apparently, it would be great not to re-write it in some other language.

答:
There is an HelloWorld Example Java-Program which is running in a browser:

https://github.com/neo-expert/jsjvm_helloworld

After compiling you can just run the jar file which starts a webserver where the program will be served. (port 8080)


问:
Going from Jupyter Notebook to Command Prompt - pass arguments
I've been learning python coding using jupyter notebooks and now I need to call this program from command prompt.

```<code>import sys
import codecs
import re

incoming_file =  open ('file_with_bad_character.xml', 'r')
outgoing_file = open ('cleaned_up_file.xml', 'a')

cc = [u'\u0015', u'\u0009']
def remove_control_characters(s):
    return re.sub ("|".join(cc), '', line)

for line in incoming_file.readlines():
    outgoing_file.write(remove_control_characters(line))
outgoing_file.close()
</code>```

The purpose of this code is the read a file (incoming_file) and write a file out removing the two special control characters. I don't want the file name to change and I want to be able to call this code form command prompt passing it one arguments, the file name.

Can someone please suggest if this is the right approach and help me transition this from jupyter notebook to a python script I can call from command prompt?

答:
One option is to run a command to convert the file to .py, but the easiest way is to execute the command:
ipython [file_name.ipynb]</p>

Body:
I've been learning python coding using jupyter notebooks and now I need to call this program from command prompt.

import sys
import codecs
import re

incoming_file =  open ('file_with_bad_character.xml', 'r')
outgoing_file = open ('cleaned_up_file.xml', 'a')

cc = [u'\u0015', u'\u0009']
def remove_control_characters(s):
    return re.sub ("|".join(cc), '', line)

for line in incoming_file.readlines():
    outgoing_file.write(remove_control_characters(line))
outgoing_file.close()

The purpose of this code is the read a file (incoming_file) and write a file out removing the two special control characters. I don't want the file name to change and I want to be able to call this code form command prompt passing it one arguments, the file name.

Can someone please suggest if this is the right approach and help me transition this from jupyter notebook to a python script I can call from command prompt?


问:
Can Modbus slave report events to master?
I want to daisy chain Modbus slave with momentary switch.

Since Modbus is a Master/Slave protocole I’m not even sure if this is the way to go.

My understanding is that for the master to be aware of such events he must poll each single slave to read they register state.

Maybe this is trivial for this protocole and doesn’t generate overhang on the bus, or maybe I must switch to a different protocole?

I’ve found countless example of modbus master controlling slave (like motor, relay any kind of actuator) or even read temperature / humidity from sensors but I’m struggling to find any example of “events based sensors” Like momentary switch for instance...

答:
No, only the master can send data requests and also in Modbus RTU (serial) there can only exist a single master in the entire network.

With Modbus TCP there can be several masters.

If you want a protocol in which all connected devices can both send and read data take a look at MQTT, which works through the Publish-Subscribe system and not with Request-Response which is how most industrial protocols work, including Modbus.

Another protocol that could work for you is OPC UA, which apart from Request -Response also allows the master. through subscriptions. to receive data from a slave when the data value changes, without the need of a previous request.


问:
Why is it bad to pause/abort threads?
My model of how threads work is that some ThreadManager gives each thread a turn.  When it's a thread's turn, it gets to execute a few lines of code.

To pause a thread, couldn't one just have the ThreadManager (momentarily) stop allowing that thread to have a turn?

To abort a thread, couldn't the ThreadManager just never give that thread another turn?

What's the problem?

答:
Quote from MSDN about pausing threads:

You have no way of knowing what code a
  thread is executing when you suspend
  it. If you suspend a thread while it
  holds locks during a security
  permission evaluation, other threads
  in the AppDomain might be blocked. If
  you suspend a thread while it is
  executing a class constructor, other
  threads in the AppDomain that attempt
  to use that class are blocked.
  Deadlocks can occur very easily.

Aborted thread can lead to unpredicted circumstances. There is a good article about this: http://www.bluebytesoftware.com/blog/2009/03/13/ManagedCodeAndAsynchronousExceptionHardening.aspx

Title: Why is it bad to pause/abort threads?