问:
I want to add active class to menu and submenu by using PHP. I have added it ib submenu but on main menu I am having problems
```<code><li class="nav-item  <?php if($page=='userforms'){echo 'active';}?>

    <a href="javascript:;" class="nav-link nav-toggle" style="">
        <i class="icon-layers"></i>
        <span class="title">Userforms</span>
        <span class="arrow open"></span>
    </a>

    <ul class="sub-menu" style="display: block;">
        <li class="nav-item <?php if($page=='newproduct'){echo 'active';}?>">
            <a href="add.php" class="nav-link ">
                <span class="title">New Product</span>
            </a>
        </li>

        <li class="nav-item  <?php if($page=='stockin'){echo 'active';}?>">
            <a href="StockIn.php" class="nav-link ">
                <span class="title">Stock In</span>
            </a>
        </li>

        <li class="nav-item  <?php if($page=='stockout'){echo 'active';}?>">
            <a href="StockOut.php" class="nav-link ">
                <span class="title">Stock Out</span>
            </a>
        </li>

    </ul>

</li>

<?php $page = 'stockin'; include('includes/header.php');
include('includes/navbar.php');
?>
</code>```

I want to add active class to menu and submenu by using PHP. I have added it ib submenu but on main menu I am having problems. I want both menu to be selected Main menu and Sub Menu.

I want both menu to be selected

答:
It's not possible only by CSS. You should use some javascript codes.</p>

```<code>$('.child').on('click', function(){
   $(this).closest('.parent').toggleClass('active');
});
</code>```

Body:
<li class="nav-item  <?php if($page=='userforms'){echo 'active';}?>

        Userforms

        <li class="nav-item <?php if($page=='newproduct'){echo 'active';}?>">

                New Product

        <li class="nav-item  <?php if($page=='stockin'){echo 'active';}?>">

                Stock In

        <li class="nav-item  <?php if($page=='stockout'){echo 'active';}?>">

                Stock Out

<?php $page = 'stockin'; include('includes/header.php');
include('includes/navbar.php');
?>

I want to add active class to menu and submenu by using PHP. I have added it ib submenu but on main menu I am having problems. I want both menu to be selected Main menu and Sub Menu.

I want both menu to be selected

Body:
It's not possible only by CSS. You should use some javascript codes.

$('.child').on('click', function(){
   $(this).closest('.parent').toggleClass('active');
});


来源: stackexchange

问:
How to put\save files into your application directory? (adobe air)
How to put\save files into your application directory? (adobe air) (code example, please)</p>

答:
It's not recomended but it is possible. Construct your File reference like this:</p>

```<code>var pathToFile:String = File.applicationDirectory.resolvePath('file.txt').nativePath;
var someFile:File = new File(pathToFile);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's not recomended but it is possible. Construct your File reference like this:

var pathToFile:String = File.applicationDirectory.resolvePath('file.txt').nativePath;
var someFile:File = new File(pathToFile);

ContentLicense: CC BY-SA 3.0


问:
Translate Array with Array
I search a way to translate a key from one array with other array.

tmp_title=$3
title=$(echo ${tmp_title,,} | sed -e 's/\s/-/g')
tags=(computer media state society)
de=(computer medien staat gesellschaft)
fr=(ordinateur journalisme politique société)
ru=(Компьютер СМИ штат общество)

      file="./content/de/blog/$(date +"%Y")/$(date +"%m")/$title.md"
      if test -n "$2"; then

        # check tag is in tags array
        if [[ ${tags[*]} =~ $2 ]]; then

          # check the folder structure is right
          if [[ -d ./content/de/blog/$(date +"%Y")/$(date +"%m") ]]; then

            # create the content and fill up the file
            echo "---" >> "$file"
            echo "title: \"$3\"" >> "$file"
            echo "date: $(date +\"%Y-%m-%d\")" >> "$file"
            echo "draft: false" >> "$file"
            echo "tags: \"$2\"" >> "$file"
            echo "shorttext:" >> "$file"
            echo "cover: \"$2\"" >> "$file"
            echo "lang: $1" >> "$file"
            echo "---" >> "$file"
          fi
        else
          echo "Enter a valid tag name ..."
        fi
      fi
```

I search a way to translate "tags: \"$2\"" >> "$file" in the language array value. When I append society to the script then should be tags: "gesellschaft".

Thank you for help.

Silvio

答:
I have it realize other. I ask for categories and translate then to the $lang value.

#!/usr/bin/env bash

# variables through user input
lang=$1
cover=$2
tmp_title=$3

# variables which we use in script
# create a title with small letters and remove whitespace
title=$(echo ${tmp_title,,} | sed -e 's/\s/-/g')

# categories
categories=(computer media repression society)

# date variables
date=$(date +"%Y-%m-%d")
year=$(date +"%Y")
month=$(date +"%m")

# content variables
content_dir="./content/$lang/blog/$year/$month"
file="$content_dir/$title.md"

# function
function create_file()
{
  {
    echo "---"
    echo "title: \"$tmp_title\""
    echo "date: $date"
    echo "draft: false"
    echo "tags: \"$tag\""
    echo "shorttext:"
    echo "cover: \"$cover\""
    echo "lang: $lang"
    echo "---"
  } >> "$file"
}

case $1 in
  de)
    if test -n "$lang"; then
      # check tag is in array
      if [[ ${categories[*]} =~ $cover ]]; then

        # translation tag > categories
        if [[ $cover =~ "computer" ]]; then
          tag="Computer"

        elif [[ $cover =~ "media" ]]; then
          tag="Medien"

        elif [[ $cover =~ "repression" ]]; then
          tag="Staat"

        elif [[ $cover =~ "society" ]]; then
          tag="Gesellschaft"
        fi

        # check the folder structure is right
        if [[ -d "$content_dir" ]]; then

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        else

          # create the folder of content
          mkdir -p "$content_dir"

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        fi
      else
        echo "Enter a valid tag name ..."
      fi
    fi
  ;;

  en)
    if test -n "$lang"; then
      # check tag is in array
      if [[ ${categories[*]} =~ $cover ]]; then

        # translation tag > categories
        if [[ $cover =~ "computer" ]]; then
          tag="Computer"

        elif [[ $cover =~ "media" ]]; then
          tag="Media"

        elif [[ $cover =~ "repression" ]]; then
          tag="State"

        elif [[ $cover =~ "society" ]]; then
          tag="Society"
        fi

        # check the folder structure is right
        if [[ -d "$content_dir" ]]; then

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        else

          # create the folder of content
          mkdir -p "$content_dir"

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        fi
      else
        echo "Enter a valid tag name ..."
      fi
    fi
  ;;

  info)
    echo "To work with this script you need append the follow stuff"
    echo "./bin/new.sh lang cover title"
    echo "./bin/news.sh en society 'This is a title'"
    echo "cover: computer, media, repression, society"
  ;;
esac
```

Silvio

ContentLicense: CC BY-SA 4.0

Title: Translate Array with Array

Body:
I search a way to translate a key from one array with other array.

tmp_title=$3
title=$(echo ${tmp_title,,} | sed -e 's/\s/-/g')
tags=(computer media state society)
de=(computer medien staat gesellschaft)
fr=(ordinateur journalisme politique société)
ru=(Компьютер СМИ штат общество)

      file="./content/de/blog/$(date +"%Y")/$(date +"%m")/$title.md"
      if test -n "$2"; then

        # check tag is in tags array
        if [[ ${tags[*]} =~ $2 ]]; then

          # check the folder structure is right
          if [[ -d ./content/de/blog/$(date +"%Y")/$(date +"%m") ]]; then

            # create the content and fill up the file
            echo "---" >> "$file"
            echo "title: \"$3\"" >> "$file"
            echo "date: $(date +\"%Y-%m-%d\")" >> "$file"
            echo "draft: false" >> "$file"
            echo "tags: \"$2\"" >> "$file"
            echo "shorttext:" >> "$file"
            echo "cover: \"$2\"" >> "$file"
            echo "lang: $1" >> "$file"
            echo "---" >> "$file"
          fi
        else
          echo "Enter a valid tag name ..."
        fi
      fi

I search a way to translate "tags: \"$2\"" >> "$file" in the language array value. When I append society to the script then should be tags: "gesellschaft".

Thank you for help.

Silvio

Body:
I have it realize other. I ask for categories and translate then to the $lang value.

#!/usr/bin/env bash

# variables through user input
lang=$1
cover=$2
tmp_title=$3

# variables which we use in script
# create a title with small letters and remove whitespace
title=$(echo ${tmp_title,,} | sed -e 's/\s/-/g')

# categories
categories=(computer media repression society)

# date variables
date=$(date +"%Y-%m-%d")
year=$(date +"%Y")
month=$(date +"%m")

# content variables
content_dir="./content/$lang/blog/$year/$month"
file="$content_dir/$title.md"

# function
function create_file()
{
  {
    echo "---"
    echo "title: \"$tmp_title\""
    echo "date: $date"
    echo "draft: false"
    echo "tags: \"$tag\""
    echo "shorttext:"
    echo "cover: \"$cover\""
    echo "lang: $lang"
    echo "---"
  } >> "$file"
}

case $1 in
  de)
    if test -n "$lang"; then
      # check tag is in array
      if [[ ${categories[*]} =~ $cover ]]; then

        # translation tag > categories
        if [[ $cover =~ "computer" ]]; then
          tag="Computer"

        elif [[ $cover =~ "media" ]]; then
          tag="Medien"

        elif [[ $cover =~ "repression" ]]; then
          tag="Staat"

        elif [[ $cover =~ "society" ]]; then
          tag="Gesellschaft"
        fi

        # check the folder structure is right
        if [[ -d "$content_dir" ]]; then

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        else

          # create the folder of content
          mkdir -p "$content_dir"

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        fi
      else
        echo "Enter a valid tag name ..."
      fi
    fi
  ;;

  en)
    if test -n "$lang"; then
      # check tag is in array
      if [[ ${categories[*]} =~ $cover ]]; then

        # translation tag > categories
        if [[ $cover =~ "computer" ]]; then
          tag="Computer"

        elif [[ $cover =~ "media" ]]; then
          tag="Media"

        elif [[ $cover =~ "repression" ]]; then
          tag="State"

        elif [[ $cover =~ "society" ]]; then
          tag="Society"
        fi

        # check the folder structure is right
        if [[ -d "$content_dir" ]]; then

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        else

          # create the folder of content
          mkdir -p "$content_dir"

          # create the content and fill up the file
          create_file

          if [[ -f "$file" ]]; then
            subl "$file"
          fi

        fi
      else
        echo "Enter a valid tag name ..."
      fi
    fi
  ;;

  info)
    echo "To work with this script you need append the follow stuff"
    echo "./bin/new.sh lang cover title"
    echo "./bin/news.sh en society 'This is a title'"
    echo "cover: computer, media, repression, society"
  ;;
esac

Silvio


问:
Bound Method - Python
```<code>class Iloilo():
     def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

