问:
Minecraft Server Paper player.setResourcePack doesn't work
I'm currently working on a Plugin, which lets Players decide, whether they want to load a 16x16 ResourcePack or a 32x32 one. The packs are forced (they're needed for the gameplay). My problem is, that when I select a pack it should do this:

```<code>p.setResourcePack("https://github.com/Ole1Tau1/RPG/blob/main/RPGPack.zip", "E3CED908E76C7390DDC4F47C22F6FF16", true);
</code>```

But instead of loading it, the client gives me an error:

Server resource pack couldn't be applied

Any functionality that requires custom resources might not work as expected

Anybody got an idea what I did wrong?

Full code is here BTW: https://github.com/Ole1Tau1/RPG/tree/main/RPSelector/src/main/java/dev/onetone/rpg/rpselector

答:
Your repository seems private. So, only you -with your account- can access to it. With this, for all players that tried to download it, it will return 404 error.

To fix this, you can:

Make your repository public. I think you don't want, but if it contains only the zip file, it's fine.

Create a second repository to host it. It can be a good solution if you already have another repo with a wiki or other help that are public.

Use something else to host it. A website on the server where spigot is running, another website or anything else, you can host the zip file then change the link in your plugin.

Body:
I'm currently working on a Plugin, which lets Players decide, whether they want to load a 16x16 ResourcePack or a 32x32 one. The packs are forced (they're needed for the gameplay). My problem is, that when I select a pack it should do this:

p.setResourcePack("https://github.com/Ole1Tau1/RPG/blob/main/RPGPack.zip", "E3CED908E76C7390DDC4F47C22F6FF16", true);

But instead of loading it, the client gives me an error:

Server resource pack couldn't be applied

Any functionality that requires custom resources might not work as expected

Anybody got an idea what I did wrong?

Full code is here BTW: https://github.com/Ole1Tau1/RPG/tree/main/RPSelector/src/main/java/dev/onetone/rpg/rpselector


来源: stackexchange

问:
Python: how to tell if number strings mixed European or US format, cast all of them to float?
I want to convert all of the numbers in my list to float.

Every number contains 2 or 3 decimal places.

In some cases, I may have US number strings, such as:

```<code>"0.00", "0.000", "874.80", "10.000", "1,234.56"
</code>```

In other cases, I may have European format, like the following:

```<code>"29.461,24", "20.919,000", "0,00", "0,000", "372,13", "11,000"
</code>```

I want to identify which one is which and format it correctly to be cast to float. Such as the US numbers becoming.

```<code>"0.00", "0.000", "874.80", "10.000", "1234.56"
</code>```

and the EU numbers becoming

```<code>"29461.24", "20919.000", "0.00", "0.000", "372.13", "11.000"
</code>```

How can I do this in Python?

I know that

```<code>sub(r'[\.|]', '', sub(r',', '.', i))
</code>```

Converts from E to a ready to cast format, but it will break US numbers.

答:
This is my proposed solutions which works assuming that there are only 2 numbers after the decimal sign. Code can be optimized, but works as an initial quick and dirty solution.</p>
```<code>us_nodec1 = "1,000,000"
us_nodec2 = "1,234"
us_dec = "1,334.99"
us_dec1 = "334.99"
eu_nodec1 = "1.000.000"
eu_nodec2 = "2.431"
eu_dec = "3,432.33"
eu_dec1 = "432,44"

def fix_nr_format(string):
    comma_counts = string.count(',')
    point_counts = string.count('.')
    comma_splits = string.split(',')
    point_splits = string.split('.')
    if comma_splits.__len__() > 1:
        if comma_splits[-1].__len__() > 2:
            string = string.replace(',', '')
        elif comma_splits[-1].__len__() == 2:
            if not string.__contains__('.'):
                string = string.replace(',', '.')
            else:
                string = string.replace('.', '', point_counts-1)
    if point_splits.__len__() > 1:
        if point_splits[-1].__len__() > 2:
            string = string.replace('.', '')
        elif point_splits[-1].__len__() == 2:
            if not string.__contains__(','):
                pass
            else:
                string.replace(',', '', comma_counts-1)
    return float(string)
print(fix_nr_format(eu_dec))
print(fix_nr_format(eu_dec1))
print(fix_nr_format(eu_nodec1))
print(fix_nr_format(eu_nodec2))
print(fix_nr_format(us_nodec1))
print(fix_nr_format(us_nodec2))
print(fix_nr_format(us_dec))
print(fix_nr_format(us_dec1))
3432.33
432.44
1000000.0
2431.0
1000000.0
1234.0
1334.99
334.99
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to convert all of the numbers in my list to float.

Every number contains 2 or 3 decimal places.

In some cases, I may have US number strings, such as:

"0.00", "0.000", "874.80", "10.000", "1,234.56"

In other cases, I may have European format, like the following:

"29.461,24", "20.919,000", "0,00", "0,000", "372,13", "11,000"

I want to identify which one is which and format it correctly to be cast to float. Such as the US numbers becoming.

"0.00", "0.000", "874.80", "10.000", "1234.56"

and the EU numbers becoming

"29461.24", "20919.000", "0.00", "0.000", "372.13", "11.000"

How can I do this in Python?

I know that

sub(r'[\.|]', '', sub(r',', '.', i))

Converts from E to a ready to cast format, but it will break US numbers.

Body:
This is my proposed solutions which works assuming that there are only 2 numbers after the decimal sign. Code can be optimized, but works as an initial quick and dirty solution.

us_nodec1 = "1,000,000"
us_nodec2 = "1,234"
us_dec = "1,334.99"
us_dec1 = "334.99"
eu_nodec1 = "1.000.000"
eu_nodec2 = "2.431"
eu_dec = "3,432.33"
eu_dec1 = "432,44"

def fix_nr_format(string):
    comma_counts = string.count(',')
    point_counts = string.count('.')
    comma_splits = string.split(',')
    point_splits = string.split('.')
    if comma_splits.__len__() > 1:
        if comma_splits[-1].__len__() > 2:
            string = string.replace(',', '')
        elif comma_splits[-1].__len__() == 2:
            if not string.__contains__('.'):
                string = string.replace(',', '.')
            else:
                string = string.replace('.', '', point_counts-1)
    if point_splits.__len__() > 1:
        if point_splits[-1].__len__() > 2:
            string = string.replace('.', '')
        elif point_splits[-1].__len__() == 2:
            if not string.__contains__(','):
                pass
            else:
                string.replace(',', '', comma_counts-1)
    return float(string)
print(fix_nr_format(eu_dec))
print(fix_nr_format(eu_dec1))
print(fix_nr_format(eu_nodec1))
print(fix_nr_format(eu_nodec2))
print(fix_nr_format(us_nodec1))
print(fix_nr_format(us_nodec2))
print(fix_nr_format(us_dec))
print(fix_nr_format(us_dec1))
3432.33
432.44
1000000.0
2431.0
1000000.0
1234.0
1334.99
334.99

ContentLicense: CC BY-SA 4.0


问:
Is right pass hsahMap to repository mvvm android
Hi is right pass HashMap to functions in repository

```<code>void sendComment(HashMap<String, String> data){
FirebaseDatabase.getInstance(). getRefrence().setValue(data);
}
</code>```

And in viewmodel i create HashMap var and add key,value to it like

```<code>HashMap<String, String> data=new HashMap<>();
data.add("commentText","any text");
data.add("senderId","any text");
data.add("postId","any text");
repo.sendComment(data);
</code>```

Is that true or should i add arguments senderId,postId,commentText
In function in repository
Like

```<code>void sendComment(String postId,String senderId){
//Add to database code
}
</code>```

答:
first of all you can use SparseArray instead of HashMap . because SparseArray is intended to be more memory-efficient than a HashMap, because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping
depends on your task .

```<code>SparseArray<Int>().set(key , value)
</code>```

you can use the repository for change any object(data) to save in DB or send to the server and change any object(data) to pass to ui and viewModel .

Body:
Hi is right pass HashMap to functions in repository

void sendComment(HashMap<String, String> data){
FirebaseDatabase.getInstance(). getRefrence().setValue(data);
}

And in viewmodel i create HashMap var and add key,value to it like

HashMap<String, String> data=new HashMap<>();
data.add("commentText","any text");
data.add("senderId","any text");
data.add("postId","any text");
repo.sendComment(data);

Is that true or should i add arguments senderId,postId,commentText
In function in repository
Like

void sendComment(String postId,String senderId){
//Add to database code
}

Body:
first of all you can use SparseArray instead of HashMap . because SparseArray is intended to be more memory-efficient than a HashMap, because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping
depends on your task .

SparseArray<Int>().set(key , value)

you can use the repository for change any object(data) to save in DB or send to the server and change any object(data) to pass to ui and viewModel .


问:
Locating table cell using the header cell text
I have table kind of appearance as shown below but it's not a single table. Header is in one table and rows are in another table.

The header has Primary, Language and the add button which is one table and rest of the two rows are in another table. Now I have to identify the cell using the header text. For an example, If I give 1 Language then it has to locate the first row second cell in which Arabic is chosen. Likewise, If I give 2 Primary it has locate the second row first column.

The HTML code is shown in the pic below. If it's possible to solve this problem, then I will give the actual code.

```<code><div id="d78Pt30" style="width: 35em;" class="gridMaxHeight z-grid">
    <div id="d78Pt30-head" class="z-grid-header" style="">
        <table id="d78Pt30-headtbl" style="table-layout: fixed;" width="100%">
            <colgroup id="d78Px30-hdfaker">
                <col id="d78Py30-hdfaker" style="width: 61px;">
                <col id="d78Pz30-hdfaker" style="">
                <col id="d78P_40-hdfaker" style="width: 50px;">
                <col id="d78Px30-hdfaker-bar" style="width: 0px">
            </colgroup>
            <tbody id="d78Pt30-headrows">
            <tr id="d78Px30" class="z-columns" style="text-align: left;">
                <th id="d78Py30" class="z-column">
                    <div id="d78Py30-cave" class="z-column-content">
                        <div class="z-column-sorticon"><i id="d78Py30-sort-icon"></i></div>
                        Primary
                    </div>
                </th>
                <th id="d78Pz30" class="z-column">
                    <div id="d78Pz30-cave" class="z-column-content">
                        <div class="z-column-sorticon"><i id="d78Pz30-sort-icon"></i></div>
                        Language
                    </div>
                </th>
                <th id="d78P_40" class="z-column">
                    <div id="d78P_40-cave" class="z-column-content">
                        <div class="z-column-sorticon"><i id="d78P_40-sort-icon"></i></div>
                        <a id="d78P040" class="z-a" href="javascript:;"><img src="assets/images/add.png"
                                                                             align="absmiddle"></a></div>
                </th>
                <th id="d78Px30-bar" class="z-columns-bar"></th>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="z-grid-header-border"></div>
    <div id="d78Pt30-body" class="z-grid-body" style="overflow: auto;">
        <table id="d78Pt30-cave" style="table-layout: fixed;" width="100%">
            <colgroup id="d78Px30-bdfaker">
                <col id="d78Py30-bdfaker" style="width: 61px;">
                <col id="d78Pz30-bdfaker" style="">
                <col id="d78P_40-bdfaker" style="width: 50px;">
            </colgroup>
            <tbody id="d78Pi50" class="z-rows">
            <tr id="d78P260" class="gridMaxHeight z-row">
                <td id="d78P360-chdextr" class="z-row-inner">
                    <div id="d78P360-cell" class="z-row-content"><span id="d78P360"
                                                                       class="z-radio z-radio-default"><input
                            type="radio" id="d78P360-real" name="d78P360" checked="checked"><label for="d78P360-real"
                                                                                id="d78P360-cnt"
                                                                                class="z-radio-content"></label></span>
                    </div>
                </td>
                <td id="d78P460-chdextr" class="z-row-inner">
                    <div id="d78P460-cell" class="z-row-content"><span id="d78P460" class="z-combobox"
                                                                       style="width: 225px;"><input id="d78P460-real"
                                                                                class="z-combobox-input"
                                                                                autocomplete="off"
                                                                                value="" type="text"
                                                                                size="20"
                                                                                style="width: 196px;"><a
                            id="d78P460-btn" class="z-combobox-button"><i id="d78P460-icon"
                                                                          class="z-combobox-icon z-icon-caret-down"></i></a><div
                            id="d78P460-pp" style="display: none;"></div></span></div>
                </td>
                <td id="d78Py60-chdextr" class="z-row-inner">
                    <div id="d78Py60-cell" class="z-row-content">
                        <div id="d78Py60" class="z-hlayout">
                            <div id="d78Pz60-chdex" class="z-hlayout-inner" style=""><a id="d78Pz60" class="z-a"
                                                                                href="javascript:;"><img
                                    src="assets/images/delete.png" align="absmiddle"></a></div>
                        </div>
                    </div>
                </td>
            </tr>
            </tbody>
            <tbody class="z-grid-emptybody">
            <tr>
                <td id="d78Pt30-empty" style="display: none;" colspan="3">
                    <div id="d78Pt30-empty-content" class="z-grid-emptybody-content">No data available</div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