Iloilo = Iloilo()
Palawan = Palawan()

print(Iloilo.Population)
print(Palawan.Population)
</code>```

I am trying to print its value but I'm getting an error saying:
bound method

My question is, how can I compare both method results?

答:
Use below code</p>

```<code>class Iloilo():
    def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

a= Iloilo()
b=Palawan()
print(a.Population(),b.Population())
</code>```

Title: Bound Method - Python

Body:
class Iloilo():
     def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

Iloilo = Iloilo()
Palawan = Palawan()

print(Iloilo.Population)
print(Palawan.Population)

I am trying to print its value but I'm getting an error saying:
bound method

My question is, how can I compare both method results?

Body:
Use below code

class Iloilo():
    def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

a= Iloilo()
b=Palawan()
print(a.Population(),b.Population())


问:
Generating boolean dataframe based on contents in series and dataframe
I have:

```<code> df = pd.DataFrame(
        [
            [22, 33, 44],
            [55, 11, 22],
            [33, 55, 11],
        ],
        index=["abc", "def", "ghi"],
        columns=list("abc")
    ) # size(3,3)
</code>```

and:

```<code>unique = pd.Series([11, 22, 33, 44, 55]) # size(1,5)
</code>```

then I create a new df based on unique and df, so that:

```<code>df_new = pd.DataFrame(index=unique, columns=df.columns) # size(5,3)
</code>```

From this newly created df, I'd like to create a new boolean df based on unique and df, so that the end result is:

```<code> df_new = pd.DataFrame(
        [
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 0],
            [0, 0, 1],
            [1, 1, 0],
        ],
        index=unique,
        columns=df.columns
    )
</code>```

This new df is either true or false depending on whether the value is present in the original dataframe or not. For example, the first column has three values: [22, 55, 33]. In a df with dimensions (5,3), this first column would be: [0, 1, 1, 0, 1] i.e. [0, 22, 33, 0 , 55]

I tried filter2 = unique.isin(df) but this doesn't work, also notnull. I tried applying a filter but the dimensions returned were incorrect. How can I do this?

答:
Use DataFrame.stack with DataFrame.reset_index, DataFrame.pivot, then check if not missing values by DataFrame.notna, cast to integers for True->1 and False->0 mapping and last remove index and columns names by DataFrame.rename_axis:

```<code>df_new = (df.stack()
            .reset_index(name='v')
            .pivot('v','level_1','level_0')
            .notna()
            .astype(int)
            .rename_axis(index=None, columns=None))
print (df_new)
    a  b  c
11  0  1  1
22  1  0  1
33  1  1  0
44  0  0  1
55  1  1  0
</code>```

Helper Series is not necessary, but if there is more values or is necessary change order by helper Series use add DataFrame.reindex:

```<code>#added 66
unique = pd.Series([11, 22, 33, 44, 55,66])

df_new = (df.stack()
            .reset_index(name='v')
            .pivot('v','level_1','level_0')
            .reindex(unique)
            .notna()
            .astype(int)
            .rename_axis(index=None, columns=None))
print (df_new)
    a  b  c
11  0  1  1
22  1  0  1
33  1  1  0
44  0  0  1
55  1  1  0
66  0  0  0
</code>```

Body:
I have:

 df = pd.DataFrame(
        [
            [22, 33, 44],
            [55, 11, 22],
            [33, 55, 11],
        ],
        index=["abc", "def", "ghi"],
        columns=list("abc")
    ) # size(3,3)

and:

unique = pd.Series([11, 22, 33, 44, 55]) # size(1,5)

then I create a new df based on unique and df, so that:

df_new = pd.DataFrame(index=unique, columns=df.columns) # size(5,3)

From this newly created df, I'd like to create a new boolean df based on unique and df, so that the end result is:

 df_new = pd.DataFrame(
        [
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 0],
            [0, 0, 1],
            [1, 1, 0],
        ],
        index=unique,
        columns=df.columns
    )

This new df is either true or false depending on whether the value is present in the original dataframe or not. For example, the first column has three values: [22, 55, 33]. In a df with dimensions (5,3), this first column would be: [0, 1, 1, 0, 1] i.e. [0, 22, 33, 0 , 55]

I tried filter2 = unique.isin(df) but this doesn't work, also notnull. I tried applying a filter but the dimensions returned were incorrect. How can I do this?

Body:
Use DataFrame.stack with DataFrame.reset_index, DataFrame.pivot, then check if not missing values by DataFrame.notna, cast to integers for True->1 and False->0 mapping and last remove index and columns names by DataFrame.rename_axis:

df_new = (df.stack()
            .reset_index(name='v')
            .pivot('v','level_1','level_0')
            .notna()
            .astype(int)
            .rename_axis(index=None, columns=None))
print (df_new)
    a  b  c
11  0  1  1
22  1  0  1
33  1  1  0
44  0  0  1
55  1  1  0

Helper Series is not necessary, but if there is more values or is necessary change order by helper Series use add DataFrame.reindex:

#added 66
unique = pd.Series([11, 22, 33, 44, 55,66])

df_new = (df.stack()
            .reset_index(name='v')
            .pivot('v','level_1','level_0')
            .reindex(unique)
            .notna()
            .astype(int)
            .rename_axis(index=None, columns=None))
print (df_new)
    a  b  c
11  0  1  1
22  1  0  1
33  1  1  0
44  0  0  1
55  1  1  0
66  0  0  0


问:
ReactJS - FCM not working in safari browser
I am trying to implement FCM push notification in my ReactJS application.
It is working in chrome and firefox browser perfectly but facing in an issue in safari browser.

FirebaseError: Messaging: This browser doesn't support the API's required to use the firebase SDK. (messaging/unsupported-browser).

I also gone through the documentation of firebase also found that it only supports on only 3 browsers.

Chrome

Firefox

Safari

Is there any method to supports in safari browser as well.

答:
I was getting error in Safari because FCM is not supported.

Firebase Provides an inbuilt method to check weather FCM supported or not.

```<code>    if(firebase.messaging.isSupported()) {
        messaging = initializedFirebaseApp.messaging();
        messaging.usePublicVapidKey(
          "Key"
        );
    }

</code>```

Body:
I was getting error in Safari because FCM is not supported.

Firebase Provides an inbuilt method to check weather FCM supported or not.

    if(firebase.messaging.isSupported()) {
        messaging = initializedFirebaseApp.messaging();
        messaging.usePublicVapidKey(
          "Key"
        );
    }


答:
You could just use conditional aggregation:

```<code>select
    definition,
    sum(case
        when dateRecorded >= datefromparts(2020, 1, 1) and dateRecorded < datefromparts(2020, 2, 1)
        then rating
        else 0
    end) Jan,
    sum(case
        when dateRecorded >= datefromparts(2020, 2, 1) and dateRecorded < datefromparts(2020, 3, 1)
        then rating
        else 0
    end) Feb,
    ...
    sum(case
        when dateRecorded >= datefromparts(2020, 12, 1) and dateRecorded < datefromparts(2021, 1, 1)
        then rating
        else 0
    end) Dec
from graphDetails
where dateRecorded >= datefromparts(2020, 1, 1) and dateRecorded < datefromparts(2021, 1, 1)
group by definition
order by definition
</code>```

This syntax is somehow more flexible than the specific PIVOT operator (and also, for what it's worth, it works across different database products).

Note that I modified the filters on dates so it uses half-open intervals, and no date function is applied on column dateRecorded: this should allow the database to take advantage of an index on the date column (and would also smoothly handle the time component of dateCreated, if any).

Title: How can I get values of the Rating column together with their definition for every specific month by using Pivot with Month in MSSQL

Body:
Example :

Data:

GraphDetails
|----------------------------------------------------------|
| Id  GoalId  Definition                Rating  DateCrated |
| -------------------------------------------------------- |
| 1   2       Zero Infra Back Log       100     2020-02-05 |
| 2   2       Happy Customers           95      2020-02-05 |
| 3   2       Complete All Projects     100     2020-02-05 |
| 4   1       Zero Infra Back Log       100     2020-02-05 |
| 5   1       Happy Customers           98      2020-02-05 |
| 6   1       Complete All Projects     100     2020-02-05 |
|----------------------------------------------------------|

Query:

SELECT
 [1] AS Jan,
 [2] AS Feb,
 [3] AS Mar,
 [4] AS Apr,
 [5] AS May,
 [6] AS Jun,
 [7] AS Jul,
 [8] AS Aug,
 [9] AS Sep,
 [10] AS Oct,
 [11] AS Nov,
 [12] AS [Dec]
FROM
(Select Id, MONTH(DateRecorded) as TMonth
  FROM GraphDetails
    WHERE YEAR(DateRecorded) = 2020 AND GoalId = 1
    ) source
PIVOT
( Definition, Rating
    FOR TMonth
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth

I get this error:

Incorrect syntax near ','.

In line with " Definition, Rating "

Result should look like this:

|-------------------------------------------------------------------------------------------------|
| Definition              | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|-------------------------------------------------------------------------------------------------|
| Zero Infra Back Log     | 0   | 100 | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
| Happy Customers         | 0   | 98  | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
| Complete All Projects   | 0   | 100 | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
|-------------------------------------------------------------------------------------------------|

Is this possible?
Any help, please!

Thank you!

*The code above was based on PIVOT with MONTH().

Body:
You could just use conditional aggregation:

select
    definition,
    sum(case
        when dateRecorded >= datefromparts(2020, 1, 1) and dateRecorded < datefromparts(2020, 2, 1)
        then rating
        else 0
    end) Jan,
    sum(case
        when dateRecorded >= datefromparts(2020, 2, 1) and dateRecorded < datefromparts(2020, 3, 1)
        then rating
        else 0
    end) Feb,
    ...
    sum(case
        when dateRecorded >= datefromparts(2020, 12, 1) and dateRecorded < datefromparts(2021, 1, 1)
        then rating
        else 0
    end) Dec
from graphDetails
where dateRecorded >= datefromparts(2020, 1, 1) and dateRecorded < datefromparts(2021, 1, 1)
group by definition
order by definition

This syntax is somehow more flexible than the specific PIVOT operator (and also, for what it's worth, it works across different database products).

Note that I modified the filters on dates so it uses half-open intervals, and no date function is applied on column dateRecorded: this should allow the database to take advantage of an index on the date column (and would also smoothly handle the time component of dateCreated, if any).


问:
data structure for sets of strings
I was wondering if anyone could suggest a data structure for storing strings in two mutually exclusive sets. The operations would include adding and removing a string from a set, moving a string from one set to the other, and returning the number of strings in each set. I'm considering a trie, but I'm not sure about returning the number of strings in each set.

I would like to implement it in C.

答:
GLib has a hash table implementation you could use:
http://developer.gnome.org/glib/2.28/glib-Hash-Tables.html</p>

Title: data structure for sets of strings


问:
Can Flutter for Web show Pdf or Webview?
I try to show pdf documents on flutter web, I am very new to flutter and not sure whether the Webview and Pdf plugin is available on flutter web yet. if yes can you please show me some example links? If not, is there any alternative solution?

Thank you

答:
You can use WebView() widget to show PDF online and it works fine. Here is the Code,

```<code>WebView(
        initialUrl: ('https://docs.google.com/gview?embedded=true&url=${yourPdfPath}'),
        javascriptMode: JavascriptMode.unrestricted,
      )