As you can see in the HTML, there are two tables and first one is having the header and second one is having the rest of the rows.

答:
Since the full markup of the table was not provided, I've used the HTML at the end of the answer to illustrate the possible solutions.

Solution 1 - Hardcode the column index

If the table columns are _static, the easiest solution is to hardcode an index lookup in your code. This solution also makes it easier to deal with header cells that do not have text - eg the add icon.

For example, you know that "Language" header is always column index 1 and "Primary" is always column index 0. Therefore, you know that if you want the "Language" of a data row, it will be the 2nd cell in the row.

```<code>def cell_by_header_text(browser, data_row_index, header_text)
  columns = ['Primary', 'Language', 'Add'] # must match the order on the page
  column_index = columns.index(header_text)

  data_table = browser.div(class: 'z-grid-body').table
  data_table[data_row_index - 1][column_index] # returns Watir::Cell
end

p cell_by_header_text(browser, 1, 'Language').html
#=> "<td><select><option selected=\"selected\">Arabic</option><option>Bengali</option></select></td>"
p cell_by_header_text(browser, 2, 'Primary').html
#=> "<td><input type=\"radio\" checked=\"\"></td>"
</code>```

Solution 2 - Dynamic lookup of column index

If the table columns are dynamic or you want a more general solution, you can lookup the column index from the header table.

```<code>def cell_by_header_text(browser, data_row_index, header_text)
  header_table = browser.div(class: 'z-grid-header').table
  column_index = header_table.tds.find_index { |td| td.text == header_text }

  data_table = browser.div(class: 'z-grid-body').table
  data_table[data_row_index - 1][column_index] # returns Watir::Cell
end
</code>```

Solution 3 - Domain-specific collection

If you want to improve readability and have more flexibility, you could take it a step further and create a domain-specific collection for the grid:

```<code>class LanguageRowCollection
  include Enumerable

  def initialize(browser)
    @browser = browser
  end

  def each
    data_rows.map { |data| yield LanguageRow.new(header_row, data) }
  end

  def [](value)
    to_a[value]
  end

  private

  def header_row
    @browser.div(class: 'z-grid-header').table.tr
  end

  def data_rows
    @browser.div(class: 'z-grid-body').table.trs
  end
end

class LanguageRow
  def initialize(header_row, tr)
    @header_row = header_row
    @tr = tr
  end

  def primary_cell
    @tr.tds[@header_row.tds.map(&:text).index('Primary')]
  end

  def primary?
    primary_cell.radio.selected?
  end

  def set_primary(value)
    primary_cell.radio.set(value)
  end

  def language_cell
    @tr.tds[@header_row.tds.map(&:text).index('Language')]
  end

  def language
    language_cell.select.text
  end

  def set_language(value)
    language_cell.select.set(value)
  end

  def remove_cell
    # Locating the 3rd column by it's image since it doesn't have text
    @tr.tds[@header_row.tds.find_index { |td| td.image(class: 'add').exists? }]
  end

  def remove
    remove_cell.link.click
  end
end

def languages(browser)
  grid = browser.div(class: 'z-grid')
  LanguageRowCollection.new(grid)
end
</code>```

You get a more readable way to get/set values:

```<code># Get/set the language of the first row (note the 0-based index)
languages(browser)[0].language
#=> "Arabic"
languages(browser)[0].set_language('Bengali')
</code>```

You also get the flexibility of locating rows based on their values:

```<code># Get the primary language
languages(browser).find(&:primary?).language
#=> "Bengali"

# Remove the Arabic row
languages(browser).find { |l| l.language == 'Arabic' }.remove
</code>```

HTML Example

The following HTML was used for the above examples.

```<code><html>
  <body>
    <div id="d78Pt30" class="gridMaxHeight -grid">
      <div class="z-grid-header">
        <table>
          <tr>
            <td>Primary</td>
            <td>Language</td>
            <td>Add</td>
          </tr>
        </table>
      </div>
      <div class="z-grid-header-border"></div>
      <div class="z-grid-body">
        <table>
          <tr>
            <td><input type="radio"></td>
            <td><select><option selected="selected">Arabic</option><option>Bengali</option></select></td>
            <td><a href="#">Minus</a></td>
          </tr>
          <tr>
            <td><input type="radio" checked></td>
            <td><select><option>Arabic</option><option selected="selected">Bengali</option></select></td>
            <td><a href="#">Minus</a></td>
          </tr>
      </div>
    </div>
  </body>
</html>
</code>```

Body:
I have table kind of appearance as shown below but it's not a single table. Header is in one table and rows are in another table.

The header has Primary, Language and the add button which is one table and rest of the two rows are in another table. Now I have to identify the cell using the header text. For an example, If I give 1 Language then it has to locate the first row second cell in which Arabic is chosen. Likewise, If I give 2 Primary it has locate the second row first column.

The HTML code is shown in the pic below. If it's possible to solve this problem, then I will give the actual code.

            <colgroup id="d78Px30-hdfaker">
                <col id="d78Py30-hdfaker" style="width: 61px;">
                <col id="d78Pz30-hdfaker" style="">
                <col id="d78P_40-hdfaker" style="width: 50px;">
                <col id="d78Px30-hdfaker-bar" style="width: 0px">
            </colgroup>

                        Primary

                        Language

            <colgroup id="d78Px30-bdfaker">
                <col id="d78Py30-bdfaker" style="width: 61px;">
                <col id="d78Pz30-bdfaker" style="">
                <col id="d78P_40-bdfaker" style="width: 50px;">
            </colgroup>