</code>```

Body:
You can use WebView() widget to show PDF online and it works fine. Here is the Code,

WebView(
        initialUrl: ('https://docs.google.com/gview?embedded=true&url=${yourPdfPath}'),
        javascriptMode: JavascriptMode.unrestricted,
      )


问:
How to replace lines from one file to another file
I have a one file like below and required to grep the lines which are starting with system_props(^system_props).

```<code>JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi
</code>```

I have another file called as file2 which having dummy content like below.

```<code>JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi
</code>```

Now my requirement is to replace the content of cat file1 | grep ^system_props to cat file2 | grep ^system_props)

the expected output of both system_props values should be same and append missing lines from file1

答:
EDIT: Since OP has changed requirement a bit so adding edited solution here.

```<code>awk  '
FNR==NR{
  if(match($0,/^system_props=".*/)){
    a[++count]=substr($0,RSTART+14,RLENGTH-14)
  }
  next
}
match($0,/^system_props="/){
  $0=substr($0,RSTART,RLENGTH) a[++count1]
}
1;
 END{
  if(count!=count1){
    while(++count1<=count){
      print a[count1]
    }
  }
}
' File2 File1
</code>```

Could you please try following. This is going to substitute values from 1 file to another file by string system_props occurrence., means 1st occurrence of string from File2 will be placed in first occurrence of string in File1.

```<code>awk  '
FNR==NR{
  if(match($0,/^system_props=".*/)){
    a[++count]=substr($0,RSTART+14,RLENGTH-14)
  }
  next
}
match($0,/^system_props="/){
  $0=substr($0,RSTART,RLENGTH) a[++count1]
}
1
'   Input_file2  Input_file1
</code>```

For your shown samples output will be as follows.

```<code>JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi
</code>```

Explanation: Adding detailed explanation for above code.

```<code>awk  '                                            ##Starting awk program from here.
FNR==NR{                                          ##Checking condition if FNR==NR which will be TRUE when file2 is being read.
  if(match($0,/^system_props=".*/)){              ##Checking condition if line has system_props=" then do following.
    a[++count]=substr($0,RSTART+14,RLENGTH-14)    ##Creating array a with index variable count(whose value is increasing with 1) and its value is substring of current line with starting point of RSTART and ending point of RLENGTH.
  }
  next                                            ##next will skip all further lines from here.
}
match($0,/^system_props="/){                      ##Checking condition if a line starts from
  $0=substr($0,RSTART,RLENGTH) a[++count1]        ##Assigning substring of current line from RSTART to RLENGTH and putting value of array a which we collected from previous file.
}
1                                                 ##1 will print edited/non-edited lines of Input_file1 here.
'  File2 File1                                    ##Mentioning Input_file names here.
</code>```

Body:
I have a one file like below and required to grep the lines which are starting with system_props(^system_props).

JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi

I have another file called as file2 which having dummy content like below.

JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi

Now my requirement is to replace the content of cat file1 | grep ^system_props to cat file2 | grep ^system_props)

the expected output of both system_props values should be same and append missing lines from file1

Body:
EDIT: Since OP has changed requirement a bit so adding edited solution here.

awk  '
FNR==NR{
  if(match($0,/^system_props=".*/)){
    a[++count]=substr($0,RSTART+14,RLENGTH-14)
  }
  next
}
match($0,/^system_props="/){
  $0=substr($0,RSTART,RLENGTH) a[++count1]
}
1;
 END{
  if(count!=count1){
    while(++count1<=count){
      print a[count1]
    }
  }
}
' File2 File1

Could you please try following. This is going to substitute values from 1 file to another file by string system_props occurrence., means 1st occurrence of string from File2 will be placed in first occurrence of string in File1.

awk  '
FNR==NR{
  if(match($0,/^system_props=".*/)){
    a[++count]=substr($0,RSTART+14,RLENGTH-14)
  }
  next
}
match($0,/^system_props="/){
  $0=substr($0,RSTART,RLENGTH) a[++count1]
}
1
'   Input_file2  Input_file1

For your shown samples output will be as follows.

JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi

Explanation: Adding detailed explanation for above code.

awk  '                                            ##Starting awk program from here.
FNR==NR{                                          ##Checking condition if FNR==NR which will be TRUE when file2 is being read.
  if(match($0,/^system_props=".*/)){              ##Checking condition if line has system_props=" then do following.
    a[++count]=substr($0,RSTART+14,RLENGTH-14)    ##Creating array a with index variable count(whose value is increasing with 1) and its value is substring of current line with starting point of RSTART and ending point of RLENGTH.
  }
  next                                            ##next will skip all further lines from here.
}
match($0,/^system_props="/){                      ##Checking condition if a line starts from
  $0=substr($0,RSTART,RLENGTH) a[++count1]        ##Assigning substring of current line from RSTART to RLENGTH and putting value of array a which we collected from previous file.
}
1                                                 ##1 will print edited/non-edited lines of Input_file1 here.
'  File2 File1                                    ##Mentioning Input_file names here.


问:
How to control SSLContext scope
If I use the following code because I want to, for example, to change the way certificates are validated.

trm = some trust manager

```<code>SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { trm }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
</code>```

Then this sets the SSLContext for all https connections that will be made in the future regardless of what thread. What is the cleanest way to control the scope so that I set it only for those calls I want?

答:
You can set the socket factory on the actual connection object that you want to have use this trust store:

```<code>HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sc.getSocketFactory());
</code>```

Do that instead of invoking setDefaultSSLSocketFactory.

Title: How to control SSLContext scope

Body:
If I use the following code because I want to, for example, to change the way certificates are validated.

trm = some trust manager

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { trm }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

Then this sets the SSLContext for all https connections that will be made in the future regardless of what thread. What is the cleanest way to control the scope so that I set it only for those calls I want?

Body:
You can set the socket factory on the actual connection object that you want to have use this trust store:

HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sc.getSocketFactory());

Do that instead of invoking setDefaultSSLSocketFactory.


问:
arcore the displaying image is perpendicular to the plane
This is what I want ->

Here some importants part of code,  I want to display the author of the book on top of the book but as you see displaying image perpendicular to the book. Help me,  this is what I got ->

```<code>  private void OnUpdateFrame(FrameTime frameTime){
                    Frame frame=arFragment.getArSceneView().getArFrame();

                    Collection<AugmentedImage> augmentedImages=frame.getUpdatedTrackables(AugmentedImage.class);
                    for(AugmentedImage augmentedImage: augmentedImages){

                        if(augmentedImage.getTrackingState()== TrackingState.TRACKING ){

                            if(augmentedImage.getName().equals("arimage") && shouldAddModel){
                                placeObject(arFragment,
                                        augmentedImage.createAnchor(augmentedImage.getCenterPose()),
                                        Uri.parse("author.jpg"));
                                shouldAddModel=false;
                            }
                    }}
                }

          private void placeObject(ArFragment fragment, Anchor anchor, Uri model){
                ViewRenderable.builder().
                        setView(this,R.layout.lol)
                        .setVerticalAlignment(ViewRenderable.VerticalAlignment.BOTTOM)
                        .build()
                        .thenAccept(viewRenderable -> addNodeToScene(fragment,anchor,viewRenderable))
                        .exceptionally(throwable -> {
                        AlertDialog.Builder builder=new AlertDialog.Builder(this);
                        builder.setMessage(throwable.getMessage())
                                .setTitle("Error!");
                        AlertDialog dialog=builder.create();
                        dialog.show();
                        return null;
                        });
            }

      private void addNodeToScene(ArFragment fragment, Anchor anchor, ViewRenderable viewRenderable) {

            AnchorNode anchorNode=new AnchorNode(anchor);

            anchorNode.setLocalScale(new Vector3(0.5f, 0.5f, 0.5f));

            TransformableNode node=new TransformableNode(fragment.getTransformationSystem());

            node.setRenderable(viewRenderable);

            node.setParent(anchorNode);
            fragment.getArSceneView().getScene().addChild(anchorNode);
            node.select();

        }
</code>```

答:
A simple local rotation of the node should do the trick.Once you have set the parent of the node as this.

```<code> node.setParent(anchorNode);
 node.setLocalRotation(Quaternion.axisAngle(new Vector3(0, 0, 1f), 180));
 fragment.getArSceneView().getScene().addChild(anchorNode);
</code>```

Play around with the values of the Quaternion. You should get it.

Body:
This is what I want ->

Here some importants part of code,  I want to display the author of the book on top of the book but as you see displaying image perpendicular to the book. Help me,  this is what I got ->

  private void OnUpdateFrame(FrameTime frameTime){
                    Frame frame=arFragment.getArSceneView().getArFrame();

                    Collection<AugmentedImage> augmentedImages=frame.getUpdatedTrackables(AugmentedImage.class);
                    for(AugmentedImage augmentedImage: augmentedImages){

                        if(augmentedImage.getTrackingState()== TrackingState.TRACKING ){

                            if(augmentedImage.getName().equals("arimage") && shouldAddModel){
                                placeObject(arFragment,
                                        augmentedImage.createAnchor(augmentedImage.getCenterPose()),
                                        Uri.parse("author.jpg"));
                                shouldAddModel=false;
                            }
                    }}
                }

          private void placeObject(ArFragment fragment, Anchor anchor, Uri model){
                ViewRenderable.builder().
                        setView(this,R.layout.lol)
                        .setVerticalAlignment(ViewRenderable.VerticalAlignment.BOTTOM)
                        .build()
                        .thenAccept(viewRenderable -> addNodeToScene(fragment,anchor,viewRenderable))
                        .exceptionally(throwable -> {
                        AlertDialog.Builder builder=new AlertDialog.Builder(this);
                        builder.setMessage(throwable.getMessage())
                                .setTitle("Error!");
                        AlertDialog dialog=builder.create();
                        dialog.show();
                        return null;
                        });
            }

      private void addNodeToScene(ArFragment fragment, Anchor anchor, ViewRenderable viewRenderable) {

            AnchorNode anchorNode=new AnchorNode(anchor);

            anchorNode.setLocalScale(new Vector3(0.5f, 0.5f, 0.5f));

            TransformableNode node=new TransformableNode(fragment.getTransformationSystem());

            node.setRenderable(viewRenderable);

            node.setParent(anchorNode);
            fragment.getArSceneView().getScene().addChild(anchorNode);
            node.select();

        }

Body:
A simple local rotation of the node should do the trick.Once you have set the parent of the node as this.

 node.setParent(anchorNode);
 node.setLocalRotation(Quaternion.axisAngle(new Vector3(0, 0, 1f), 180));
 fragment.getArSceneView().getScene().addChild(anchorNode);

Play around with the values of the Quaternion. You should get it.


问:
Where is the "Sync Project With Gradle Files" option in Android Studio 3.5.3?
I'm new to Android Studio and I'm having trouble in finding the "Sync Project With Gradle Files"

option in Android Studio version 3.5.3. I'm currently developing applications with Flutter.

I did find out that in the previous version of Android Studio (I'm not sure which, sorry!), it seems that the "Sync Project With Gradle Files" option can be found by clicking
File > Sync Project With Gradle Files OR at the toolbar.

(Attached are images regarding previous "Sync Project With Gradle Files" locations)

File

toolbar

However, I could not find it in my Android Studio version 3.5.3's  File nor at the toolbar. There is no such option.

I am sorry if this question has already been answered else where or
  the question is a duplicated one. (This is also my first time posting
  a question in Stack Overflow) I would be very grateful if someone can
  help me with this...thank you in advance

答:
This icon is not showing up because you are inside your Flutter project.

If you open the Android project, that is inside your Flutter project, directly on Android Studio, an Icon will appear next to the AVD Manager (Device Manager) that looks like a little elefant with an arrow pointing diagonally to the bottom left corner. That is the button that does the action "Sync project with Gradle Files".

The first time you open the Android project directly it may take a minute for that icon to not be greyed out, as Android Studio will be syncing all the files, as you'll be able to see on the bottom bar.


问:
How to update DB when field changed in mongoalchemy.(flask)？
I am using flask-mongoalchemy to do a demo, and here is a question confused me for a while.
At first I create a class User

```<code>class Student(db.Document):
    '''student info'''
    name = db.StringField()
    grade = db.IntField(required=False, default=None)
</code>```

Then, I use this DB and create some example, such as student1, student2...and so on。
Now, I change the default value of grade from None to 0

```<code>grade = db.IntField(required=False, default=0)
</code>```

When I run query again, it raise error:

```<code>mongoalchemy.exceptions.BadValueException: Bad value for field of type "grade".  Reason: "Value is not an instance of <class 'int'>
</code>```

SO， how to auto-update this field change?  What I did now is to modify the value of age in database manualy.

答:
First, to get the queries working as before set allow_none option on the field to True.

```<code>grade = db.IntField(required=False, default=0, allow_none=True)
</code>```

That should allow documents having no value for grades to not trigger errors when unwrapped as python objects.

Next, make a migration that sets the default value for documents where grade is None to 0.

from mongoalchemy.session import Session

with Session.connect('mongoalchemy') as s:
    update = s.query(Student).filter(Student.grade == None).set(User.grade, 0)
    update.execute()
```

Lastly, switch the field declaration back to disallow None values for the grade.

Body:
I am using flask-mongoalchemy to do a demo, and here is a question confused me for a while.
At first I create a class User

class Student(db.Document):
    '''student info'''
    name = db.StringField()
    grade = db.IntField(required=False, default=None)

Then, I use this DB and create some example, such as student1, student2...and so on。
Now, I change the default value of grade from None to 0

grade = db.IntField(required=False, default=0)

When I run query again, it raise error:

mongoalchemy.exceptions.BadValueException: Bad value for field of type "grade".  Reason: "Value is not an instance of <class 'int'>

SO， how to auto-update this field change?  What I did now is to modify the value of age in database manualy.

Body:
First, to get the queries working as before set allow_none option on the field to True.

grade = db.IntField(required=False, default=0, allow_none=True)

That should allow documents having no value for grades to not trigger errors when unwrapped as python objects.

Next, make a migration that sets the default value for documents where grade is None to 0.

from mongoalchemy.session import Session

with Session.connect('mongoalchemy') as s:
    update = s.query(Student).filter(Student.grade == None).set(User.grade, 0)
    update.execute()

Lastly, switch the field declaration back to disallow None values for the grade.


问:
Get table schema in Redshift
Hello I am trying to retrieve the schema of an existing table. I am mysql developer and am trying to work with amazon redshift. How can I export the schema of an existing table. In mysql we can use the show create table command.</p>

```<code>SHOW CREATE TABLE tblName;
</code>```

答:
To get the column data and schema of a particular table:

select * from information_schema.columns where tablename='<<table_name>>'

To get the information of a table metadata fire the below query

select * from information_schema.tables where schema='<<schema_name>>'

Title: Get table schema in Redshift

Body:
Hello I am trying to retrieve the schema of an existing table. I am mysql developer and am trying to work with amazon redshift. How can I export the schema of an existing table. In mysql we can use the show create table command.

SHOW CREATE TABLE tblName;


问:
Refactor jQuery inview event listener
I want to convert the following code to pure JavaScript.

```<code>$(function () {
    $('h2,.single').on('inview', function () {
        $(this).addClass('is-show');
    });
});
</code>```

I tried much time but still can not figure out how. Any helps?

答:
Except the event you can use this:

```<code>(function() {
     document.querySelector("h2, .single").addEventListener("click", function(){
         this.classList.add("is-show");
  });
})();
</code>```

I didn't find an equivalent for inview. You can refer to this.

Title: Refactor jQuery inview event listener

Body:
I want to convert the following code to pure JavaScript.

$(function () {
    $('h2,.single').on('inview', function () {
        $(this).addClass('is-show');
    });
});

I tried much time but still can not figure out how. Any helps?

Body:
Except the event you can use this:

(function() {
     document.querySelector("h2, .single").addEventListener("click", function(){
         this.classList.add("is-show");
  });
})();

I didn't find an equivalent for inview. You can refer to this.


问:
Identical Oracle db setups: exception on just one of them
edit: Look to the end of this question for what caused the error and how I found out.

I have a very strange exception thrown on me from Hibernate when I run an app that does batch inserts of data into an oracle database. The error comes from the Oracle database, ORA-00001, which

" means that an attempt has been made to
  insert a record with a duplicate
  (unique) key. This error will also be
  generated if an existing record is
  updated to generate a duplicate
  (unique) key."

The error is weird because I have created the same table (exactly same definition) on another machine where I do NOT get the same error if I use that through my app. AND all the data get inserted into the database, so nothing is really rejected.

There has to be something different between the two setups, but the only thing I can see that is different is the banner output that I get when issuing

```<code>select * from v$version where banner like 'Oracle%';
</code>```

The database that gives me trouble:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod

The one that works:
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production

Table definitions, input, and the app I wrote is the same for both. The table involved is basically a four column table with a composite id (serviceid, date, value1, value2) - nothing fancy.

Any ideas on what can be wrong? I have started out clean several times, dropping both tables to start on equal grounds, but I still get the error from the database.

Some more of the output:

```<code>Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (STATISTICS.PRIMARY_KEY_CONSTRAINT) violated

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:367)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:8728)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
</code>```

How I found out what caused the problem

Thanks to APC and ik_zelf I was able to pinpoint the root cause of this error. It turns out the Quartz scheduler was wrongly configured for the production database (where the error turned up).
For the job running against the non-failing oracle server I had <cronTriggerExpression>0/5 * * * * ?</cronTriggerExpression> which ran the batch job every five seconds. I figured that once a minute was sufficent for the other oracle server, and set the quartz scheduler up with * */1 * * * ?. This turns out to be wrong, and instead of running every minute, this ran every second!

Each job took approximately 1.5-2 seconds, and thus two or more jobs were running concurrently, thus causing simultaneous inserts on the server. So instead of inserting 529 elements, I was getting anywhere from 1000 to 2000 inserts. Changing the crontrigger expression to the same as the other one, running every five seconds, fixed the problem.

To find out what was wrong I had to set true in hibernate.cfg.xml and disable the primary key constraint on the table.

```<code>-- To catch exceptions
-- to find the offending rows run the following query
-- SELECT * FROM uptime_statistics, EXCEPTIONS WHERE MY_TABLE.rowid = EXCEPTIONS.row_id;
create table exceptions(row_id rowid,
                        owner varchar2(30),
                        table_name varchar2(30),
                        constraint varchar2(30));

-- This table was set up
CREATE TABLE MY_TABLE
  (
    LOGDATE DATE NOT NULL,
    SERVICEID           VARCHAR2(255 CHAR) NOT NULL,
    PROP_A   NUMBER(10,0),
    PROP_B NUMBER(10,0),
    CONSTRAINT PK_CONSTRAINT PRIMARY KEY (LOGDATE, SERVICEID)
  );

-- Removed the constraint to see what was inserted twice or more
alter table my_table
  disable constraint PK_CONSTRAINT;

-- Enable this later on to find rows that offend the constraints
alter table my_table
  enable constraint PK_CONSTRAINT
    exceptions into exceptions;
</code>```

答:
My guess would be the service id. Whatever service_id hibernate is using for the 'fresh' insert has already been used.

Possibly the table is empty in one database but populated in another

I'm betting though that the service_id is sequence generated and the sequence number is out of sync with the data content. So you have the same 1000 rows in the table but doing

```<code>SELECT service_id_seq.nextval FROM DUAL
</code>```

in one database gives a lower number than the other. I see this a lot where the sequence has been created (eg out of source control) and data has been imported into the table from another database.

Body:
edit: Look to the end of this question for what caused the error and how I found out.

I have a very strange exception thrown on me from Hibernate when I run an app that does batch inserts of data into an oracle database. The error comes from the Oracle database, ORA-00001, which

" means that an attempt has been made to
  insert a record with a duplicate
  (unique) key. This error will also be
  generated if an existing record is
  updated to generate a duplicate
  (unique) key."

The error is weird because I have created the same table (exactly same definition) on another machine where I do NOT get the same error if I use that through my app. AND all the data get inserted into the database, so nothing is really rejected.

There has to be something different between the two setups, but the only thing I can see that is different is the banner output that I get when issuing

select * from v$version where banner like 'Oracle%';

The database that gives me trouble:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod

The one that works:
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production

Table definitions, input, and the app I wrote is the same for both. The table involved is basically a four column table with a composite id (serviceid, date, value1, value2) - nothing fancy.

Any ideas on what can be wrong? I have started out clean several times, dropping both tables to start on equal grounds, but I still get the error from the database.

Some more of the output:

Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (STATISTICS.PRIMARY_KEY_CONSTRAINT) violated

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:367)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:8728)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)