<input
                            type="radio" id="d78P360-real" name="d78P360" checked="checked">

<input id="d78P460-real"
                                                                                class="z-combobox-input"
                                                                                autocomplete="off"
                                                                                value="" type="text"
                                                                                size="20"
                                                                                style="width: 196px;">

No data available

As you can see in the HTML, there are two tables and first one is having the header and second one is having the rest of the rows.

Body:
Since the full markup of the table was not provided, I've used the HTML at the end of the answer to illustrate the possible solutions.

Solution 1 - Hardcode the column index

If the table columns are _static, the easiest solution is to hardcode an index lookup in your code. This solution also makes it easier to deal with header cells that do not have text - eg the add icon.

For example, you know that "Language" header is always column index 1 and "Primary" is always column index 0. Therefore, you know that if you want the "Language" of a data row, it will be the 2nd cell in the row.

def cell_by_header_text(browser, data_row_index, header_text)
  columns = ['Primary', 'Language', 'Add'] # must match the order on the page
  column_index = columns.index(header_text)

  data_table = browser.div(class: 'z-grid-body').table
  data_table[data_row_index - 1][column_index] # returns Watir::Cell
end

p cell_by_header_text(browser, 1, 'Language').html
#=> "<td><select><option selected=\"selected\">Arabic</option><option>Bengali</option></select></td>"
p cell_by_header_text(browser, 2, 'Primary').html
#=> "<td><input type=\"radio\" checked=\"\"></td>"

Solution 2 - Dynamic lookup of column index

If the table columns are dynamic or you want a more general solution, you can lookup the column index from the header table.

def cell_by_header_text(browser, data_row_index, header_text)
  header_table = browser.div(class: 'z-grid-header').table
  column_index = header_table.tds.find_index { |td| td.text == header_text }

  data_table = browser.div(class: 'z-grid-body').table
  data_table[data_row_index - 1][column_index] # returns Watir::Cell
end

Solution 3 - Domain-specific collection

If you want to improve readability and have more flexibility, you could take it a step further and create a domain-specific collection for the grid:

class LanguageRowCollection
  include Enumerable

  def initialize(browser)
    @browser = browser
  end

  def each
    data_rows.map { |data| yield LanguageRow.new(header_row, data) }
  end

  def [](value)
    to_a[value]
  end

  private

  def header_row
    @browser.div(class: 'z-grid-header').table.tr
  end

  def data_rows
    @browser.div(class: 'z-grid-body').table.trs
  end
end

class LanguageRow
  def initialize(header_row, tr)
    @header_row = header_row
    @tr = tr
  end

  def primary_cell
    @tr.tds[@header_row.tds.map(&:text).index('Primary')]
  end

  def primary?
    primary_cell.radio.selected?
  end

  def set_primary(value)
    primary_cell.radio.set(value)
  end

  def language_cell
    @tr.tds[@header_row.tds.map(&:text).index('Language')]
  end

  def language
    language_cell.select.text
  end

  def set_language(value)
    language_cell.select.set(value)
  end

  def remove_cell
    # Locating the 3rd column by it's image since it doesn't have text
    @tr.tds[@header_row.tds.find_index { |td| td.image(class: 'add').exists? }]
  end

  def remove
    remove_cell.link.click
  end
end

def languages(browser)
  grid = browser.div(class: 'z-grid')
  LanguageRowCollection.new(grid)
end

You get a more readable way to get/set values:

# Get/set the language of the first row (note the 0-based index)
languages(browser)[0].language
#=> "Arabic"
languages(browser)[0].set_language('Bengali')

You also get the flexibility of locating rows based on their values:

# Get the primary language
languages(browser).find(&:primary?).language
#=> "Bengali"

# Remove the Arabic row
languages(browser).find { |l| l.language == 'Arabic' }.remove

HTML Example

The following HTML was used for the above examples.

<html>
  <body>
    <div id="d78Pt30" class="gridMaxHeight -grid">
      <div class="z-grid-header">
        <table>
          <tr>
            <td>Primary</td>
            <td>Language</td>
            <td>Add</td>
          </tr>
        </table>
      </div>
      <div class="z-grid-header-border"></div>
      <div class="z-grid-body">
        <table>
          <tr>
            <td><input type="radio"></td>
            <td><select><option selected="selected">Arabic</option><option>Bengali</option></select></td>
            <td><a href="#">Minus</a></td>
          </tr>
          <tr>
            <td><input type="radio" checked></td>
            <td><select><option>Arabic</option><option selected="selected">Bengali</option></select></td>
            <td><a href="#">Minus</a></td>
          </tr>
      </div>
    </div>
  </body>
</html>


问:
OnbackPrees to return home always in react stack navigation
I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations

What is happening

On home:
go details then go A
back arrow press in A, it  return  back to  details

Need actions

On home:
go details then go A
back arrow press in A  return  back to home instead of details

The code I try

```<code>import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;
</code>```

答:
u can do it by passing "key" to "navigate"
more info (source):
https://reactnavigation.org/docs/navigation-prop/

https://reactnavigation.org/docs/navigation-prop/#going-back-from-a-specific-screen

navigation.navigate({ name: SCREEN, key: SCREEN_KEY_A });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_B });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_C });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_D });
```
<pre class="lang-js prettyprint-override"><code>navigation.navigate({ key: SCREEN_KEY_A }); // will go to screen A FROM screen D
</code>```

Body:
I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations

What is happening

On home:
go details then go A
back arrow press in A, it  return  back to  details

Need actions

On home:
go details then go A
back arrow press in A  return  back to home instead of details

The code I try

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;

Body:
u can do it by passing "key" to "navigate"
more info (source):
https://reactnavigation.org/docs/navigation-prop/

https://reactnavigation.org/docs/navigation-prop/#going-back-from-a-specific-screen

navigation.navigate({ name: SCREEN, key: SCREEN_KEY_A });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_B });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_C });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_D });

navigation.navigate({ key: SCREEN_KEY_A }); // will go to screen A FROM screen D


问:
How to create watermark like shutterstock and Adobe Stock in python
I am trying to create a GAN model which will remove watermark. After doing some homework, I got to this Google AI Blog which makes things worse. Thus I need to create a dataset from these websites Shutterstock, Adobe Stock, Fotolia and Canstock and manymore.

So, when I try to do same image using reverse image search. I founded out that the resolutions, images are changed which makes it more worse.

Thus, I'm only left to create a custom dataset doing the same watermark like from these websites and that's why I need to create same watermark like them on images from unsplash and so..

Can anyone please help me create same watermark which we can get from Shutterstock and Adobe Stock. It'd be a great help.

Note: I have gone through this link for watermark using Imagemagick but I need it in python. If someone can show me a way of doing the same in python. That'd be a great help.

EDIT1: If you look at this Example of Shutterstock. Zoom in and you will find that not only lines but text and rounded symbols are curved and also name and rounded symbol with different opacity. So, that's what I want to replicate.

答:
Here is one way to do that in Python/OpenCV.

Read the input

Create an image of the text

Rotate the text image

Tile out the rotated text image to the size of the input

Blend the tiled, rotated text image with the input image

Save the output

Input:

```<code>import cv2
import numpy as np
import math

text = "WATERMARK"
thickness = 2
scale = 0.75
pad = 5
angle = -45
blend = 0.25

   def rotate_bound(image, angle):
    # function to rotate an image
    # from https://github.com/PyImageSearch/imutils/blob/master/imutils/convenience.py
    # grab the dimensions of the image and then determine the center
    (h, w) = image.shape[:2]
    (cX, cY) = (w / 2, h / 2)

    # grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    # perform the actual rotation and return the image
    return cv2.warpAffine(image, M, (nW, nH))

# read image
photo = cv2.imread('lena.jpg')
ph, pw = photo.shape[:2]

# determine size for text image
(wd, ht), baseLine = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, scale, thickness)
print (wd, ht, baseLine)

# add text to black background image padded all around
pad2 = 2 * pad
text_img = np.zeros((ht+pad2,wd+pad2,3), dtype=np.uint8)
text_img = cv2.putText(text_img, text, (pad,ht+pad), cv2.FONT_HERSHEY_SIMPLEX, scale, (255,255,255), thickness)

# rotate text image
text_rot = rotate_bound(text_img, angle)
th, tw = text_rot.shape[:2]

# tile the rotated text image to the size of the input
xrepeats = math.ceil(pw/tw)
yrepeats = math.ceil(ph/th)
print(yrepeats,xrepeats)
tiled_text = np.tile(text_rot, (yrepeats,xrepeats,1))[0:ph, 0:pw]

# combine the text with the image
result = cv2.addWeighted(photo, 1, tiled_text, blend, 0)

# save results
cv2.imwrite("text_img.png", text_img)
cv2.imwrite("text_img_rot.png", text_rot)
cv2.imwrite("lena_tiled_rotated_text_img.jpg", result)

# show the results
cv2.imshow("text_img", text_img)
cv2.imshow("text_rot", text_rot)
cv2.imshow("tiled_text", tiled_text)
cv2.imshow("result", result)
cv2.waitKey(0)
</code>```

Text Image:

Rotated Text Image:

Result:

Body:
Here is one way to do that in Python/OpenCV.

Read the input

Create an image of the text

Rotate the text image

Tile out the rotated text image to the size of the input