How I found out what caused the problem

Thanks to APC and ik_zelf I was able to pinpoint the root cause of this error. It turns out the Quartz scheduler was wrongly configured for the production database (where the error turned up).
For the job running against the non-failing oracle server I had <cronTriggerExpression>0/5 * * * * ?</cronTriggerExpression> which ran the batch job every five seconds. I figured that once a minute was sufficent for the other oracle server, and set the quartz scheduler up with * */1 * * * ?. This turns out to be wrong, and instead of running every minute, this ran every second!

Each job took approximately 1.5-2 seconds, and thus two or more jobs were running concurrently, thus causing simultaneous inserts on the server. So instead of inserting 529 elements, I was getting anywhere from 1000 to 2000 inserts. Changing the crontrigger expression to the same as the other one, running every five seconds, fixed the problem.

To find out what was wrong I had to set true in hibernate.cfg.xml and disable the primary key constraint on the table.

-- To catch exceptions
-- to find the offending rows run the following query
-- SELECT * FROM uptime_statistics, EXCEPTIONS WHERE MY_TABLE.rowid = EXCEPTIONS.row_id;
create table exceptions(row_id rowid,
                        owner varchar2(30),
                        table_name varchar2(30),
                        constraint varchar2(30));

-- This table was set up
CREATE TABLE MY_TABLE
  (
    LOGDATE DATE NOT NULL,
    SERVICEID           VARCHAR2(255 CHAR) NOT NULL,
    PROP_A   NUMBER(10,0),
    PROP_B NUMBER(10,0),
    CONSTRAINT PK_CONSTRAINT PRIMARY KEY (LOGDATE, SERVICEID)
  );

-- Removed the constraint to see what was inserted twice or more
alter table my_table
  disable constraint PK_CONSTRAINT;

-- Enable this later on to find rows that offend the constraints
alter table my_table
  enable constraint PK_CONSTRAINT
    exceptions into exceptions;

Body:
My guess would be the service id. Whatever service_id hibernate is using for the 'fresh' insert has already been used.

Possibly the table is empty in one database but populated in another

I'm betting though that the service_id is sequence generated and the sequence number is out of sync with the data content. So you have the same 1000 rows in the table but doing

SELECT service_id_seq.nextval FROM DUAL

in one database gives a lower number than the other. I see this a lot where the sequence has been created (eg out of source control) and data has been imported into the table from another database.


问:
AppleScript to launch and loop a video full screen avoiding menu bar
I'm trying to run this applescript:

```<code>tell application "QuickTime Player"
    activate
    open alias "Users:ebowen:Desktop:MOUND_1.32GB_h264.mov"
    play the front document
end tell
tell application "System Events" to tell process "QuickTime Player"
    set frontmost to true
    tell menu bar item 5 of menu bar 1
        click menu item "Enter Full Screen" of menu 1
        click menu item "Loop" of menu 1
    end tell
end tell
</code>```

on a mac mini running OSX 10.6.8 and it works except if it runs automatically when starting up.

When running from start-up, the mac's mouse pointer defaults to positioning itself over the apple menu and this leaves the menu bar still visible over the full-screen mov

I need to avoid all that and have it play full-screen with no menu bar automatically. Any pointers?
Thanks

答: In the end, I had to resort to switching on mouse keys in accessibility preferences and then applescript keystrokes to move the cursor away from the apple.</p>

Body:
I'm trying to run this applescript:

tell application "QuickTime Player"
    activate
    open alias "Users:ebowen:Desktop:MOUND_1.32GB_h264.mov"
    play the front document
end tell
tell application "System Events" to tell process "QuickTime Player"
    set frontmost to true
    tell menu bar item 5 of menu bar 1
        click menu item "Enter Full Screen" of menu 1
        click menu item "Loop" of menu 1
    end tell
end tell

on a mac mini running OSX 10.6.8 and it works except if it runs automatically when starting up.

When running from start-up, the mac's mouse pointer defaults to positioning itself over the apple menu and this leaves the menu bar still visible over the full-screen mov

I need to avoid all that and have it play full-screen with no menu bar automatically. Any pointers?
Thanks


问:
How do I make my end users (under wso2 identity server) subscribe to a api in wso2 api manager?
I am currently doing a PoC on WSO2 API manager (v2.6.0). I am already having a Web application (Ex: Pizza booking) and also registered customers (end users) who is using the application for pizza booking. Now I wanted to bring the backend services of the pizza booking app such as,

Choose store location,

Book pizza,

Track order, etc.

as APIs into the WSO2 API Manager. For this, I would create the required apis in API manager. Then I wanted to bring my existing web application users (end users) into the API manager and provide access to those apis.

What would be the best way to implement this?

Bring my users under WSO2 identity server and use identity server as a key manager to my API manager?

Bring my users under secondary user store/ use custom user store of API manager?

Out in that case, how would I provide access to particular API's (subscribing to API's) without logging to API manager store and subscribing manually for every user?

Also,

What is the use of creating a Service provider and creating an Oauth application under Inbound authentication?

What can I do with this application?

Is this same as the application we create before subscribing to an API in API manager store?

Can I add users to this application and grant access to them in common?

Can I subscribe to API's using this application so that all users under this application will have access to it?

答:
Adding to what @Menaka has explained. </p>

<p>Your end-users don't have to subscribe to APIs. Only the application developer has to subscribe and embed the consumer key/secret to their app. Then the application should generate tokens for the end-users using those keypair+end user credentials.  </p>

Body:
Adding to what @Menaka has explained.

Your end-users don't have to subscribe to APIs. Only the application developer has to subscribe and embed the consumer key/secret to their app. Then the application should generate tokens for the end-users using those keypair+end user credentials.


问:
How to Call Method in Fragment From Parent Activity?
**Here is the Fragment I want call getAvailableWebsites(); from parent Activity **    </p>

```<code>public class Earn extends Fragment {

public Earn() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_earn, container, false);
}
public void getAvailableWebsites(){
    Toast.makeText(getActivity(),"Called From Activity",Toast.LENGTH_LONG).show();
}
</code>```

<p>}</p>

答:
Implement an interface b/w your fragment and activity.
Read this for more clarity

Body:
**Here is the Fragment I want call getAvailableWebsites(); from parent Activity **

public class Earn extends Fragment {

public Earn() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_earn, container, false);
}
public void getAvailableWebsites(){
    Toast.makeText(getActivity(),"Called From Activity",Toast.LENGTH_LONG).show();
}

}


问:
RabbitMQ Multiple Listeners for same Event
I have an event named CompanyUpdated that gets raised each time when a company profile is updated.
I need two listeners to listen to this event . One for search service to update its data for Azure Search and another for Updating the company details in Catalog Management.

Can I create two listeners to listen to this event?

Also, is it possible to name the two listeners with the same name in two different microservices?

答:
Rabbit MQ supports pub-sub. You should create two queues and use an exchange that will route the message to two queues (like fanout exchange). Then the listener for Azure Search should listen to one queue, and Catalog Management Listener should listen to another queue.

This will guarantee that both listeners will get the event.