Blend the tiled, rotated text image with the input image

Save the output

Input:

import cv2
import numpy as np
import math

text = "WATERMARK"
thickness = 2
scale = 0.75
pad = 5
angle = -45
blend = 0.25

   def rotate_bound(image, angle):
    # function to rotate an image
    # from https://github.com/PyImageSearch/imutils/blob/master/imutils/convenience.py
    # grab the dimensions of the image and then determine the center
    (h, w) = image.shape[:2]
    (cX, cY) = (w / 2, h / 2)

    # grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    # perform the actual rotation and return the image
    return cv2.warpAffine(image, M, (nW, nH))

# read image
photo = cv2.imread('lena.jpg')
ph, pw = photo.shape[:2]

# determine size for text image
(wd, ht), baseLine = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, scale, thickness)
print (wd, ht, baseLine)

# add text to black background image padded all around
pad2 = 2 * pad
text_img = np.zeros((ht+pad2,wd+pad2,3), dtype=np.uint8)
text_img = cv2.putText(text_img, text, (pad,ht+pad), cv2.FONT_HERSHEY_SIMPLEX, scale, (255,255,255), thickness)

# rotate text image
text_rot = rotate_bound(text_img, angle)
th, tw = text_rot.shape[:2]

# tile the rotated text image to the size of the input
xrepeats = math.ceil(pw/tw)
yrepeats = math.ceil(ph/th)
print(yrepeats,xrepeats)
tiled_text = np.tile(text_rot, (yrepeats,xrepeats,1))[0:ph, 0:pw]

# combine the text with the image
result = cv2.addWeighted(photo, 1, tiled_text, blend, 0)

# save results
cv2.imwrite("text_img.png", text_img)
cv2.imwrite("text_img_rot.png", text_rot)
cv2.imwrite("lena_tiled_rotated_text_img.jpg", result)

# show the results
cv2.imshow("text_img", text_img)
cv2.imshow("text_rot", text_rot)
cv2.imshow("tiled_text", tiled_text)
cv2.imshow("result", result)
cv2.waitKey(0)

Text Image:

Rotated Text Image:

Result:


问:
How to lower this image and background without creating a massive margin where nothing can be entered to?
Hi can anyone help me I'm trying to have this image and background in the center of my page but also down from the red bar I can only seem to do it with a massive margin which I can't put anything in, any advice would be appreciated thank you.

```<code>HTML:
<main>
    <img src="image/cup_coffee.png" alt="Cup of coffee with raw coffee beans around it" class="cup_coffee">
        <span>This is a text</span>
    </main>

CSS:
main{
background-color: #e6e6e6;
display: relative;
margin-left: auto;
margin-right: auto;
width: 50%
</code>```

This is what it looks like at the moment

答:
Try it with a flex as a display instead of relative.

.main {
  background-color: #e6e6e6;
  display: flex;
  justify-content: center;
  width: 50%
}
```

Body:
Hi can anyone help me I'm trying to have this image and background in the center of my page but also down from the red bar I can only seem to do it with a massive margin which I can't put anything in, any advice would be appreciated thank you.

HTML:

        This is a text

CSS:
main{
background-color: #e6e6e6;
display: relative;
margin-left: auto;
margin-right: auto;
width: 50%

This is what it looks like at the moment


问:
Rich Inspect Discovery
Im trying to dig into the Rich inpsect further to understand how it is doing the following.

If I look at an object (result) like so. I can see that it has the following attributes and methods.

```<code>>>> vars(result)
{'name': 'hello_world'}
>>> print(dir(result))
[
    '__class__',
    '__class_getitem__',
    '__contains__',
    '__delattr__',
    '__delitem__',
    '__dict__',
    '__dir__',
    '__doc__',
    '__eq__',
    '__format__',
    '__ge__',
    '__getattribute__',
    '__getitem__',
    '__gt__',
    '__hash__',
    '__init__',
    '__init_subclass__',
    '__iter__',
    '__le__',
    '__len__',
    '__lt__',
    '__module__',
    '__ne__',
    '__new__',
    '__orig_bases__',
    '__parameters__',
    '__reduce__',
    '__reduce_ex__',
    '__repr__',
    '__reversed__',
    '__setattr__',
    '__setitem__',
    '__sizeof__',
    '__slots__',
    '__str__',
    '__subclasshook__',
    '__weakref__',
    '_is_protocol',
    'clear',
    'copy',
    'failed',
    'failed_hosts',
    'fromkeys',
    'get',
    'items',
    'keys',
    'name',
    'pop',
    'popitem',
    'raise_on_error',
    'setdefault',
    'update',
    'values'
]
</code>```

If I look at the output of Rich like so:

```<code>>>> inspect(result)
╭─────────────────────────────────────────────────────────────────────────────── <class 'nornir.core.task.AggregatedResult'> ────────────────────────────────────────────────────────────────────────────────╮
│ It basically is a dict-like object that aggregates the results for all devices.                                                                                │
│ You can access each individual result by doing ``my_aggr_result["hostname_of_device"]``.                                                                                │
│                                                                                │
│ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │ AggregatedResult (hello_world): {'spine1-nxos': MultiResult: [Result: "hello_world", Result: "ABC1", Result: "ABC1a", Result: "ABC1b"], 'spine2-nxos': MultiResult: [Result: "hello_world", Result:    │ │
│ │ "ABC1", Result: "ABC1a", Result: "ABC1b"]}                                                                                │ │
│ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
│                                                                                │
│       failed = False                                                                                │
│ failed_hosts = {}                                                                                │
│         name = 'hello_world'                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
</code>```

I see that it has correctly only shown be the attributes and methods of interest.
Can anyone point to me how Rich determines what to print?

Thanks,

答:
The nice thing about open-source code is that you can just go find the source and read it. For this question, you'll be interested in this file in the rich source code. You're mostly interested in the _render method, though some things are set up in __init__.

We can break down the output you were seeing, to properly understand it:

```<code>╭─────────────────────────────────────────────────────────────────────────────── <class 'nornir.core.task.AggregatedResult'> ────────────────────────────────────────────────────────────────────────────────╮
</code>```

The top line contains the "title" of the object being inspected. In this case, it's the repr of the class of the object.

```<code>│ It basically is a dict-like object that aggregates the results for all devices.                                                                                │
│ You can access each individual result by doing ``my_aggr_result["hostname_of_device"]``.                                                                                │
</code>```

This is the docstring of the object.

```<code>│ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │ AggregatedResult (hello_world): {'spine1-nxos': MultiResult: [Result: "hello_world", Result: "ABC1", Result: "ABC1a", Result: "ABC1b"], 'spine2-nxos': MultiResult: [Result: "hello_world", Result:    │ │
│ │ "ABC1", Result: "ABC1a", Result: "ABC1b"]}                                                                                │ │
│ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
</code>```

This is the pretty-printed "value" of the object. It's probably based on the object's own repr, but I've not dived too deeply into how rich.pretty.Pretty works, so there might be more to it.

```<code>│       failed = False                                                                                │
│ failed_hosts = {}                                                                                │
│         name = 'hello_world'                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
</code>```

The rest of the output is a list of attributes and their values. By default, only the non-callable, non-_private, non-__dunder__ attributes will be listed, but you could get a more complete list with different arguments to inspect.

Title: Rich Inspect Discovery

Body:
Im trying to dig into the Rich inpsect further to understand how it is doing the following.

If I look at an object (result) like so. I can see that it has the following attributes and methods.

>>> vars(result)
{'name': 'hello_world'}
>>> print(dir(result))
[
    '__class__',
    '__class_getitem__',
    '__contains__',
    '__delattr__',
    '__delitem__',
    '__dict__',
    '__dir__',
    '__doc__',
    '__eq__',
    '__format__',
    '__ge__',
    '__getattribute__',
    '__getitem__',
    '__gt__',
    '__hash__',
    '__init__',
    '__init_subclass__',
    '__iter__',
    '__le__',
    '__len__',
    '__lt__',
    '__module__',
    '__ne__',
    '__new__',
    '__orig_bases__',
    '__parameters__',
    '__reduce__',
    '__reduce_ex__',
    '__repr__',
    '__reversed__',
    '__setattr__',
    '__setitem__',
    '__sizeof__',
    '__slots__',
    '__str__',
    '__subclasshook__',
    '__weakref__',
    '_is_protocol',
    'clear',
    'copy',
    'failed',
    'failed_hosts',
    'fromkeys',
    'get',
    'items',
    'keys',
    'name',
    'pop',
    'popitem',
    'raise_on_error',
    'setdefault',
    'update',
    'values'
]

If I look at the output of Rich like so:

>>> inspect(result)
╭─────────────────────────────────────────────────────────────────────────────── <class 'nornir.core.task.AggregatedResult'> ────────────────────────────────────────────────────────────────────────────────╮
│ It basically is a dict-like object that aggregates the results for all devices.                                                                                │
│ You can access each individual result by doing ``my_aggr_result["hostname_of_device"]``.                                                                                │
│                                                                                │
│ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │ AggregatedResult (hello_world): {'spine1-nxos': MultiResult: [Result: "hello_world", Result: "ABC1", Result: "ABC1a", Result: "ABC1b"], 'spine2-nxos': MultiResult: [Result: "hello_world", Result:    │ │
│ │ "ABC1", Result: "ABC1a", Result: "ABC1b"]}                                                                                │ │
│ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
│                                                                                │
│       failed = False                                                                                │
│ failed_hosts = {}                                                                                │
│         name = 'hello_world'                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

I see that it has correctly only shown be the attributes and methods of interest.
Can anyone point to me how Rich determines what to print?

Thanks,

Body:
The nice thing about open-source code is that you can just go find the source and read it. For this question, you'll be interested in this file in the rich source code. You're mostly interested in the _render method, though some things are set up in __init__.

We can break down the output you were seeing, to properly understand it:

╭─────────────────────────────────────────────────────────────────────────────── <class 'nornir.core.task.AggregatedResult'> ────────────────────────────────────────────────────────────────────────────────╮

The top line contains the "title" of the object being inspected. In this case, it's the repr of the class of the object.

│ It basically is a dict-like object that aggregates the results for all devices.                                                                                │
│ You can access each individual result by doing ``my_aggr_result["hostname_of_device"]``.                                                                                │

This is the docstring of the object.

│ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │ AggregatedResult (hello_world): {'spine1-nxos': MultiResult: [Result: "hello_world", Result: "ABC1", Result: "ABC1a", Result: "ABC1b"], 'spine2-nxos': MultiResult: [Result: "hello_world", Result:    │ │
│ │ "ABC1", Result: "ABC1a", Result: "ABC1b"]}                                                                                │ │
│ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │

This is the pretty-printed "value" of the object. It's probably based on the object's own repr, but I've not dived too deeply into how rich.pretty.Pretty works, so there might be more to it.

│       failed = False                                                                                │
│ failed_hosts = {}                                                                                │
│         name = 'hello_world'                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

The rest of the output is a list of attributes and their values. By default, only the non-callable, non-_private, non-__dunder__ attributes will be listed, but you could get a more complete list with different arguments to inspect.


问:
Trying to make a discord but I keep getting the error "required is not defined"
I'm really new at this and I'm trying to get the bot to come online but no matter what I do the error message comes up, I also downloaded requirejs but it doesn't seem to be working. basically, I have no idea what I'm doing and need help.</p>
```<code>const {Clients, Intents} = require(discord.js);
const TOKEN = '************************************************'
const client = new Client({
    intents: [
        Inents.FLAGS.GUILDS,
        Intents.FLags.GUILD_MESSAGES,
    ]
});