I can't comment much on asp.net since I don't have any experience with the .Net platform.
However, you can read Pub-Sub implementation tutorial for C# for more details.


问:
CSS child selector doesn't work on ie9
i have a page like this:

```<code><body>
<table width="100%">...</table>
<table width="100%">...</table>
<table width="100%">...</table>
<table width="100%">...</table>
</body>
</code>```

what i need to do is making all those tables 85% width and horizontally centered on the page. it would be easy if the page was a single page but this needs to work on 100+ pages and the only thing they have in common is the stylesheet file. so i need to do this with css only. i can't cover the tables inside a div or use jquery.

what i tried is:

```<code>body { text-align:center; }
body > table { text-align: left; margin: 0 auto; width: 85%; }
</code>```

this works perfectly on firefox and google chrome but it doesn't seem to work on ie9 (didn't tested but i'm sure it won't work with earlier ie versions)

i've tried lots of methods they wrote on similar questions but couldn't be able to solve this.

EDIT:

The doctype of the page was:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
</code>```

i changed it to:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

and it works on ie9 too now!

The updated question is: is it possible without changing the doctype?

答:
As Yi Jiang says, your doctype declaration isn't correct. IE9 probably can't figure out what to do about that, so runs back and hides in its quirks-mode shell, where it becomes blind to the child selector (or, becomes 10 years younger).

The easiest and surely-recommended way is to change your doctype declaration in order to get it back to standards mode and apply the rule:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
</code>```

Otherwise you can try forgoing the child selector and try to reset styles on the rest of your tables using whatever default styles you'd like:

```<code>body { text-align:center; }
body table { text-align: left; margin: 0 auto; width: 85%; }
body * table { /* Styles for other tables */ }
</code>```

But as you see, the * selector there doesn't look very friendly, so changing the doctype is definitely the better path to take.

Title: CSS child selector doesn't work on ie9

Body:
i have a page like this:

...

...

...

...

what i need to do is making all those tables 85% width and horizontally centered on the page. it would be easy if the page was a single page but this needs to work on 100+ pages and the only thing they have in common is the stylesheet file. so i need to do this with css only. i can't cover the tables inside a div or use jquery.

what i tried is:

body { text-align:center; }
body > table { text-align: left; margin: 0 auto; width: 85%; }

this works perfectly on firefox and google chrome but it doesn't seem to work on ie9 (didn't tested but i'm sure it won't work with earlier ie versions)

i've tried lots of methods they wrote on similar questions but couldn't be able to solve this.

EDIT:

The doctype of the page was:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

i changed it to:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

and it works on ie9 too now!

The updated question is: is it possible without changing the doctype?

Body:
As Yi Jiang says, your doctype declaration isn't correct. IE9 probably can't figure out what to do about that, so runs back and hides in its quirks-mode shell, where it becomes blind to the child selector (or, becomes 10 years younger).

The easiest and surely-recommended way is to change your doctype declaration in order to get it back to standards mode and apply the rule:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Otherwise you can try forgoing the child selector and try to reset styles on the rest of your tables using whatever default styles you'd like:

body { text-align:center; }
body table { text-align: left; margin: 0 auto; width: 85%; }
body * table { /* Styles for other tables */ }

But as you see, the * selector there doesn't look very friendly, so changing the doctype is definitely the better path to take.


问:
Why Jackson JSON mapping exception when Serializing/Deserializing Geometry type
When I create a User defined class "Asset".

```<code>public class Asset {
    private UUID id;
    private String name;
}
</code>```

And set an object of this class as a response.

```<code>@GetMapping("/testSerialization")
public Asset testSerialization() {
    return new Asset()
}
</code>```

This controller works successfully.

But when the same controller uses Geometry Types the request fails,

```<code>import com.vividsolutions.jts.geom.Point;

// Does not work
@GetMapping("/testSerialization")
public Point testSerialization() {
    GeometryFactory geometryFactory = new GeometryFactory();
    Point point = geometryFactory.createPoint(new Coordinate(1, 2));
    return point;
}
</code>```

I know that I have to add Serialization & De-Serialization references to Jackson, either manually or using a library like Jackson-datatype-jts, to enable Jackson to work with Geometry classes

My Question is, why do I have to do this explicitly for Geomtery types, whereas my Custom classes work without manipulating any configurations?

答:
Jackson works well without any extra configuration with all regular POJO classes. Problem appears, when POJO classes are not regular: for example, do not have getters, setters, no-arg constructor, etc.

In your case, two or more classes have circular reference between them. When default serialiser wants to serialise all properties it dives in infinite recursion because of that. In that case we need to provide custom serialiser which handles this case properly.

This is why you need to provide custom serialisers and deserialisers for com.vividsolutions.jts.geom package.

Body:
When I create a User defined class "Asset".

public class Asset {
    private UUID id;
    private String name;
}

And set an object of this class as a response.

@GetMapping("/testSerialization")
public Asset testSerialization() {
    return new Asset()
}

This controller works successfully.

But when the same controller uses Geometry Types the request fails,

import com.vividsolutions.jts.geom.Point;

// Does not work
@GetMapping("/testSerialization")
public Point testSerialization() {
    GeometryFactory geometryFactory = new GeometryFactory();
    Point point = geometryFactory.createPoint(new Coordinate(1, 2));
    return point;
}

I know that I have to add Serialization & De-Serialization references to Jackson, either manually or using a library like Jackson-datatype-jts, to enable Jackson to work with Geometry classes

My Question is, why do I have to do this explicitly for Geomtery types, whereas my Custom classes work without manipulating any configurations?


问:
Delete duplicate rows with an order by
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

```<code>;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1
</code>```

and this is the output:

how to delete duplicate rows and show the output like this:

答:
In your particular scenario logic which has been written will not work work because if you closely look at the output of your CTE you will always have RowNumber as 1.

You query would be somewhat like this.

```<code>DECLARE @Temp AS TABLE
(
    ID          INT IDENTITY(1,1)
    ,NIP        VARCHAR(2)
    ,[NAME]     VARCHAR(10)
    ,DEPARTMENT VARCHAR(4)
    ,STATUSIN   DATETIME
)

INsERT INTO @Temp
(
     NIP
    ,[NAME]
    ,DEPARTMENT
    ,STATUSIN
)
VALUES
 ('A1','ARIA','BB',GETDATE())
,('A1','ARIA','BB',GETDATE())
,('A1','ARIA','BB',DATEADD(MINUTE,-1,GETDATE()))
,('A1','ARIA','BB',DATEADD(MINUTE,-1,GETDATE()))
,('A2','CHLOE','BB',DATEADD(MINUTE,-2,GETDATE()))
,('A2','CHLOE','BB',DATEADD(MINUTE,-3,GETDATE()))
,('A2','CHLOE','BB',DATEADD(MINUTE,-3,GETDATE()))
,('A3','Test','BB',DATEADD(MINUTE,-6,GETDATE()))

;WITH CTE AS
(
   SELECT
         NIP
        ,[NAME]
        ,ID         = MAX(Id)
        ,STATUSIN
        ,ROW_NUMBER()OVER(PARTITION BY [Name] ORDER BY STATUSIN) AS RowNumber
   FROM @Temp
   GROUP BY
        NIP
        ,[NAME]
        ,STATUSIN
)
SELECT * -- To do a delete change this line to DELETE T
FROM
    @Temp AS T
    LEFT OUTER JOIN CTE ON T.ID = CTE.ID
WHERE
    CTE.ID IS NULL
ORDER BY
    T.[NAME]
    ,T.STATUSIN
</code>```

I have only written select which will display the records needs to be deleted. You can verify the results by changing CTE.ID IS NULL to IS NOT NULL.

I hope this will help... Good Luck

Title: Delete duplicate rows with an order by

Body:
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1

and this is the output:

how to delete duplicate rows and show the output like this:

Body:
In your particular scenario logic which has been written will not work work because if you closely look at the output of your CTE you will always have RowNumber as 1.

You query would be somewhat like this.

DECLARE @Temp AS TABLE
(
    ID          INT IDENTITY(1,1)
    ,NIP        VARCHAR(2)
    ,[NAME]     VARCHAR(10)
    ,DEPARTMENT VARCHAR(4)
    ,STATUSIN   DATETIME
)

INsERT INTO @Temp
(
     NIP
    ,[NAME]
    ,DEPARTMENT
    ,STATUSIN
)
VALUES
 ('A1','ARIA','BB',GETDATE())
,('A1','ARIA','BB',GETDATE())
,('A1','ARIA','BB',DATEADD(MINUTE,-1,GETDATE()))
,('A1','ARIA','BB',DATEADD(MINUTE,-1,GETDATE()))
,('A2','CHLOE','BB',DATEADD(MINUTE,-2,GETDATE()))
,('A2','CHLOE','BB',DATEADD(MINUTE,-3,GETDATE()))
,('A2','CHLOE','BB',DATEADD(MINUTE,-3,GETDATE()))
,('A3','Test','BB',DATEADD(MINUTE,-6,GETDATE()))

;WITH CTE AS
(
   SELECT
         NIP
        ,[NAME]
        ,ID         = MAX(Id)
        ,STATUSIN
        ,ROW_NUMBER()OVER(PARTITION BY [Name] ORDER BY STATUSIN) AS RowNumber
   FROM @Temp
   GROUP BY
        NIP
        ,[NAME]
        ,STATUSIN
)
SELECT * -- To do a delete change this line to DELETE T
FROM
    @Temp AS T
    LEFT OUTER JOIN CTE ON T.ID = CTE.ID
WHERE
    CTE.ID IS NULL
ORDER BY
    T.[NAME]
    ,T.STATUSIN

I have only written select which will display the records needs to be deleted. You can verify the results by changing CTE.ID IS NULL to IS NOT NULL.

I hope this will help... Good Luck


问:
Remove an item of an inner array inside an array - react native
I've an json data that has an array. Each element of an array has array named items. I want to remove the inner array element if the string doesnot match the itemName. I tried using filter method but its not working as expected. It only returns the matching inner array elements but all the outer array elements are removed too.
P.S see the code, json data, the output I get and the expected output. Thanks in advance

Code:

```<code>const update2 =
 state.menuResponse.map(
       item => {
        return item.items.filter(item => (item.itemName).includes("C"))
})

console.log("menuSearcheddd", update2)
</code>```

Json data

```<code>{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "2",
          "itemName": "burger-non veg",
        }
      ]
    }
  ]
}
</code>```

Output:

```<code>{
  "data": [
    {
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "items": []
    }
  ]
}
</code>```

What should be?

```<code>{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": []
    }
  ]
}
</code>```

答:
```<code>var list = this.state.materialList.filter(item => {
            //Filter Inner Array
            var innerData = item.data.filter(dataItem => {
                return dataItem.qty > 0
            })
            // Assign value
            item.data = innerData;
            return item.Id > 0
        })
 console.log('Filtered List ',list);
</code>```

Body:
I've an json data that has an array. Each element of an array has array named items. I want to remove the inner array element if the string doesnot match the itemName. I tried using filter method but its not working as expected. It only returns the matching inner array elements but all the outer array elements are removed too.
P.S see the code, json data, the output I get and the expected output. Thanks in advance

Code:

const update2 =
 state.menuResponse.map(
       item => {
        return item.items.filter(item => (item.itemName).includes("C"))
})

console.log("menuSearcheddd", update2)

Json data

{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "2",
          "itemName": "burger-non veg",
        }
      ]
    }
  ]
}

Output:

{
  "data": [
    {
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "items": []
    }
  ]
}

What should be?

{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": []
    }
  ]
}


问:
How to check if pid is threads or process
To check if process id is exist I check

```<code>if (0 != kill(pid, 0))
    printf(" not exist");
</code>```

In /proc/pid/task I can see all threads id in process id

How can I determine if pid is process or threads in Linux?

答:
you can check the gettid function.

The PID must be equal but the TID must be different in your case.

http://man7.org/linux/man-pages/man2/gettid.2.html

Body:
To check if process id is exist I check

if (0 != kill(pid, 0))
    printf(" not exist");

In /proc/pid/task I can see all threads id in process id

How can I determine if pid is process or threads in Linux?


问:
Laravel API, MySQL Query, Get average data in same date
My table is about weight. For example,

```<code>(February 10, 2020) = 60kg
(February 11, 2020) = 62kg
(February 11, 2020) = 63kg
(February 11, 2020) = 64kg
(February 12, 2020) = 65kg
</code>```

Json should return,

```<code>{
"weight": 60,
 "created_at": "2020-02-10"
},
{
"weight": 63,
"created_at": "2020-02-11"
},
{
"weight": 65,
"created_at": "2020-02-12"
}
</code>```

with pagination.

Here's my existing code without average.

```<code>public function weightChart(Request $request, $id)
    {
        $data = WeightHistory::where('user_id', $id)->orderBy('created_at', 'DESC')->paginate(7);

        return WeightChartResource::collection($data);
    }
</code>```

答:
Change your query

```<code>$data = WeightHistory::where('user_id', $id)->orderBy('created_at', 'DESC')->paginate(7);
</code>```

To

```<code>$data = WeightHistory::where('user_id', $id)->select('created_at', DB::raw('AVG(weight) as weight'))->groupBy('created_at')->orderBy('created_at', 'DESC')->paginate(7);
</code>```

Body:
My table is about weight. For example,

(February 10, 2020) = 60kg
(February 11, 2020) = 62kg
(February 11, 2020) = 63kg
(February 11, 2020) = 64kg
(February 12, 2020) = 65kg

Json should return,

{
"weight": 60,
 "created_at": "2020-02-10"
},
{
"weight": 63,
"created_at": "2020-02-11"
},
{
"weight": 65,
"created_at": "2020-02-12"
}

with pagination.

Here's my existing code without average.

public function weightChart(Request $request, $id)
    {
        $data = WeightHistory::where('user_id', $id)->orderBy('created_at', 'DESC')->paginate(7);

        return WeightChartResource::collection($data);
    }

Body:
Change your query

$data = WeightHistory::where('user_id', $id)->orderBy('created_at', 'DESC')->paginate(7);

To

$data = WeightHistory::where('user_id', $id)->select('created_at', DB::raw('AVG(weight) as weight'))->groupBy('created_at')->orderBy('created_at', 'DESC')->paginate(7);


问:
Difference between View and Request scope in managed beans
What does the view scope mean? Can anyone explain about it, so that I can understand how it differs from the request scope?</p>

答:
A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

How to choose the right bean scope?

The benefits and pitfalls of @ViewScoped


问:
Why is the Microsoft.Azure.WebJobs.HttpTriggerAttribute used in Azure Function applications a parameter attribute and not a method attribute?
I have an Azure Functions app.

I was surprised to learn that when defining a Azure WebJob function the HttpTriggerAttribute does not have to be applied to a HttpRequest parameter.

So while this is valid, and matches most tutorials and examples,

```<code>[FunctionName("get")]
public async Task<IActionResult> Get(
      [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Get), Route = "api/get")]HttpRequest httpRequest)
</code>```

This is also valid,

```<code>[FunctionName("post")]
public async Task<IActionResult> Post(
      [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Post), Route = "api/post")]MyType body)
</code>```

Since the attribute is not tied to a HttpRequest parameter, I'm surprised the attribute is a parameter attribute and not a method attribute like,

```<code>[FunctionName("post")]
[HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Post), Route = "api/post")]
public async Task<IActionResult> Post(MyType body)
</code>```

Why is the HttpTriggerAttribute implemented as a parameter attribute and not a method attribute like FunctionNameAttribute?

答:
For C # class library development, FunctionName acts as a marker, marking methods as function entry points. It does not involve the input of a function. However, the trigger property is different. It not only has the function of marking the Function type, but also the role of binding input data to method parameters. These data are needed when processing the method. You can think of the trigger property as a binding of the type 'direction in'. This type of binding needs to be entered as a parameter in the development method of the C # class library. Bindings of type 'direction out' are defined outside the function as outputs. Its characteristics are so.

Example of a standard C # class library Function: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-example#class-library-example

Body:
I have an Azure Functions app.

I was surprised to learn that when defining a Azure WebJob function the HttpTriggerAttribute does not have to be applied to a HttpRequest parameter.

So while this is valid, and matches most tutorials and examples,

[FunctionName("get")]
public async Task<IActionResult> Get(
      [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Get), Route = "api/get")]HttpRequest httpRequest)

This is also valid,

[FunctionName("post")]
public async Task<IActionResult> Post(
      [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Post), Route = "api/post")]MyType body)

Since the attribute is not tied to a HttpRequest parameter, I'm surprised the attribute is a parameter attribute and not a method attribute like,

[FunctionName("post")]
[HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Post), Route = "api/post")]
public async Task<IActionResult> Post(MyType body)

Why is the HttpTriggerAttribute implemented as a parameter attribute and not a method attribute like FunctionNameAttribute?


问:
Highlighting unmatched brackets in vim
I'm getting burned repeatedly by unmatched parentheses while writing python code in vim.  I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren.  I looked at the c.vim syntax file briefly to try to understand it, but the section that handles bracket errors is very complex.  Can anyone explain how that code works and suggest how I might write something similar for python code?

Example C code with unmatched parens:

```<code>int main(void
{  /* brace highlighted in red */
}  /* brace highlighted in red */
</code>```

Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).

BTW, I tried out this vim plugin but I wasn't happy with the behavior.

Edit:

I'm using python to generate C++ code (a language that likes parentheses and semicolons).  I have a nasty habit of leaving the trailing paren off a file.write() method call.  It would be nice if I could get vim to make that mistake more visually obvious.

Update:

Ok, here's what I've tried so far.

```<code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code>```

Unfortunately, all this does is highlight as an error the right paren of all balanced parentheses, the opposite of what I want to do.  I really don't understand what I'm doing here (just copied off of the existing C syntax file).  If anyone could explain what I did (wrong), I would appreciate it.

答: Have you tried using matchit.vim?  It supports all sorts of matches, and it should work in Python.

OwnerDisplayName: Kristo

Title: Highlighting unmatched brackets in vim

Body:
I'm getting burned repeatedly by unmatched parentheses while writing python code in vim.  I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren.  I looked at the c.vim syntax file briefly to try to understand it, but the section that handles bracket errors is very complex.  Can anyone explain how that code works and suggest how I might write something similar for python code?

Example C code with unmatched parens:

int main(void
{  /* brace highlighted in red */
}  /* brace highlighted in red */

Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).

BTW, I tried out this vim plugin but I wasn't happy with the behavior.

Edit:

I'm using python to generate C++ code (a language that likes parentheses and semicolons).  I have a nasty habit of leaving the trailing paren off a file.write() method call.  It would be nice if I could get vim to make that mistake more visually obvious.

Update:

Ok, here's what I've tried so far.

:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error

Unfortunately, all this does is highlight as an error the right paren of all balanced parentheses, the opposite of what I want to do.  I really don't understand what I'm doing here (just copied off of the existing C syntax file).  If anyone could explain what I did (wrong), I would appreciate it.

LastEditorDisplayName: Kristo

OwnerDisplayName: Nathan Fellman


问:
Shuffling of the training data for LightGBM
Do I need to externally shuffle the training dataset before passing it to lightgbm train function? Please assume that I DO NOT use lgbm's Cross Validation methods. </p>

答: In the official example they don't shuffle the data. It is very common for tree based models to not require manual shuffling. So NO, you don't need to shuffle.</p>


问:
Returning records from multiple (4) tables
I am trying to write a query returning records from multiple tables.

ConfRooms contains a list of rooms
FIDS_Hardware contains information about the hardware in the room
ConfBookings contains a list of booked rooms
ConfRoomOverride contains information on the room status, i.e does the room have an override flag set

Return all the records from "ConfRooms AS c" where c.HotelID = 'EXBHX'.

Return all the records from "FIDS_Hardware AS h" where r.HotelID = 'EXBHX' AND c.ConfRoomID = h.deviceID.