client.once('ready', () => {
    console.log('Logged in as ${client.user.tag}')
});
client.login(TOKEN);
</code>```

答:
You need to put discord.js in quotes like this:

const {Clients, Intents} = require("discord.js");
```

Body:
I'm really new at this and I'm trying to get the bot to come online but no matter what I do the error message comes up, I also downloaded requirejs but it doesn't seem to be working. basically, I have no idea what I'm doing and need help.

const {Clients, Intents} = require(discord.js);
const TOKEN = '************************************************'
const client = new Client({
    intents: [
        Inents.FLAGS.GUILDS,
        Intents.FLags.GUILD_MESSAGES,
    ]
});

client.once('ready', () => {
    console.log('Logged in as ${client.user.tag}')
});
client.login(TOKEN);


问:
SQL Match table and multiple columns
I wanted to know a Query where in which i want to locate a specific table that contains two or more columns:

I tried:

```<code>SELECT *
FROM DB
WHERE TableName = 'TableName'
AND ColumName in('column1' , 'column2')
</code>```

But this query will look if any of those columns are there, but i want it to return only if all of them are a match.

I hope this questions makes sense.

答:
This should work for you in MySQL:

```<code>SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME in ('column1','column2')
AND TABLE_SCHEMA='your_database'
GROUP BY table_name
HAVING COUNT(COLUMN_NAME) =2;
</code>```

Title: SQL Match table and multiple columns

Body:
I wanted to know a Query where in which i want to locate a specific table that contains two or more columns:

I tried:

SELECT *
FROM DB
WHERE TableName = 'TableName'
AND ColumName in('column1' , 'column2')

But this query will look if any of those columns are there, but i want it to return only if all of them are a match.

I hope this questions makes sense.

Body:
This should work for you in MySQL:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME in ('column1','column2')
AND TABLE_SCHEMA='your_database'
GROUP BY table_name
HAVING COUNT(COLUMN_NAME) =2;


问:
Go mock function from extenal lib without interface
I’ve used the following logger lib for our program.
We have create unit tests and we need to provide mock for version 0.4.0
https://github.com/go-logr/logr/blob/v0.4.0/logr.go#L148

This is how we mocked the functions which works as expected

```<code>type testLog struct {
    msg   string
    key   string
    value string
}

func (log *testLog) Enabled() bool {
    return true
}

func (log *testLog) Info(msg string, keysAndValues ...interface{}) {
    log.msg = msg
    log.key = keysAndValues[0].(string)
    log.value = keysAndValues[1].(string)
}

func (log *testLog) Error(err error, msg string, keysAndValues ...interface{}) {
}

func (log *testLog) V(level int) logr.Logger {
    return &testLog{}
}

func (log *testLog) WithValues(keysAndValues ...interface{}) logr.Logger {
    return &testLog{}
}

func (log *testLog) WithName(name string) logr.Logger {
    return &testLog{}
}
</code>```

Now we need to upgrade to version 1.2.0
And the implementation is changed, there is no interface.
My question is how should I mock the logger with the new version ?

See this link with the followed functions
https://github.com/go-logr/logr/blob/v1.2.2/logr.go#L230

答:
My question is how should I mock the logger with the new version ?

You cannot. Come up with a non mock-based testing strategy.

Body:
I’ve used the following logger lib for our program.
We have create unit tests and we need to provide mock for version 0.4.0
https://github.com/go-logr/logr/blob/v0.4.0/logr.go#L148

This is how we mocked the functions which works as expected

type testLog struct {
    msg   string
    key   string
    value string
}

func (log *testLog) Enabled() bool {
    return true
}

func (log *testLog) Info(msg string, keysAndValues ...interface{}) {
    log.msg = msg
    log.key = keysAndValues[0].(string)
    log.value = keysAndValues[1].(string)
}

func (log *testLog) Error(err error, msg string, keysAndValues ...interface{}) {
}

func (log *testLog) V(level int) logr.Logger {
    return &testLog{}
}

func (log *testLog) WithValues(keysAndValues ...interface{}) logr.Logger {
    return &testLog{}
}

func (log *testLog) WithName(name string) logr.Logger {
    return &testLog{}
}

Now we need to upgrade to version 1.2.0
And the implementation is changed, there is no interface.
My question is how should I mock the logger with the new version ?

See this link with the followed functions
https://github.com/go-logr/logr/blob/v1.2.2/logr.go#L230


问:
How do I tell TypeScript that two variables have the same type?
I have a few classes that all have the same function with a parameter that takes itself:

```<code>class Foo {
    someProp: number;
    constructor() {
        this.someProp = 5;
    }

    takesSelf(x: Foo | number) {}
}

class Bar {
    someProp: string;
    constructor() {
        this.someProp = "string";
    }

    takesSelf(x: Bar | string) {}
}
</code>```

Now I have two variables, of which I know that both are the same type, both are either Foo or Bar, the two types will never be mixed. But if I call takesSelf I get a type error.

```<code>const typeA = new Bar() as Foo | Bar;
const typeB = new Bar() as Foo | Bar;
typeA.takesSelf(typeB);
//              ^^^^^----- Type 'Foo' is not assignable to type 'Bar'
</code>```

Which makes sense, because TypeScript doesn't know these two variables will always share the same type.

How can I tell TypeScript these two variables will have the same type, while keeping things type safe?

For context, here's how I'm ending up with a situation of two variables that are known to both have the same type:

```<code>const fooBarMap = new Map<number, Foo | Bar>();

function assertIsSameType(a: Foo | Bar, b: Foo | Bar) {
    if (!(a instanceof b.constructor)) {
        throw new Error("a and b are not of the same type");
    }
}

function passAToB(a: number, b: number) {
    const typeA = fooBarMap.get(a);
    const typeB = fooBarMap.get(b);

    if (!typeA || !typeB) return;
    assertIsSameType(typeA, typeB);

    typeA.takesSelf(typeB);
    //              ^^^^^----- Type 'Foo' is not assignable to type 'Bar'
}
</code>```

Here's a playground link with an example and some failed experiments.

答:
I hope I understood you correctly and this is your use case, if so then you can use TS generics for that

Ex:

// This way you will have typesafe and keep DRY for this method
type TakeSelf<T extends Object> = (x: T)=> void

class Foo {
    takesSelf: TakeSelf<this>
}

class Bar {
    takesSelf: TakeSelf<this>
}
```

Body:
I have a few classes that all have the same function with a parameter that takes itself:

class Foo {
    someProp: number;
    constructor() {
        this.someProp = 5;
    }

    takesSelf(x: Foo | number) {}
}

class Bar {
    someProp: string;
    constructor() {
        this.someProp = "string";
    }

    takesSelf(x: Bar | string) {}
}

Now I have two variables, of which I know that both are the same type, both are either Foo or Bar, the two types will never be mixed. But if I call takesSelf I get a type error.

const typeA = new Bar() as Foo | Bar;
const typeB = new Bar() as Foo | Bar;
typeA.takesSelf(typeB);
//              ^^^^^----- Type 'Foo' is not assignable to type 'Bar'

Which makes sense, because TypeScript doesn't know these two variables will always share the same type.

How can I tell TypeScript these two variables will have the same type, while keeping things type safe?

For context, here's how I'm ending up with a situation of two variables that are known to both have the same type:

const fooBarMap = new Map<number, Foo | Bar>();

function assertIsSameType(a: Foo | Bar, b: Foo | Bar) {
    if (!(a instanceof b.constructor)) {
        throw new Error("a and b are not of the same type");
    }
}

function passAToB(a: number, b: number) {
    const typeA = fooBarMap.get(a);
    const typeB = fooBarMap.get(b);

    if (!typeA || !typeB) return;
    assertIsSameType(typeA, typeB);

    typeA.takesSelf(typeB);
    //              ^^^^^----- Type 'Foo' is not assignable to type 'Bar'
}

Here's a <a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEBiD29oG8CwAoAkBeBbApgAoBO8ADgFzQB2ArrgEb7EDcGmw81EALsbcB7xiACgCUKdph4ALAJYQAdDgIly0ALzQArGywBfDOx5gA1vggBlfCABmIgB5UESAD416TYhOSH0fjFBIGAAhMGJJLBUiUkpoXmI5agBzPQ4uBIEhUR8pWQVlPBj1LQAiBKTk0rSArBNzKxt7J2gwiPcKlJ8-Ws5uHmhbRDaAWTAyTRp8AHdoMbIAHjpGZgAaOERodzaAPnE9DFtaakE5Lmhg5h4ASSswAgAVAE8yfBEwZ03t8PWGT7dWuFclg5LZoCIAITvaBJXhgE74eBghiKPqZQTCMTAzDSGSkWbUGbQACixFIolKYAu1AAJtAGBdiPgaPABkjoLJmRB7syeC98KUxDUMLUjiceGdqNAyMEAIIPeAhd5UZZeX4qzzMbFogZ816yyZDRXheaKZL4HjvIXsHUc-khQ3DE3jM0WkQMa3odig8EQvX4A2udx++0SJk8WjEahpS7EG53R78kT+2Xrf0hT3GfmyxT1CzWOzJ0NpAD0JegFcrVarAD063WALRNpvQZ6vaAAchcHZhMGorIuUDkyWoYAYIF5SH9nbaHZFRnQZegAAl4LMaUhrtAJwM2-hLMBEmQBqZ+7MAAYp8-UumX+3X6ZyEAgC4gaZgJ4wJjQdmc+I8u1XgAfgXMsHnkFIYC3Pg5HwGkKECDJdWzSZCVmNpxEHDYATaPRbXTVCiQwiRIGwrZAVYRD+mgYBIB4PcDS0FMsP9X97TwpCaLovcHSY+0WP5Nj9Tw7js1zMx8yaItXgzFhoCXftXgwFNxIaAt7Fo3geKFeTy0U-BAlE-VVMkwtNPo4tdNfHAWSUr17LFU5znNQlEmAWBqAWB5oHwBweHwWkYBccjdmVVt1VbbEwBMxpCw9OSl14J8X2YckYAoER53QFzmDkdzqGkgM02LBdDmOJypVjHhLB5MLgu+YgIvqiiJCoKqYCpBRAMRZEUFqKqaoIQrU262TlLEvNYvsdMdKXdroA3Fl8hSaAKBLUrF3LcCuumYRTAgX5aF1eQYC6qkmRpAQ4J8hx7jICdFAwJcRieaAmTAF9OBpZk+hMWELm3AdcGEH7wCgbqYBs-IYEfZ9oHNAZaGSEBXoAR1oPLTEe9AfWGmF+nhYAerIgAyEnRvxuEEXZFxsRUyb1MKsb-B8kAIGZXHmNhExqbBNpoDJinucJ4m2jpiaJKmpnPVqJ7ywQCIz2gLcZDAAA3ZkmRwONrqEBD0FtcyGIAJkmZjSOQBmmioRwqGOU812oCQNB2aA1fgOQaT8I3s2NmLGZmg5NoAdXkYAZF7Jb4loV4ImnblbAMg2jIDP2rcLUoQDkHh-OID6UepJ5luSVn2YW+ALGoDsBlS4RC+BplBRYIA" rel="nofollow noreferrer">playground link with an example and some failed experiments.


问:
Filtering data after fetching in React
I need to make a list of objects based on combined data from 2 arrays, one comes from a localStorage and the second one from Django backend. First of all objects from localStorage are displayed by showCart() function

```<code>export const showCart = () => {
    if (typeof window !== undefined) {
        if (localStorage.getItem("cart")) {
            return JSON.parse(localStorage.getItem("cart"));
        };
    };
};
</code>```

it returns data in this format: FE: { id: 1, amount: 7, size: "L", product: 1 }. product is the Foreign Key needed to match data from other array.

The second array comes form a backend and it is feched by getAllProducts() function

```<code>export const getAllProducts = () => {
    return fetch(`${url}/products/`, {method: "GET"})
    .then((response) => {
        return response.json();
    })
    .catch((error) => console.log(error))
};

</code>```

It returns data in this format: FE { name: "Red", id: 3, price: 33, image:"some-url"}

Now I need to create another list of objects by merging then by product of an object in first array with id of an object from the second one. The objects in the third array need to contain amount and size from first array as well as name, price and image from the second one. In the end I want to store it in useState().

This is what I came up with, I guess my code stops working arter first for loop:

```<code>const [cart, setCart] = useState([]);

   const CheckAnonymousCart = () => {
        getAllProducts()
        .then((data) => {
            const localCart = showCart();
            var products = [];
            for (let i = 0; i < localCart.lenght; i++) {
                for (let y = 0; y < data.lenght; y++) {
                    if (localCart[i].product === data[y].id) {
                        console.log(localCart[i].product, data[y].id)
                        const item = {
                            name: data[y].name,
                            price: data[y].price,
                            image: data[y].image,
                            amount: localCart[i].amount,
                            size: localCart[i].size,
                        }
                        products.push(item)
                        break;
                    }
                }
            }
            setCart(products);
        })
        .catch((error) => console.log(error))
    };

</code>```

Any thoughts?

答:
The problem could simply be the typo from the for loop conditions, but you can also accomplish this more succinctly using the JS ES6 methods:

const products = localCart.map(item => {
    const match = data.find(x => x.id === item.product);
    return {
        amount,
        size,
        name: match?.name,
        price: match?.price,
        image: match?.image
    }
});
```

Title: Filtering data after fetching in React

Body:
I need to make a list of objects based on combined data from 2 arrays, one comes from a localStorage and the second one from Django backend. First of all objects from localStorage are displayed by showCart() function

export const showCart = () => {
    if (typeof window !== undefined) {
        if (localStorage.getItem("cart")) {
            return JSON.parse(localStorage.getItem("cart"));
        };
    };
};

it returns data in this format: FE: { id: 1, amount: 7, size: "L", product: 1 }. product is the Foreign Key needed to match data from other array.

The second array comes form a backend and it is feched by getAllProducts() function

export const getAllProducts = () => {
    return fetch(`${url}/products/`, {method: "GET"})
    .then((response) => {
        return response.json();
    })
    .catch((error) => console.log(error))
};

It returns data in this format: FE { name: "Red", id: 3, price: 33, image:"some-url"}

Now I need to create another list of objects by merging then by product of an object in first array with id of an object from the second one. The objects in the third array need to contain amount and size from first array as well as name, price and image from the second one. In the end I want to store it in useState().

This is what I came up with, I guess my code stops working arter first for loop:

const [cart, setCart] = useState([]);

   const CheckAnonymousCart = () => {
        getAllProducts()
        .then((data) => {
            const localCart = showCart();
            var products = [];
            for (let i = 0; i < localCart.lenght; i++) {
                for (let y = 0; y < data.lenght; y++) {
                    if (localCart[i].product === data[y].id) {
                        console.log(localCart[i].product, data[y].id)
                        const item = {
                            name: data[y].name,
                            price: data[y].price,
                            image: data[y].image,
                            amount: localCart[i].amount,
                            size: localCart[i].size,
                        }
                        products.push(item)
                        break;
                    }
                }
            }
            setCart(products);
        })
        .catch((error) => console.log(error))
    };

Any thoughts?


问:
Bootstrap Navbar collapsing at custom width with showing icon
Can I customize following breakpoint using bootstrap ?

Code :-

```<code><nav class="navbar navbar-expand-lg" style="background-color:#1B202C;">
  <a class="navbar-brand" href="#"><img style="margin-left: 15px; margin-top: -20px;" class="logo" src="assets/logo.png" alt="logo"></a>
  <button  class="navbar-toggler" data-toggle="collapse"  data-target="#collapsedNavBar"><span class="navbar-toggler-icon"></span></button>
  <div class="fixed-nav">
    <ul class="navbar-nav ">
      <li id="nav-1" class="nav-item ">
        <a class="nav-link" href="#">AAAAA</a>
      </li>
      <li id="nav-2" class="nav-item">
        <a class="nav-link" href="#">BBBBB</a>
      </li>
      <li id="nav-3" class="nav-item">
        <a class="nav-link" href="#">CCCCC</a>
      </li>
    </ul>
  </div>
</nav>
</code>```

But when I override this by adding,

```<code>@media screen and (min-width:633px) and (max-width:1072px) {
   .collapse {
      display: none !important;
    }
}
</code>```