Return all the record from "ConfBookings AS b" where HotelID = 'EXBHX' AND c.ConfRoomName = b.RoomName.

Return all the record from "ConfRoomOverride AS o" where HotelID = 'EXBHX' AND c.ConfRoomNID = b.RoomID

At the moment my query is not returning all the records from "ConfRooms" but returns only the room that have a booked status in ConfBookings.

Can anyone see where I am going wrong.

```<code>SELECT
h.messageCount,
h.deviceID,
c.ConfRoomName,
r.DisplayMainBoard,
r.RecordID,
r.RoomID,
r.RoomName,
r.RoomBooked,
r.RoomFromDate,
r.RoomToDate,
r.FullBoardRoom,
COUNT(r.RecordID) AS RC,
r.Override,
r.HotelID,
o.Override AS ConfOverride
FROM
ConfRooms AS c
Left Join FIDS_Hardware AS h ON (c.ConfRoomID = h.deviceID)
Left Join ConfBookings AS r ON (c.ConfRoomName = r.RoomName)
Left Join ConfRoomOverride AS o ON (c.ConfRoomID = o.RoomID)
WHERE c.HotelID = 'EXBHX'
AND r.HotelID = 'EXBHX'
AND h.hotelID = 'EXBHX'
GROUP BY c.ConfRoomID
ORDER BY h.messageCount DESC,
ConfOverride DESC,
r.RoomBooked DESC,
c.ConfOrder ASC
</code>```

答:
Just try this :

```<code>SELECT
h.messageCount,
h.deviceID,
c.ConfRoomName,
r.DisplayMainBoard,
r.RecordID,
r.RoomID,
r.RoomName,
r.RoomBooked,
r.RoomFromDate,
r.RoomToDate,
r.FullBoardRoom,
COUNT(r.RecordID) AS RC,
r.Override,
r.HotelID,
o.Override AS ConfOverride
FROM
ConfRooms AS c
Left Join FIDS_Hardware AS h ON (c.ConfRoomID = h.deviceID AND h.hotelID = 'EXBHX')
Left Join ConfBookings AS r ON (c.ConfRoomName = r.RoomName AND r.HotelID = 'EXBHX')
Left Join ConfRoomOverride AS o ON (c.ConfRoomID = o.RoomID)
WHERE c.HotelID = 'EXBHX'
GROUP BY c.ConfRoomID
ORDER BY h.messageCount DESC,
ConfOverride DESC,
r.RoomBooked DESC,
c.ConfOrder ASC
</code>```

The problem is that your WHERE clause removes the benefits of your multiple left joins.

When you left join FIDS_Hardware AS h, it means that h values can be null but when you are executing "h.hotelID = 'EXBHX'" in your where clause you only select rows where h values are not null (a row has matched).

So what you need to do is to move these conditions right inside the ON clause of the left join as above.

Body:
I am trying to write a query returning records from multiple tables.

ConfRooms contains a list of rooms
FIDS_Hardware contains information about the hardware in the room
ConfBookings contains a list of booked rooms
ConfRoomOverride contains information on the room status, i.e does the room have an override flag set

Return all the records from "ConfRooms AS c" where c.HotelID = 'EXBHX'.

Return all the records from "FIDS_Hardware AS h" where r.HotelID = 'EXBHX' AND c.ConfRoomID = h.deviceID.

Return all the record from "ConfBookings AS b" where HotelID = 'EXBHX' AND c.ConfRoomName = b.RoomName.

Return all the record from "ConfRoomOverride AS o" where HotelID = 'EXBHX' AND c.ConfRoomNID = b.RoomID

At the moment my query is not returning all the records from "ConfRooms" but returns only the room that have a booked status in ConfBookings.

Can anyone see where I am going wrong.

SELECT
h.messageCount,
h.deviceID,
c.ConfRoomName,
r.DisplayMainBoard,
r.RecordID,
r.RoomID,
r.RoomName,
r.RoomBooked,
r.RoomFromDate,
r.RoomToDate,
r.FullBoardRoom,
COUNT(r.RecordID) AS RC,
r.Override,
r.HotelID,
o.Override AS ConfOverride
FROM
ConfRooms AS c
Left Join FIDS_Hardware AS h ON (c.ConfRoomID = h.deviceID)
Left Join ConfBookings AS r ON (c.ConfRoomName = r.RoomName)
Left Join ConfRoomOverride AS o ON (c.ConfRoomID = o.RoomID)
WHERE c.HotelID = 'EXBHX'
AND r.HotelID = 'EXBHX'
AND h.hotelID = 'EXBHX'
GROUP BY c.ConfRoomID
ORDER BY h.messageCount DESC,
ConfOverride DESC,
r.RoomBooked DESC,
c.ConfOrder ASC

Body:
Just try this :

SELECT
h.messageCount,
h.deviceID,
c.ConfRoomName,
r.DisplayMainBoard,
r.RecordID,
r.RoomID,
r.RoomName,
r.RoomBooked,
r.RoomFromDate,
r.RoomToDate,
r.FullBoardRoom,
COUNT(r.RecordID) AS RC,
r.Override,
r.HotelID,
o.Override AS ConfOverride
FROM
ConfRooms AS c
Left Join FIDS_Hardware AS h ON (c.ConfRoomID = h.deviceID AND h.hotelID = 'EXBHX')
Left Join ConfBookings AS r ON (c.ConfRoomName = r.RoomName AND r.HotelID = 'EXBHX')
Left Join ConfRoomOverride AS o ON (c.ConfRoomID = o.RoomID)
WHERE c.HotelID = 'EXBHX'
GROUP BY c.ConfRoomID
ORDER BY h.messageCount DESC,
ConfOverride DESC,
r.RoomBooked DESC,
c.ConfOrder ASC

The problem is that your WHERE clause removes the benefits of your multiple left joins.

When you left join FIDS_Hardware AS h, it means that h values can be null but when you are executing "h.hotelID = 'EXBHX'" in your where clause you only select rows where h values are not null (a row has matched).

So what you need to do is to move these conditions right inside the ON clause of the left join as above.


问:
Make sub columns (a group of columns with same header) in pdfmake
I would print a table which has a group of columns with the same cell as header.
An example in below:

I searched possible solution like this but it is a nested table, different of course from my purpose.

答:
Put your required logic accordingly in the loop of the table body. Also while doing body.push() you can concatinate the props with column name (ex: props[i] +' ' + columnA[i];) </p>

```<code>var columnA = "A";
var columnB = "B";
var columnC = "C";
var items = ["item1","item2","item3"];
var props = ["Prop1","Prop2","Prop3"];
var statuses = ["Free","Paid","Free"];
var dd = {
  content: [
      {
          table: {
              headerRows: 2,
              body: tableBody()
          }
      },
  ],
  styles: {
      header: {
        fontSize: 18,
        bold: true,
        color: 'red',
        alignment: 'center'
      }
  }
};

function tableBody(){
  var arr=[];
  var body =[
              [{text: 'Item', rowSpan: 2 , style:"header"}, {text: 'Properties',
               colSpan: 3, style:"header"}, '', '', {text: 'Status', rowSpan: 2 ,
               style:"header"}],
              ['', {text: 'A',style:"header"}, {text: 'B',style:"header"}, {text:
                 'C',style:"header"}, '']
            ]

    for(var j = 0;j < props.length; j++){
                body.push([items[j], (props[j] + ' '+ columnA), (props[j] + ' '+ columnB), (props[j] + ' '+ columnC), statuses[j]]);

    }
    return body;
}
</code>```

Body:
Put your required logic accordingly in the loop of the table body. Also while doing body.push() you can concatinate the props with column name (ex: props[i] +' ' + columnA[i];)

var columnA = "A";
var columnB = "B";
var columnC = "C";
var items = ["item1","item2","item3"];
var props = ["Prop1","Prop2","Prop3"];
var statuses = ["Free","Paid","Free"];
var dd = {
  content: [
      {
          table: {
              headerRows: 2,
              body: tableBody()
          }
      },
  ],
  styles: {
      header: {
        fontSize: 18,
        bold: true,
        color: 'red',
        alignment: 'center'
      }
  }
};

function tableBody(){
  var arr=[];
  var body =[
              [{text: 'Item', rowSpan: 2 , style:"header"}, {text: 'Properties',
               colSpan: 3, style:"header"}, '', '', {text: 'Status', rowSpan: 2 ,
               style:"header"}],
              ['', {text: 'A',style:"header"}, {text: 'B',style:"header"}, {text:
                 'C',style:"header"}, '']
            ]

    for(var j = 0;j < props.length; j++){
                body.push([items[j], (props[j] + ' '+ columnA), (props[j] + ' '+ columnB), (props[j] + ' '+ columnC), statuses[j]]);

    }
    return body;
}


问:
How to turn-on statistics through the session?
I want to turn on:

logging

pg_stat_statements

auto_explain extension

I know how to do it with configuration file, but how (if it's possible) to do it through my connection - I mean SQL statements, some directives, so that my steps are something like this:

connect to DB

execute some statements

now all queries are auto-explained in the concrete log file which I passed somewhere in 2., their statistics is collecting in pg_stat_statements table

How to achieve it? Is it possible? The initial state is: no logging at all, no auto_explain, to pg_stat_statements loaded/enabled.

PS. I have only one idea, to modify the configuration file from my app and then to call something like select pg_reload_conf(); but I am not sure that it works.

答:
You can do this using ALTER SYSTEM:

```<code>ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements,auto_explain';
</code>```

Then you need to restart the database, so that the changed shared_preload_libraries can take effect.

Then change these two:

```<code>ALTER SYSTEM SET auto_explain.log_min_duration = 0;
ALTER SYSTEM SET pg_stat_statements.track = all;
SELECT pg_reload_conf();
</code>```

Body:
You can do this using ALTER SYSTEM:

ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements,auto_explain';

Then you need to restart the database, so that the changed shared_preload_libraries can take effect.

Then change these two:

ALTER SYSTEM SET auto_explain.log_min_duration = 0;
ALTER SYSTEM SET pg_stat_statements.track = all;
SELECT pg_reload_conf();