to its style.css. Then navbar collapses at my custom breakpoint (1072px). But still hamburger icon appears when it reaches to -lg (≥992px) . So I need to know is, is there any method to collapse at custom width also appearing the hamburger icon.

Thanks !

答:
If you give lg , sm, xs or xl after navbar-expand class navbar expands automatically by it's custom value. For example if you write navbar-expand-lg value to the nav class it collapses at 992px width or if you give navbar-expand-md it collapses at 768px. You can inspect codes below . I hope it works for you.

button.navbar-toggler {
  background-color: white;
}

span.navbar-toggler-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(41,41,41, 1)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"></script>
    <title>Bootstrap</title>
</head>

<body>
    <nav style="background-color: black;" class="navbar navbar-expand-lg">
        Logo Example
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
            aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <div class="navbar-nav ml-auto">
                AAA
                BBB
                CCC
            </div>
        </div>
    </nav>
</body>

</html></code>```

Body:
Can I customize following breakpoint using bootstrap ?

Code :-

  <button  class="navbar-toggler" data-toggle="collapse"  data-target="#collapsedNavBar"></button>

        AAAAA

        BBBBB

        CCCCC

But when I override this by adding,

@media screen and (min-width:633px) and (max-width:1072px) {
   .collapse {
      display: none !important;
    }
}

to its style.css. Then navbar collapses at my custom breakpoint (1072px). But still hamburger icon appears when it reaches to -lg (≥992px) . So I need to know is, is there any method to collapse at custom width also appearing the hamburger icon.

Thanks !

Body:
If you give lg , sm, xs or xl after navbar-expand class navbar expands automatically by it's custom value. For example if you write navbar-expand-lg value to the nav class it collapses at 992px width or if you give navbar-expand-md it collapses at 768px. You can inspect codes below . I hope it works for you.

button.navbar-toggler {
  background-color: white;
}

span.navbar-toggler-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(41,41,41, 1)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"></script>
    <title>Bootstrap</title>
</head>

<body>
    <nav style="background-color: black;" class="navbar navbar-expand-lg">
        <a class="navbar-brand" href="#">Logo Example</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
            aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <div class="navbar-nav ml-auto">
                <a class="nav-link" href="#">AAA</a>
                <a class="nav-link" href="#">BBB</a>
                <a class="nav-link" href="#">CCC</a>
            </div>
        </div>
    </nav>
</body>

</html>


问:
Flutter : Assets Audio Player
I have problem with assest audio player package when I try to play two songs inside one page
both are playing !
The way I want when I press first button,first song play and when I press second button the first song stop and the second song start playing .

I used this code but it doesn't work

HomePage

```<code>import 'package:flutter/material.dart';
import 'package:mp3player/playpausebutton.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mp3 Player'),
      ),
      body: Container(
        color: Colors.white,
        child: Column(
          children: [
            PlayPauseButton(
              mp3name: 'song1',
            ),
            PlayPauseButton(
              mp3name: 'song2',
            )
          ],
        ),
      ),
    );
  }
}

</code>```

PlayPauseButton

```<code>class PlayPauseButton extends StatefulWidget {
  PlayPauseButton({this.mp3name});
  final String mp3name;
  @override
  _PlayPauseButtonState createState() => _PlayPauseButtonState();
}

class _PlayPauseButtonState extends State<PlayPauseButton> {
  final assetsAudioPlayer = AssetsAudioPlayer();
  bool ispresed = false;
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    assetsAudioPlayer.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      child: Icon(ispresed ? Icons.pause : Icons.play_arrow),
      onPressed: () {
        assetsAudioPlayer.open(Audio("assets/audios/${widget.mp3name}.mp3"));
        setState(() {
          if (ispresed == false) {
            assetsAudioPlayer.play();
            ispresed = true;
          } else if (ispresed == false) {
            assetsAudioPlayer.pause();
            ispresed = false;
          }
        });
      },
    );
  }
}
</code>```

I used this package for playing audio

https://pub.dev/packages/assets_audio_player

and also is there any way to toggle button Icon when player is finish ?

答:
you can check if the player is done playing by adding listener to it.

```<code>assetsAudioPlayer.playlistAudioFinished.listen((event){if(event) {//carry out another action you want }  });
</code>```

the callback response is a bool type, return false when the audio start and return true when it finished

Title: Flutter : Assets Audio Player

Body:
I have problem with assest audio player package when I try to play two songs inside one page
both are playing !
The way I want when I press first button,first song play and when I press second button the first song stop and the second song start playing .

I used this code but it doesn't work

HomePage

import 'package:flutter/material.dart';
import 'package:mp3player/playpausebutton.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mp3 Player'),
      ),
      body: Container(
        color: Colors.white,
        child: Column(
          children: [
            PlayPauseButton(
              mp3name: 'song1',
            ),
            PlayPauseButton(
              mp3name: 'song2',
            )
          ],
        ),
      ),
    );
  }
}

PlayPauseButton

class PlayPauseButton extends StatefulWidget {
  PlayPauseButton({this.mp3name});
  final String mp3name;
  @override
  _PlayPauseButtonState createState() => _PlayPauseButtonState();
}

class _PlayPauseButtonState extends State<PlayPauseButton> {
  final assetsAudioPlayer = AssetsAudioPlayer();
  bool ispresed = false;
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    assetsAudioPlayer.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      child: Icon(ispresed ? Icons.pause : Icons.play_arrow),
      onPressed: () {
        assetsAudioPlayer.open(Audio("assets/audios/${widget.mp3name}.mp3"));
        setState(() {
          if (ispresed == false) {
            assetsAudioPlayer.play();
            ispresed = true;
          } else if (ispresed == false) {
            assetsAudioPlayer.pause();
            ispresed = false;
          }
        });
      },
    );
  }
}

I used this package for playing audio

https://pub.dev/packages/assets_audio_player

and also is there any way to toggle button Icon when player is finish ?

Body:
you can check if the player is done playing by adding listener to it.

assetsAudioPlayer.playlistAudioFinished.listen((event){if(event) {//carry out another action you want }  });

the callback response is a bool type, return false when the audio start and return true when it finished


问:
AWS Step function - choice step - TimestampEquals matching with multiple input variables
I have been trying to create a step function with a choice step that acts as a rule engine. I would like to compare a date variable (from the stale input JSON) to another date variable that I generate with a lambda function.

AWS documentation does not go into details about the Timestamp comparator functions, but I assumed that it can handle two input variables. Here is the relevant part of the code:

```<code>{
  "Variable": "$.staleInputVariable",
  "TimestampEquals": "$.generatedTimestampUsingLambda"
}
</code>```

Here is the error that I am getting when trying to update(!!!) the stepFunction. I would like to highlight the fact that I don't even get to invoking the stepFunction as it fails while updating the function.

```<code>Resource handler returned message: "Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: String does not match RFC3339 timestamp at ..... (Service: AWSStepFunctions; Status Code: 400; Error Code: InvalidDefinition; Request ID: 97df9775-7d2d-4dd2-929b-470c8s741eaf; Proxy: null)" (RequestToken: 030aa97d-35a5-a6a5-0ac5-5698a8662bc2, HandlerErrorCode: InvalidRequest)
</code>```

The stepfunction updates without the Timestamp matching, therefore, I suspect this bit of code.. Any guess?

EDIT (08.Jun.2021):

A comparison – Two fields that specify an input variable to compare,
the type of comparison, and the value to compare the variable to.
Choice Rules support comparison between two variables. Within a Choice
Rule, the value of Variable can be compared with another value from
the state input by appending Path to name of supported comparison
operators.
Source: AWS docs

It clearly states that two variables can be compared, but to no avail. Still trying :)

答:
Looks like you indeed found a way around your initial challenge from the thread linked below.

Using an amazon step function, how do I write a choice operator that references current time?

However, I thought you wanted to compare $.staleInputVariable to the current timestamp and I wince to think you had to configure a lambda function (and test it!) to do only that.

If so, you could have achieved that simply by using the Context Object or $$.:

```<code>{
  "Variable": "$$.State.EnteredTime",
  "TimestampEqualsPath": "$.staleInputVariable"
}
</code>```

Body:
I have been trying to create a step function with a choice step that acts as a rule engine. I would like to compare a date variable (from the stale input JSON) to another date variable that I generate with a lambda function.

AWS documentation does not go into details about the Timestamp comparator functions, but I assumed that it can handle two input variables. Here is the relevant part of the code:

{
  "Variable": "$.staleInputVariable",
  "TimestampEquals": "$.generatedTimestampUsingLambda"
}

Here is the error that I am getting when trying to update(!!!) the stepFunction. I would like to highlight the fact that I don't even get to invoking the stepFunction as it fails while updating the function.

Resource handler returned message: "Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: String does not match RFC3339 timestamp at ..... (Service: AWSStepFunctions; Status Code: 400; Error Code: InvalidDefinition; Request ID: 97df9775-7d2d-4dd2-929b-470c8s741eaf; Proxy: null)" (RequestToken: 030aa97d-35a5-a6a5-0ac5-5698a8662bc2, HandlerErrorCode: InvalidRequest)

The stepfunction updates without the Timestamp matching, therefore, I suspect this bit of code.. Any guess?

EDIT (08.Jun.2021):

A comparison – Two fields that specify an input variable to compare,
the type of comparison, and the value to compare the variable to.
Choice Rules support comparison between two variables. Within a Choice
Rule, the value of Variable can be compared with another value from
the state input by appending Path to name of supported comparison
operators.
Source: AWS docs

It clearly states that two variables can be compared, but to no avail. Still trying :)

Body:
Looks like you indeed found a way around your initial challenge from the thread linked below.

Using an amazon step function, how do I write a choice operator that references current time?

However, I thought you wanted to compare $.staleInputVariable to the current timestamp and I wince to think you had to configure a lambda function (and test it!) to do only that.

If so, you could have achieved that simply by using the Context Object or $$.:

{
  "Variable": "$$.State.EnteredTime",
  "TimestampEqualsPath": "$.staleInputVariable"
}


问:
how to find ssl.conf file in apache
I am trying to install self signed ssl on IP address. I have apache in centos7. I have mod_ssl installed. I have been able to create self signed certificate with openssl req. Now I need to add this certificate to virtual hosts. I found two different files in tutorials for this purpose.
etc/apache2/sites-available/default-ssl.conf and second option is etc/httpd/conf.d/ssl.conf.
But I could find apache2 folder in etc but not sites-availabe and no httpd in etc. Where do I find the relevant file to edit virtual hosts?
Thank you.</p>

答: Config files for Apache under Centos should be at /etc/httpd/ instead of /etc/apache/</p>

Title: how to find ssl.conf file in apache


问:
Validate Json Schema
I'm getting an error when using json-schema-validator API v4.
I try to do :

```<code>final JsonValidator validator = new JsonValidator(JsonLoader.fromPath("schema.json"));
ValidationReport report = validator.validate(data);
</code>```

but every time I get an error : # [schema]: unknown keyword contacts

```<code>schema.json :
{
    "contacts": {
        "description": "The list of contacts",
        "type": "array",
        "optional": true,
        "items": {
            "description": "A contact",
            "type": "object",
            "properties": {
                "givenName": {
                    "description": "Person's first name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                },
                "familyName": {
                    "description": "A person's last name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                }
            }
        }
    }
}
</code>```

Regards

答:
Use AVJ. Instead of having your data validation and sanitization logic written as lengthy code, you can declare the requirements to your data with concise, easy to read and cross-platform JSON Schema or JSON Type Definition specifications and validate the data as soon as it arrives to your application.

// validationSchema.js

import Ajv from "ajv";
import addFormats from "ajv-formats";
import ajvErrors from "ajv-errors";

const schemas = {
  newUser: {
    {
      type: "object",
      properties: {
        lastName: {
          type: "string",
          minLength: 1,
          maxLength: 255
        },
        firstName: {
          type: "string",
          minLength: 1,
          maxLength: 255
        },
        description: {
          type: "string"
        },
        birthday: {
          type: "string",
          format: "date-time"
        },
        status: {
          type: "string",
          enum: ["ACTIVE", "DELETED"]
        },
      },
      required: ["name"]
    }
  }
};

const ajv = new Ajv({ allErrors: true });

addFormats(ajv);
ajvErrors(ajv /*, {singleError: true} */);

const mapErrors = (errorsEntry = []) => {
  const errors = errorsEntry.reduce(
    (
      acc,
      { instancePath = "", message = "", params: { missingProperty = "" } = {} }
    ) => {
      const key = (instancePath || missingProperty).replace("/", "");

      if (!acc[key]) {
        acc[key] = [];
      }

      acc[key].push(`${key} ${message}`);

      return acc;
    },
    []
  );

  return errors;
};

const validate = (schemaName, data) => {
  const v = ajv.compile(schemas[schemaName]);
  let valid = false,
    errors = [];

  valid = v(data);
  if (!valid) {
    errors = mapErrors(v.errors);
  }

  return { valid, errors };
};

export default { validate };```
</div>
</div>
</p>
<p>You can validate it like this:</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 validationSchema from "your_path/validationSchema.js"

const user = {
  firstName: "",
  lastName: "",
  ....
};

const { valid, errors = [] } = validationSchema.validate("newUser", user);

if(valid){
  console.log("Data is valid!");
} else {
  console.log("Data is not valid!");
  console.log(errors);
}</code>```

Title: Validate Json Schema

Body:
I'm getting an error when using json-schema-validator API v4.
I try to do :

final JsonValidator validator = new JsonValidator(JsonLoader.fromPath("schema.json"));
ValidationReport report = validator.validate(data);

but every time I get an error : # [schema]: unknown keyword contacts

schema.json :
{
    "contacts": {
        "description": "The list of contacts",
        "type": "array",
        "optional": true,
        "items": {
            "description": "A contact",
            "type": "object",
            "properties": {
                "givenName": {
                    "description": "Person's first name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                },
                "familyName": {
                    "description": "A person's last name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                }
            }
        }
    }
}

Regards

Body:
Use AVJ. Instead of having your data validation and sanitization logic written as lengthy code, you can declare the requirements to your data with concise, easy to read and cross-platform JSON Schema or JSON Type Definition specifications and validate the data as soon as it arrives to your application.

// validationSchema.js

import Ajv from "ajv";
import addFormats from "ajv-formats";
import ajvErrors from "ajv-errors";

const schemas = {
  newUser: {
    {
      type: "object",
      properties: {
        lastName: {
          type: "string",
          minLength: 1,
          maxLength: 255
        },
        firstName: {
          type: "string",
          minLength: 1,
          maxLength: 255
        },
        description: {
          type: "string"
        },
        birthday: {
          type: "string",
          format: "date-time"
        },
        status: {
          type: "string",
          enum: ["ACTIVE", "DELETED"]
        },
      },
      required: ["name"]
    }
  }
};

const ajv = new Ajv({ allErrors: true });

addFormats(ajv);
ajvErrors(ajv /*, {singleError: true} */);

const mapErrors = (errorsEntry = []) => {
  const errors = errorsEntry.reduce(
    (
      acc,
      { instancePath = "", message = "", params: { missingProperty = "" } = {} }
    ) => {
      const key = (instancePath || missingProperty).replace("/", "");

      if (!acc[key]) {
        acc[key] = [];
      }

      acc[key].push(`${key} ${message}`);

      return acc;
    },
    []
  );

  return errors;
};

const validate = (schemaName, data) => {
  const v = ajv.compile(schemas[schemaName]);
  let valid = false,
    errors = [];

  valid = v(data);
  if (!valid) {
    errors = mapErrors(v.errors);
  }

  return { valid, errors };
};

export default { validate };

You can validate it like this:

import validationSchema from "your_path/validationSchema.js"

const user = {
  firstName: "",
  lastName: "",
  ....
};

const { valid, errors = [] } = validationSchema.validate("newUser", user);

if(valid){
  console.log("Data is valid!");
} else {
  console.log("Data is not valid!");
  console.log(errors);
}


问:
How to mock *exec.Cmd / exec.Command()?
I need to mock exec.Command().

I can mock it using:

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    return nil
}
```
<p>However, this won't work in the actual code, as it complains about the nil pointer, since the returning <code>exec.Cmd</code> calls <code>Run()</code>.</p>
<p>I tried to mock it like:</p>
<pre class="lang-golang prettyprint-override"><code>type mock exec.Cmd

func (m *mock) Run() error {
    return nil
}

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    m := mock{}

    return &m
}
</code>```

But it complains: cannot use &m (value of type *mock) as *exec.Cmd value in return statementcompilerIncompatibleAssign.

Is there any way to approach this? Is there a better way to mock exec.Command()?

The mocked function works if I return a "mock" command, although I'd prefer to control the Run() function too:

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    return exec.Command("echo")
}
```

答:
How to mock *exec.Cmd / exec.Command()?

You cannot. Come up with a non mock-based testing strategy.

Title: How to mock *exec.Cmd / exec.Command()?

Body:
I need to mock exec.Command().

I can mock it using:

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    return nil
}

However, this won't work in the actual code, as it complains about the nil pointer, since the returning exec.Cmd calls Run().

I tried to mock it like:

type mock exec.Cmd

func (m *mock) Run() error {
    return nil
}

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    m := mock{}

    return &m
}

But it complains: cannot use &m (value of type *mock) as *exec.Cmd value in return statementcompilerIncompatibleAssign.

Is there any way to approach this? Is there a better way to mock exec.Command()?

The mocked function works if I return a "mock" command, although I'd prefer to control the Run() function too:

var rName string
var rArgs []string

mockExecCommand := func(name string, arg ...string) *exec.Cmd {
    rName = name
    rArgs = arg

    return exec.Command("echo")
}


问:
Linking to different areas on a page
This may seem like a stupid question, but:

So what i would like to do is set up a menu section so that when the user clicked on the title of the section it would send them to that particular spot on the page with out having to scoll down. I am not entirely sure how this would work or how complicated it is to achieve.

So bacially i would have

Menu

item one (be a link)

item two (be a link)

etc (be a link)

then further down the page

item one (when item one in menu is clicked page comes to here)

"details about it here"

item two (when item two in menu is clicked page comes to here)

"details here"

How exactly would i go about doing this?

Any help or suggestions are greatly appreciated. Thanks.

答:
If you want a smoother scroll than that of an anchor you can also use a jquery plugin/script.
For example https://github.com/kswedberg/jquery-smooth-scroll </p>

Title: Linking to different areas on a page