问:
SubGroup in xslt with mutiple keys
I have a source xml like below. Im trying to convert to a desired format using xslt as shown below.

Sample XML

```<code><table>
    <row>
        <tablename>table1</tablename>
        <tableDesc>table1_desc</tableDesc>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable1</ultimateSourceTable>
        <ultimateSourceTableDesc>col1sourceTable1_desc</ultimateSourceTableDesc>
    </row>
    <row>
        <tablename>table1</tablename>
        <tableDesc>table1_desc</tableDesc>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        <ultimateSourceTableDesc>col1sourceTable2_desc</ultimateSourceTableDesc>
    </row>
    <row>
        <tablename>table2</tablename>
        <tableDesc>table2_desc</tableDesc>
        <columnname>table2_col1</columnname>
        <columnDesc>table2_col1_desc</columnDesc>
        <columnDataType>String</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        <ultimateSourceTableDesc>col1sourceTable2_desc</ultimateSourceTableDesc>
    </row>
</table>
</code>```

Desired Output

```<code><Prod>
        <dataBase>
            <physicalTableName>
                <tableName>table1</tableName>
                <tableDescription>table1_desc</tableDescription>
            </physicalTableName>
            <columnList>
                <column>
                <name>col1</name>
                <columnDesc>col1_desc</columnDesc>
                <columnDataType>Number</columnDataType>
                </column>
            </columnList>
            <finalSourceList>
                <column>
                    <columnName>col1</columnName>
                    <ultimateSourceTable>sourceTable1</ultimateSourceTable>
                    <ultimateSourceTableDesc>col1sourceTable1_desc</ultimateSourceTableDesc>
                </column>
                <column>
                    <columnName>col1</columnName>
                    <ultimateSourceTable>sourceTable2</ultimateSourceTable>
                    <ultimateSourceTableDesc>col1sourceTable1_desc</ultimateSourceTableDesc>
                </column>
            </finalSourceList>
            <physicalTableName>
                <tableName>table2</tableName>
                <tableDescription>table2_desc</tableDescription>
            </physicalTableName>
            <columnList>
                <column>
                <name>table2_col1</name>
                <columnDesc>table2_col1_desc</columnDesc>
                <columnDataType>String</columnDataType>
                <column/>
            </columnList>
            <finalSourceList>
                <column>
                    <columnName>table2_col1</columnName>
                    <ultimateSourceTable>sourceTable2</ultimateSourceTable>
                    <ultimateSourceTableDesc>col1sourceTable2_desc</ultimateSourceTableDesc>
                </column>
            </finalSourceList>
        </dataBase>
    </Prod>
</code>```

XSLT used

```<code><?xml version="1.0" encoding="UTF-8"?>
        <xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output method="xml" version="1.0" encoding="UTF-8"
                indent="yes" />
            <xsl:template match="/">
                <Prod>
                    <xsl:apply-templates />
                </Prod>
            </xsl:template>
            <xsl:key name="kElsByGroup" match="row" use="tablename" />
            <xsl:key name="TableColByGroup" match="row" use="concat(tablename,'|',columnname)" />
            <xsl:template match="row">
                <xsl:apply-templates />
            </xsl:template>
            <xsl:template
                match="row[generate-id()=generate-id(key('kElsByGroup',tablename)[1])]">
                <dataBase>
                    <physicalTableName>
                        <tableName>
                            <xsl:value-of select="tablename"></xsl:value-of>
                        </tableName>
                    </physicalTableName>
                    <columnList>
                        <xsl:for-each
                                           select="//row[generate-id()=generate-id(key('TableColByGroup',concat(tablename,'|',columnname))[1])]">
                            <xsl:element name="column">
                                <name>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </name>
                            </xsl:element>
                        </xsl:for-each>
                    </columnList>
                    <finalSourceList>
                        <xsl:for-each
                                            select="key('kElsByGroup',tablename)">
                            <xsl:element name="column">
                                <columnName>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </columnName>
                                <sourceTable>
                                    <xsl:value-of
                                                        select="ultimateSourceTable"></xsl:value-of>
                                </sourceTable>
                            </xsl:element>
                        </xsl:for-each>
                    </finalSourceList>
                </dataBase>
            </xsl:template>
            <xsl:template
                match="row[not(generate-id()=generate-id(key('kElsByGroup',tablename)[1]))]" />
        </xsl:stylesheet>
</code>```

So, I basically want to have only unique value in my columnList tag. I'm trying to subgroup using muenchian grouping but, I still 2 entries of col1 in my columnList tag. Can someone help me out?

答:
In attempt to mold the previous answer into a solution for this question I have come up with

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="table" match="row" use="tablename"/>

  <xsl:key name="col" match="row" use="concat(tablename, '|', columnname)"/>

  <xsl:template match="table">
      <Prod>
          <dataBase>
             <xsl:apply-templates select="row[generate-id() = generate-id(key('table', tablename)[1])]" mode="table"/>
          </dataBase>
      </Prod>
  </xsl:template>

  <xsl:template match="row/*" mode="table"/>

  <xsl:template match="row" mode="table">
      <physicalTableName>
          <xsl:apply-templates mode="table"/>
      </physicalTableName>
      <columnList>
          <xsl:apply-templates select="key('table', tablename)[generate-id() = generate-id(key('col', concat(tablename, '|', columnname))[1])]/*"/>
      </columnList>
      <finalSourceList>
          <xsl:apply-templates select="key('table', tablename)"/>
      </finalSourceList>
  </xsl:template>

  <xsl:template match="row/tablename" mode="table">
      <tableName>
          <xsl:value-of select="."/>
      </tableName>
  </xsl:template>

  <xsl:template match="row/tableDesc" mode="table">
      <tableDescription>
          <xsl:value-of select="."/>
      </tableDescription>
  </xsl:template>

  <xsl:template match="row/*"/>

  <xsl:template match="row/columnname">
      <name>
          <xsl:value-of select="."/>
      </name>
  </xsl:template>

  <xsl:template match="row/columnDesc | row/columnDataType">
      <xsl:copy-of select="."/>
  </xsl:template>

  <xsl:template match="row">
      <column>
          <xsl:apply-templates select="*[not(self::tablename)]" mode="source-list"/>
      </column>
  </xsl:template>

  <xsl:template match="row/*" mode="source-list"/>

  <xsl:template match="row/columnname" mode="source-list">
      <columnName>
          <xsl:value-of select="."/>
      </columnName>
  </xsl:template>

  <xsl:template match="row/ultimateSourceTable | row/ultimateSourceTableDesc" mode="source-list">
      <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/naZYrpu/2

Title: SubGroup in xslt with mutiple keys

Body:
I have a source xml like below. Im trying to convert to a desired format using xslt as shown below.

Sample XML

    <row>
        <tablename>table1</tablename>
        <tableDesc>table1_desc</tableDesc>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable1</ultimateSourceTable>
        <ultimateSourceTableDesc>col1sourceTable1_desc</ultimateSourceTableDesc>
    </row>
    <row>
        <tablename>table1</tablename>
        <tableDesc>table1_desc</tableDesc>
        <columnname>col1</columnname>
        <columnDesc>col1_desc</columnDesc>
        <columnDataType>Number</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        <ultimateSourceTableDesc>col1sourceTable2_desc</ultimateSourceTableDesc>
    </row>
    <row>
        <tablename>table2</tablename>
        <tableDesc>table2_desc</tableDesc>
        <columnname>table2_col1</columnname>
        <columnDesc>table2_col1_desc</columnDesc>
        <columnDataType>String</columnDataType>
        <ultimateSourceTable>sourceTable2</ultimateSourceTable>
        <ultimateSourceTableDesc>col1sourceTable2_desc</ultimateSourceTableDesc>
    </row>

Desired Output

<Prod>
        <dataBase>
            <physicalTableName>
                <tableName>table1</tableName>
                <tableDescription>table1_desc</tableDescription>
            </physicalTableName>
            <columnList>
                <column>
                <name>col1</name>
                <columnDesc>col1_desc</columnDesc>
                <columnDataType>Number</columnDataType>
                </column>
            </columnList>
            <finalSourceList>
                <column>
                    <columnName>col1</columnName>
                    <ultimateSourceTable>sourceTable1</ultimateSourceTable>
                    <ultimateSourceTableDesc>col1sourceTable1_desc</ultimateSourceTableDesc>
                </column>
                <column>
                    <columnName>col1</columnName>
                    <ultimateSourceTable>sourceTable2</ultimateSourceTable>
                    <ultimateSourceTableDesc>col1sourceTable1_desc</ultimateSourceTableDesc>
                </column>
            </finalSourceList>
            <physicalTableName>
                <tableName>table2</tableName>
                <tableDescription>table2_desc</tableDescription>
            </physicalTableName>
            <columnList>
                <column>
                <name>table2_col1</name>
                <columnDesc>table2_col1_desc</columnDesc>
                <columnDataType>String</columnDataType>
                <column/>
            </columnList>
            <finalSourceList>
                <column>
                    <columnName>table2_col1</columnName>
                    <ultimateSourceTable>sourceTable2</ultimateSourceTable>
                    <ultimateSourceTableDesc>col1sourceTable2_desc</ultimateSourceTableDesc>
                </column>
            </finalSourceList>
        </dataBase>
    </Prod>

XSLT used

<?xml version="1.0" encoding="UTF-8"?>
        <xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output method="xml" version="1.0" encoding="UTF-8"
                indent="yes" />
            <xsl:template match="/">
                <Prod>
                    <xsl:apply-templates />
                </Prod>
            </xsl:template>
            <xsl:key name="kElsByGroup" match="row" use="tablename" />
            <xsl:key name="TableColByGroup" match="row" use="concat(tablename,'|',columnname)" />
            <xsl:template match="row">
                <xsl:apply-templates />
            </xsl:template>
            <xsl:template
                match="row[generate-id()=generate-id(key('kElsByGroup',tablename)[1])]">
                <dataBase>
                    <physicalTableName>
                        <tableName>
                            <xsl:value-of select="tablename"></xsl:value-of>
                        </tableName>
                    </physicalTableName>
                    <columnList>
                        <xsl:for-each
                                           select="//row[generate-id()=generate-id(key('TableColByGroup',concat(tablename,'|',columnname))[1])]">
                            <xsl:element name="column">
                                <name>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </name>
                            </xsl:element>
                        </xsl:for-each>
                    </columnList>
                    <finalSourceList>
                        <xsl:for-each
                                            select="key('kElsByGroup',tablename)">
                            <xsl:element name="column">
                                <columnName>
                                    <xsl:value-of
                                                        select="columnname"></xsl:value-of>
                                </columnName>
                                <sourceTable>
                                    <xsl:value-of
                                                        select="ultimateSourceTable"></xsl:value-of>
                                </sourceTable>
                            </xsl:element>
                        </xsl:for-each>
                    </finalSourceList>
                </dataBase>
            </xsl:template>
            <xsl:template
                match="row[not(generate-id()=generate-id(key('kElsByGroup',tablename)[1]))]" />
        </xsl:stylesheet>

So, I basically want to have only unique value in my columnList tag. I'm trying to subgroup using muenchian grouping but, I still 2 entries of col1 in my columnList tag. Can someone help me out?

Body:
In attempt to mold the previous answer into a solution for this question I have come up with

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="table" match="row" use="tablename"/>

  <xsl:key name="col" match="row" use="concat(tablename, '|', columnname)"/>

  <xsl:template match="table">
      <Prod>
          <dataBase>
             <xsl:apply-templates select="row[generate-id() = generate-id(key('table', tablename)[1])]" mode="table"/>
          </dataBase>
      </Prod>
  </xsl:template>

  <xsl:template match="row/*" mode="table"/>

  <xsl:template match="row" mode="table">
      <physicalTableName>
          <xsl:apply-templates mode="table"/>
      </physicalTableName>
      <columnList>
          <xsl:apply-templates select="key('table', tablename)[generate-id() = generate-id(key('col', concat(tablename, '|', columnname))[1])]/*"/>
      </columnList>
      <finalSourceList>
          <xsl:apply-templates select="key('table', tablename)"/>
      </finalSourceList>
  </xsl:template>

  <xsl:template match="row/tablename" mode="table">
      <tableName>
          <xsl:value-of select="."/>
      </tableName>
  </xsl:template>

  <xsl:template match="row/tableDesc" mode="table">
      <tableDescription>
          <xsl:value-of select="."/>
      </tableDescription>
  </xsl:template>

  <xsl:template match="row/*"/>

  <xsl:template match="row/columnname">
      <name>
          <xsl:value-of select="."/>
      </name>
  </xsl:template>

  <xsl:template match="row/columnDesc | row/columnDataType">
      <xsl:copy-of select="."/>
  </xsl:template>

  <xsl:template match="row">
      <column>
          <xsl:apply-templates select="*[not(self::tablename)]" mode="source-list"/>
      </column>
  </xsl:template>

  <xsl:template match="row/*" mode="source-list"/>

  <xsl:template match="row/columnname" mode="source-list">
      <columnName>
          <xsl:value-of select="."/>
      </columnName>
  </xsl:template>

  <xsl:template match="row/ultimateSourceTable | row/ultimateSourceTableDesc" mode="source-list">
      <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/naZYrpu/2


来源: stackexchange

问:
How to determine the lucene index version?
I am writing a shell script (csh) that has to determine the lucene index version and then based on that it has to upgrade the index to next version.
So, if the lucene indices are on 2.x, I have to upgrade the indices to 3.x
Finally the indices need to be upgraded to 6.x.

Since upgrading indices is a sequential process(2.x->3.x->4.x->5.x->6.x), I have to know the indices version before hand so that I can set the classpath properly and upgrade.

Please help me on this.

答:
This is a piece of code I wrote to print the index version.

```<code>import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.index.StandardDirectoryReader;
import org.apache.lucene.store.SimpleFSDirectory;
import org.junit.Test;

public class TestReindex {

    public void testVersion() throws IOException{
        Path path = Paths.get("<Path_to_index_files>");

        try (DirectoryReader reader = StandardDirectoryReader.open(new SimpleFSDirectory(path))){
            Pattern pattern = Pattern.compile("lucene.version=(.*?),");

            Matcher matcher = pattern.matcher(reader.toString());
            if (matcher.find()) {
                System.out.println("Current version: " + matcher.group(1));
            }
        } catch(IndexFormatTooOldException ex) {
            System.out.println("Current version: " + ex.getVersion());
            System.out.println("Min Version: " + ex.getMinVersion());
            System.out.println("Max Version: " + ex.getMaxVersion());
        } catch (IndexFormatTooNewException ex) {
            System.out.println("Current version: " + ex.getVersion());
            System.out.println("Min Version: " + ex.getMinVersion());
            System.out.println("Max Version: " + ex.getMaxVersion());
        }
    }
}
</code>```

If you are trying to read an index that is too new or too old with respect to the version of Lucene being used, an exception will be thrown. The exceptions have info about the version which could be leveraged accordingly.

ContentLicense: CC BY-SA 3.0

Body:
This is a piece of code I wrote to print the index version.

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.index.StandardDirectoryReader;
import org.apache.lucene.store.SimpleFSDirectory;
import org.junit.Test;

public class TestReindex {

    public void testVersion() throws IOException{
        Path path = Paths.get("<Path_to_index_files>");

        try (DirectoryReader reader = StandardDirectoryReader.open(new SimpleFSDirectory(path))){
            Pattern pattern = Pattern.compile("lucene.version=(.*?),");

            Matcher matcher = pattern.matcher(reader.toString());
            if (matcher.find()) {
                System.out.println("Current version: " + matcher.group(1));
            }
        } catch(IndexFormatTooOldException ex) {
            System.out.println("Current version: " + ex.getVersion());
            System.out.println("Min Version: " + ex.getMinVersion());
            System.out.println("Max Version: " + ex.getMaxVersion());
        } catch (IndexFormatTooNewException ex) {
            System.out.println("Current version: " + ex.getVersion());
            System.out.println("Min Version: " + ex.getMinVersion());
            System.out.println("Max Version: " + ex.getMaxVersion());
        }
    }
}

If you are trying to read an index that is too new or too old with respect to the version of Lucene being used, an exception will be thrown. The exceptions have info about the version which could be leveraged accordingly.

ContentLicense: CC BY-SA 4.0


问:
Is there any way to pull the changes made in console using ask-cli? I couldn't find a command to do so
I am newbie and I have developed an Alexa Skill. I have already cloned the skill in my computer, but recently I have added new language support to my skill using the console. Now I want to pull those changes to my local copy. Is there a command to do so? I couldn't find one. If there isn't a command, then how to do it?

I have already ran ask -help, but it doesn't have any such commands to pull changes, or maybe I missed something.

I used ask diff to see the differences.

答:
I know this is late but In case it helps anyone out their, I agree with @Dana answer but a slight change is required here which seems to be missing in their official documentation and i.e. the order of providing the parameters. It works only one way round mentioned below.

ask api get-skill --stage development -s {skill_id}

If you try and provider skill-id before stage , you will be server with error : -

Please input required parameter: skill-id.


问:
NUXT SSR using images
I have an SSR application built in Nuxt. I am using renderRoute to render The Vue files since I need to send data to client side. Everything works fine but the static images are not being loaded in my application. I am using the following code to insert images in my vue file.

答:
This may help</p>

```<code><img :src="require('@/assets/img/picture.png')">
</code>```

Title: NUXT SSR using images

Body:
This may help

<img :src="require('@/assets/img/picture.png')">


问:
How use python function in flask jinja2 template?
I am sending one list of list to my HTML page, using flask jinja2 template. I want to check:- is item in list is of type str or not ?. But getting an exception of

jinja2.exceptions.UndefinedError: 'isinstance' is undefined

Code is as below:-

```<code>{% for i in req%}

    <tr>
        <th scope="row">{{loop.index}}</th>
        <td>{{i[1]}}</td>
        <td>{{i[24]}}</td>
        <td>{{i[49]}}</td>
        <td>{{i[53]}}</td>
        {% if isinstance(i[86], str) %}
            {% for j in i[86].split(",") %}
                <ol>
                    <li>{{i[86]}}</li>
                </ol>
            {% endfor %}
        {% else %}
            <td>{{i[86]}}</td>
        {% endif %}

    </tr>

    {% endfor %}
</code>```

I am able to use split(",") function and Want to use isinstance() or str()  of python in jinja 2 template.

答:
The language in the jinja template is not actually python, it's python like looking, it means python built-ins are not present. To make python built-ins present in every template, at startup, add any required built-ins to the globals parameter when building the jinja2.Environment. Something like below:

app.jinja_env.globals.update(isinstance=isinstance)
```

<p>or</p>

<pre class="lang-py prettyprint-override"><code>import jinja2
env = jinja2.Environment()
env.globals.update(isinstance:isinstance)
</code>```

Body:
I am sending one list of list to my HTML page, using flask jinja2 template. I want to check:- is item in list is of type str or not ?. But getting an exception of

jinja2.exceptions.UndefinedError: 'isinstance' is undefined

Code is as below:-

{% for i in req%}

        {{loop.index}}
        {{i[1]}}
        {{i[24]}}
        {{i[49]}}
        {{i[53]}}
        {% if isinstance(i[86], str) %}
            {% for j in i[86].split(",") %}

{{i[86]}}

            {% endfor %}
        {% else %}
            {{i[86]}}
        {% endif %}

    {% endfor %}

I am able to use split(",") function and Want to use isinstance() or str()  of python in jinja 2 template.

Body:
The language in the jinja template is not actually python, it's python like looking, it means python built-ins are not present. To make python built-ins present in every template, at startup, add any required built-ins to the globals parameter when building the jinja2.Environment. Something like below:

app.jinja_env.globals.update(isinstance=isinstance)

or

import jinja2
env = jinja2.Environment()
env.globals.update(isinstance:isinstance)


问:
How to use images as icons in bottom navigation view [Android]
I am trying to add bottom navigation view like below:

But it is coming like below:

I tried all the options, but I don't seem to quite get through, everything I do is only changing the color but I am not able to quite achieve what I want to.

Code below

```<code><com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/action_search"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/navigation_menu"
        tools:layout_editor_absoluteX="8dp"
        android:background="#232323"
        app:itemTextColor="@color/PrimaryText"
        app:itemIconTint="@null"/>
</code>```

Navigation Menu :

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_add_expense"
        android:icon="@drawable/addincome"
        android:title="Add Income" />
    <item android:id="@+id/action_add_income"
        android:icon="@drawable/addexpense"
        android:title="Add Expense" />
</menu>
</code>```

答:
set the Icon TintList to null programatically and you will be able to show your icons without any tint. </p>

```<code>bottomNavigationView.setItemIconTintList(null);
</code>```

Body:
I am trying to add bottom navigation view like below:

But it is coming like below:

I tried all the options, but I don't seem to quite get through, everything I do is only changing the color but I am not able to quite achieve what I want to.

Code below

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/action_search"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/navigation_menu"
        tools:layout_editor_absoluteX="8dp"
        android:background="#232323"
        app:itemTextColor="@color/PrimaryText"
        app:itemIconTint="@null"/>

Navigation Menu :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_add_expense"
        android:icon="@drawable/addincome"
        android:title="Add Income" />
    <item android:id="@+id/action_add_income"
        android:icon="@drawable/addexpense"
        android:title="Add Expense" />
</menu>

Body:
set the Icon TintList to null programatically and you will be able to show your icons without any tint.

bottomNavigationView.setItemIconTintList(null);


问:
How can WebRTC reconnect to the same peer after disconnection?
Now I am working on a peer-to-peer chatting system based on WebRTC. This system can make a pair with any person who is listening on the peer list at the same time and I have finished the basic functionanity of real-time communication in audio and video. But I have no ideas how to reconnect to the same peer if it disconnected accidentally ?</p>

答:
Put additional constraint:

1: cons.mandatory.add(new MediaConstraints.KeyValuePair("IceRestart", "true"));

Generate sdp file:

2: pc.createOffer(new WebRtcObserver(callbacks), cons);

Set resulted sdp to PeerConnection:

3: pc.setLocalDescription(new WebRtcObserver(callbacks), sdp);

4: Send it to remote peer.

So steps 2-4 are the same as for regular offer.


问:
Accessing a function inside a function from another module/file?
index.js

```<code>    import React from 'react'
    import ReactDOM from 'react-dom'
    import './index.css'
    import SquareBox from './game-buttons.js'

    const Game = () => {
      return (
        <div className="main-container">
          <i id="reset-icon" className="fas-disabled fas fa-redo-alt" onClick={() => SquareBox.resetGame}></i>
          <SquareBox />
        </div>
      )
    }

    ReactDOM.render(<Game />, document.getElementById('root'));

    export default Game;
</code>```

game-buttons.js

```<code>import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Game from './index.js'
import './index.css'

const SquareBox = () => {

    // reset game
    function resetGame () {
        console.log("Game reset");
    }

   return (
        <div>
            Testing
        </div >
    )
}

export default SquareBox
</code>```

I am new to reactJS. Trying to figure out how can I access resetGame() function inside game-buttons.js by clicking  tag icon inside index.js.

答:
you can access inner methods of class components by passing them ref
in order to do that make the squareBox component a class component and then access it properties from the parents by calling it's ref.resetGame
check out the
codesandbox

class SquareBox extends React.Component {
  constructor() {
    super();
    this.resetGame = this.resetGame.bind(this);
  }
  // reset game
  resetGame = () => {
    console.log("Game reset");
  };
  render() {
    return
Testing
;
  }
}

const Game = () => {
  let sb = React.useRef();
  return (

      <button
        id="reset-icon"
        className="fas-disabled fas fa-redo-alt"
        onClick={() => sb.current? sb.current.resetGame() : undefined}
      >
        reset
      </button>
      <SquareBox ref={sb} />

  );
}

ReactDOM.render(<Game/>, root)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='root'></div></code>```

Body:
index.js

    import React from 'react'
    import ReactDOM from 'react-dom'
    import './index.css'
    import SquareBox from './game-buttons.js'

    const Game = () => {
      return (

           SquareBox.resetGame}>
          <SquareBox />

      )
    }

    ReactDOM.render(<Game />, document.getElementById('root'));

    export default Game;

game-buttons.js

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Game from './index.js'
import './index.css'

const SquareBox = () => {

    // reset game
    function resetGame () {
        console.log("Game reset");
    }

   return (

            Testing

    )
}

export default SquareBox

I am new to reactJS. Trying to figure out how can I access resetGame() function inside game-buttons.js by clicking  tag icon inside index.js.

Body:
you can access inner methods of class components by passing them ref
in order to do that make the squareBox component a class component and then access it properties from the parents by calling it's ref.resetGame
check out the
codesandbox

class SquareBox extends React.Component {
  constructor() {
    super();
    this.resetGame = this.resetGame.bind(this);
  }
  // reset game
  resetGame = () => {
    console.log("Game reset");
  };
  render() {
    return <div>Testing</div>;
  }
}

const Game = () => {
  let sb = React.useRef();
  return (
    <div className="main-container">
      <button
        id="reset-icon"
        className="fas-disabled fas fa-redo-alt"
        onClick={() => sb.current? sb.current.resetGame() : undefined}
      >
        reset
      </button>
      <SquareBox ref={sb} />
    </div>
  );
}

ReactDOM.render(<Game/>, root)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>


问:
XAML ComboBox SelectedIndex Binding to ViewModel property
I have tried for what seems a lifetime to get this issue sorted but unfortunately to no avail.. even after searching stackoverflow and other sites.

Ill try and keep my issue short but to the point.

Using WPF and the MVVM methodology I have : A View and a ViewModel.

From within the view XAML I am binding a comboBox to a list of values in a key/value dictionary object. This works fine - I am able to see the values drop down when I click on the combo box.

Note: Each record can have more than 1 instalment in a gridview where the combobox is displayed.

```<code><dxg:GridColumn Header="Instalments"
        Width="100"
        AllowSorting="False"
        AllowAutoFilter="False">
<dxg:GridColumn.CellTemplate>
<DataTemplate>
    <ComboBox IsEnabled="{Binding Data.IsIncludedInDD}"
              Name="cbInstalmentValues"
              Width="200"
              ItemsSource="{Binding Data.D_InstalmentValues}"
              SelectedIndex="{Binding Data.Instalments, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              DisplayMemberPath="Value"
              SelectedValuePath="Key"
              SelectedValue="{Binding SelectedInstalmentValue, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"
              VerticalAlignment="Center" />
</code>```

Code:

```<code>private static readonly Dictionary<int, string> D_instalmentValues = new Dictionary<int, string>
{
  {0, "None"},
  {1, "1 Instalment"},
  {2, "2 Instalments"},
  {3, "3 Instalments"},
  {4, "4 Instalments"},
  {5, "5 Instalments"},
  {6, "6 Instalments"},
  {7, "7 Instalments"},
  {8, "8 Instalments"},
  {9, "9 Instalments"},
  {10, "10 Instalments"},
  {11, "11 Instalments"},
  {12, "12 Instalments"}
};

public Dictionary<int, string> D_InstalmentValues
{
  get
  {
    return _instalmentValues;
  }
  set
  {
    _instalmentValues = value;
  }
}
</code>```

So..when I load up my application I want the comboBox to read the value from the 'Instalments' property in the viewmodel and bind to the same index of the value in the dictionary and display the number of instalments.. ie: None, 1 Instalment etc..

```<code>public int Instalments
{
    get
    {
        return _chargeTemplate.Instalments;
    }

    set
    {
    if (value == -1)
    {
        value = value + 1;
        _chargeTemplate.Instalments = _chargeTemplate.Instalments;
    }
    else
    {
        if (_chargeTemplate.Instalments == value)
        {
            return;
        }
        else
        {
            _chargeTemplate.Instalments = value;
        }
     }
     //NotifyNotRegister("Instalments");
     RaisePropertyChanged("Instalments");
    }
}
</code>```

Now the '_chargeTemplate.Instalments' value holds the value from the Instalments column from the record in the database.

The combobox does not seem to bind if the value in the Instalments property is 0. The box is blank.

It does get populated after I select a record which has a value greater than 0.

When I tried populating all the instalment fields in the sql table with values from 1 to 12 the selected index did not get set properly for the very first record displayed in my application but if I selected the next record it was displayed ok... then if I reselected the first record again it was also displayed correctly.

Another strange part of the behaviour was for the first record, if I had 3 instalments, and in the sql table instalment 1 = 2, instalment 2 = 4 and instalment 3 = 0... the first 2 instalments for that record had their combo box index set but the last record was empty.

In summary - I need to know how, when the application loads - how to make the selected index bind from a viewmodel to the view without the combo box being blank for the first record or for values where the selected index is 0.

I hope there is enough information here...

Many Thanks

UPDATE :

I made a small change to the XAML and the property to which I am binding the combobox selectedindex. This allows the 0 value to display 'None' in the combobox where the value is 0 for a persons instalment value in the sql database.

However the very first person displayed in the list of records does not have the selectd index set to the index of the dictionary value unless I select another person and reselect the first person again... strange

ViewModel

public int Instalments
          {
              get
              {
                  return _chargeTemplate.Instalments;
              }
            }

XAML

SelectedIndex="{Binding Data.Instalments, Mode=OneWay}"

答:
I found the answer eventually after staring at the screen for a bit and realising I had left out 1 WORD!!!!

I removed the 'SelectedIndex' property from the combobox control completely and used the 'SelectedValue' instead. Also the word missing in front was 'Data.'

With a few adjustments on the properties in the viewmodel this worked a treat displaying the correct value in the combobox from the database on loading the application

See below:)

Thanks!

                                        DisplayMemberPath="Value"
                                        SelectedValuePath="Key"
                                        SelectedValue="{Binding Data.SelectedInstalmentValue, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"
                                        Style="{StaticResource ValidationStyle}"
                                        VerticalAlignment="Center" />

Body:
I have tried for what seems a lifetime to get this issue sorted but unfortunately to no avail.. even after searching stackoverflow and other sites.

Ill try and keep my issue short but to the point.

Using WPF and the MVVM methodology I have : A View and a ViewModel.

From within the view XAML I am binding a comboBox to a list of values in a key/value dictionary object. This works fine - I am able to see the values drop down when I click on the combo box.

Note: Each record can have more than 1 instalment in a gridview where the combobox is displayed.

<dxg:GridColumn Header="Instalments"
        Width="100"
        AllowSorting="False"
        AllowAutoFilter="False">
<dxg:GridColumn.CellTemplate>
<DataTemplate>
    <ComboBox IsEnabled="{Binding Data.IsIncludedInDD}"
              Name="cbInstalmentValues"
              Width="200"
              ItemsSource="{Binding Data.D_InstalmentValues}"
              SelectedIndex="{Binding Data.Instalments, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              DisplayMemberPath="Value"
              SelectedValuePath="Key"
              SelectedValue="{Binding SelectedInstalmentValue, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"
              VerticalAlignment="Center" />

Code:

private static readonly Dictionary<int, string> D_instalmentValues = new Dictionary<int, string>
{
  {0, "None"},
  {1, "1 Instalment"},
  {2, "2 Instalments"},
  {3, "3 Instalments"},
  {4, "4 Instalments"},
  {5, "5 Instalments"},
  {6, "6 Instalments"},
  {7, "7 Instalments"},
  {8, "8 Instalments"},
  {9, "9 Instalments"},
  {10, "10 Instalments"},
  {11, "11 Instalments"},
  {12, "12 Instalments"}
};

public Dictionary<int, string> D_InstalmentValues
{
  get
  {
    return _instalmentValues;
  }
  set
  {
    _instalmentValues = value;
  }
}

So..when I load up my application I want the comboBox to read the value from the 'Instalments' property in the viewmodel and bind to the same index of the value in the dictionary and display the number of instalments.. ie: None, 1 Instalment etc..

public int Instalments
{
    get
    {
        return _chargeTemplate.Instalments;
    }

    set
    {
    if (value == -1)
    {
        value = value + 1;
        _chargeTemplate.Instalments = _chargeTemplate.Instalments;
    }
    else
    {
        if (_chargeTemplate.Instalments == value)
        {
            return;
        }
        else
        {
            _chargeTemplate.Instalments = value;
        }
     }
     //NotifyNotRegister("Instalments");
     RaisePropertyChanged("Instalments");
    }
}

Now the '_chargeTemplate.Instalments' value holds the value from the Instalments column from the record in the database.

The combobox does not seem to bind if the value in the Instalments property is 0. The box is blank.

It does get populated after I select a record which has a value greater than 0.

When I tried populating all the instalment fields in the sql table with values from 1 to 12 the selected index did not get set properly for the very first record displayed in my application but if I selected the next record it was displayed ok... then if I reselected the first record again it was also displayed correctly.

Another strange part of the behaviour was for the first record, if I had 3 instalments, and in the sql table instalment 1 = 2, instalment 2 = 4 and instalment 3 = 0... the first 2 instalments for that record had their combo box index set but the last record was empty.

In summary - I need to know how, when the application loads - how to make the selected index bind from a viewmodel to the view without the combo box being blank for the first record or for values where the selected index is 0.

I hope there is enough information here...

Many Thanks

UPDATE :

I made a small change to the XAML and the property to which I am binding the combobox selectedindex. This allows the 0 value to display 'None' in the combobox where the value is 0 for a persons instalment value in the sql database.

However the very first person displayed in the list of records does not have the selectd index set to the index of the dictionary value unless I select another person and reselect the first person again... strange

ViewModel

public int Instalments
          {
              get
              {
                  return _chargeTemplate.Instalments;
              }
            }

XAML

SelectedIndex="{Binding Data.Instalments, Mode=OneWay}"


问:
Set row number for batch of N rows per category
I have table

```<code>+-----+----------+---------+
| id  | name     | phase   |
+-----+----------+---------+
| 101 | Bolt     | PHASE 1 |
| 102 | Nut      | PHASE 1 |
| 103 | Screw    | PHASE 1 |
| 104 | Hex BOLT | PHASE 1 |
| 105 | Rubber   | PHASE 1 |
| 106 | Aluminum | PHASE 2 |
| 107 | Slate    | PHASE 2 |
| 108 | Pen      | PHASE 3 |
| 109 | Pencil   | PHASE 3 |
| 110 | Mouse    | PHASE 3 |
| 111 | Keyboard | PHASE 3 |
+-----+----------+---------+
</code>```

I want to create a another column in which i have to put row number.

Logic :
For 3 rows, it should be same and change to next value for 4th row. And Whenever the PHASE is changing, it should go to next number even if the set of 3 is not complete for the previous number.

Expected Output

```<code>+-----+----------+---------+-----+
| id  | name     | phase   | SET |
+-----+----------+---------+-----+
| 101 | Bolt     | PHASE 1 | 1   |
| 102 | Nut      | PHASE 1 | 1   |
| 103 | Screw    | PHASE 1 | 1   |
| 104 | Hex BOLT | PHASE 1 | 2   |
| 105 | Rubber   | PHASE 1 | 2   |
| 106 | Aluminum | PHASE 2 | 3   |
| 107 | Slate    | PHASE 2 | 3   |
| 108 | Pen      | PHASE 3 | 4   |
| 109 | Pencil   | PHASE 3 | 4   |
| 110 | Mouse    | PHASE 3 | 4   |
| 111 | Keyboard | PHASE 3 | 5   |
+-----+----------+---------+-----+
</code>```

I have tried the below query, but it is not giving me the required output.

```<code>select *, (row_number() over (order by phase)-1) / 3 as sets
from table_main
</code>```

Actual Output:

```<code>+-----+----------+---------+------+
| id  | name     | phase   | sets |
+-----+----------+---------+------+
| 101 | Bolt     | PHASE 1 | 0    |
| 102 | Nut      | PHASE 1 | 0    |
| 103 | Screw    | PHASE 1 | 0    |
| 104 | Hex BOLT | PHASE 1 | 1    |
| 105 | Rubber   | PHASE 1 | 1    |
| 106 | Aluminum | PHASE 2 | 1    |
| 107 | Slate    | PHASE 2 | 2    |
| 108 | Pen      | PHASE 3 | 2    |
| 109 | Pencil   | PHASE 3 | 2    |
| 110 | Mouse    | PHASE 3 | 3    |
| 111 | Keyboard | PHASE 3 | 3    |
+-----+----------+---------+------+
</code>```

I have tried with DENSE_RANK() as well but not getting the expected output.

FIDDLE HERE

答:
Use LAG to get previous row value for column and if it changed then add 1. Use ROW_NUMBER() as mentioned with %3 and then sum those values like below.

```<code>;WITH tm AS (
    SELECT *,
            IIF((LAG(phase, 1) OVER (ORDER BY phase, id)) = phase, 0, 1) AS phase_change,
            IIF((ROW_NUMBER() OVER (PARTITION BY phase ORDER BY phase)-1)%3 = 0, 1, 0) AS [set]
    FROM table_main
)
SELECT id,
        name,
        phase,
        SUM(IIF([set] > phase_change, [set], phase_change)) OVER (ORDER BY phase, id) AS [set]
FROM tm
</code>```

Body:
I have table

+-----+----------+---------+
| id  | name     | phase   |
+-----+----------+---------+
| 101 | Bolt     | PHASE 1 |
| 102 | Nut      | PHASE 1 |
| 103 | Screw    | PHASE 1 |
| 104 | Hex BOLT | PHASE 1 |
| 105 | Rubber   | PHASE 1 |
| 106 | Aluminum | PHASE 2 |
| 107 | Slate    | PHASE 2 |
| 108 | Pen      | PHASE 3 |
| 109 | Pencil   | PHASE 3 |
| 110 | Mouse    | PHASE 3 |
| 111 | Keyboard | PHASE 3 |
+-----+----------+---------+

I want to create a another column in which i have to put row number.

Logic :
For 3 rows, it should be same and change to next value for 4th row. And Whenever the PHASE is changing, it should go to next number even if the set of 3 is not complete for the previous number.

Expected Output

+-----+----------+---------+-----+
| id  | name     | phase   | SET |
+-----+----------+---------+-----+
| 101 | Bolt     | PHASE 1 | 1   |
| 102 | Nut      | PHASE 1 | 1   |
| 103 | Screw    | PHASE 1 | 1   |
| 104 | Hex BOLT | PHASE 1 | 2   |
| 105 | Rubber   | PHASE 1 | 2   |
| 106 | Aluminum | PHASE 2 | 3   |
| 107 | Slate    | PHASE 2 | 3   |
| 108 | Pen      | PHASE 3 | 4   |
| 109 | Pencil   | PHASE 3 | 4   |
| 110 | Mouse    | PHASE 3 | 4   |
| 111 | Keyboard | PHASE 3 | 5   |
+-----+----------+---------+-----+

I have tried the below query, but it is not giving me the required output.

select *, (row_number() over (order by phase)-1) / 3 as sets
from table_main

Actual Output:

+-----+----------+---------+------+
| id  | name     | phase   | sets |
+-----+----------+---------+------+
| 101 | Bolt     | PHASE 1 | 0    |
| 102 | Nut      | PHASE 1 | 0    |
| 103 | Screw    | PHASE 1 | 0    |
| 104 | Hex BOLT | PHASE 1 | 1    |
| 105 | Rubber   | PHASE 1 | 1    |
| 106 | Aluminum | PHASE 2 | 1    |
| 107 | Slate    | PHASE 2 | 2    |
| 108 | Pen      | PHASE 3 | 2    |
| 109 | Pencil   | PHASE 3 | 2    |
| 110 | Mouse    | PHASE 3 | 3    |
| 111 | Keyboard | PHASE 3 | 3    |
+-----+----------+---------+------+

I have tried with DENSE_RANK() as well but not getting the expected output.

FIDDLE HERE

Body:
Use LAG to get previous row value for column and if it changed then add 1. Use ROW_NUMBER() as mentioned with %3 and then sum those values like below.

;WITH tm AS (
    SELECT *,
            IIF((LAG(phase, 1) OVER (ORDER BY phase, id)) = phase, 0, 1) AS phase_change,
            IIF((ROW_NUMBER() OVER (PARTITION BY phase ORDER BY phase)-1)%3 = 0, 1, 0) AS [set]
    FROM table_main
)
SELECT id,
        name,
        phase,
        SUM(IIF([set] > phase_change, [set], phase_change)) OVER (ORDER BY phase, id) AS [set]
FROM tm


问:
React Redux - Waiting for async api call to finish before next action is dispatched
I am working on a web app that uses React + Redux, with a backend using Django (DRF). I am using axios to send in my API request, which is asynchronous. The issue I am facing right now is that the actions dispatched do not wait for the API call to finish before the next action is dispatched. Below is my code

```<code>const mapDispatchToProps = dispatch => ({
    success: id => {
        dispatch(fetchSalesProject(id));
        dispatch(createMessage('Requirement successfully updated!'))
    }
})
</code>```

fetchSalesProject action (axiosInstance is just a custom modification of axios call, the functionality is the same)

```<code>export const fetchSalesProject = (id) => (dispatch) => {
    console.log('enter sales project action')
    axiosInstance
        .get(`/sales-project/detail/${id}/`)
        .then((res) => {
            console.log('fetched data')
            dispatch({
                type: FETCH_SALES_PROJECT,
                payload: res.data,
            });
        })
        .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};
</code>```

createMessage action

```<code>export const createMessage = (message) => {
  console.log('message')
  return {
    type: CREATE_MESSAGE,
    message: message,
  };
};
</code>```

When calling this.props.success (refer to mapDispatchToProps), the message is displayed before the api call response data is received (evident by the fact that console.log('message') runs before console.log('fetched data'))

I would want the data to be fetched from the api call before i run the createMessage action, is there any advise on how to accomplish that? I am new to React and especially Redux, so hope that you guys can point me in the right direction on how to accomplish that.

Also, can I check whether it is wrong to have a dispatch in the mapDispatchToProps, and also a dispatch within the action (refer to fetchSalesProject action). Would it cause any issues with performance or is it frowned upon to do so? Please advise me as I am quite confused with Redux.

Thanks all for reading through, all help is appreciated :-)

答:
There is a better way of doing this that does not force you combine two action creators. When your thunk action creator returns a promise then you can wait for it. Your current code did not return the axios promise but if you do return it you can do the following:\</p>

```<code>const mapDispatchToProps = (dispatch) => ({
  success: (id) => {
    dispatch(fetchSalesProject(id)).then(() =>
      dispatch(//wait for fetchSalesProject to finish
        createMessage('Requirement successfully updated!')
      )
    );
  },
});

export const fetchSalesProject = (id) => (dispatch) => {
  console.log('enter sales project action');
  return axiosInstance //you did not return anything here
    .get(`/sales-project/detail/${id}/`)
    .then((res) => {
      console.log('fetched data');
      dispatch({
        type: FETCH_SALES_PROJECT,
        payload: res.data,
      });
    })
    .catch((err) => {
      dispatch(
        returnErrors(err.response.data, err.response.status)
      );
      //return rejected promise here
      return Promise.reject(err);
    });
};
</code>```

Body:
I am working on a web app that uses React + Redux, with a backend using Django (DRF). I am using axios to send in my API request, which is asynchronous. The issue I am facing right now is that the actions dispatched do not wait for the API call to finish before the next action is dispatched. Below is my code

const mapDispatchToProps = dispatch => ({
    success: id => {
        dispatch(fetchSalesProject(id));
        dispatch(createMessage('Requirement successfully updated!'))
    }
})

fetchSalesProject action (axiosInstance is just a custom modification of axios call, the functionality is the same)

export const fetchSalesProject = (id) => (dispatch) => {
    console.log('enter sales project action')
    axiosInstance
        .get(`/sales-project/detail/${id}/`)
        .then((res) => {
            console.log('fetched data')
            dispatch({
                type: FETCH_SALES_PROJECT,
                payload: res.data,
            });
        })
        .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};

createMessage action

export const createMessage = (message) => {
  console.log('message')
  return {
    type: CREATE_MESSAGE,
    message: message,
  };
};

When calling this.props.success (refer to mapDispatchToProps), the message is displayed before the api call response data is received (evident by the fact that console.log('message') runs before console.log('fetched data'))

I would want the data to be fetched from the api call before i run the createMessage action, is there any advise on how to accomplish that? I am new to React and especially Redux, so hope that you guys can point me in the right direction on how to accomplish that.

Also, can I check whether it is wrong to have a dispatch in the mapDispatchToProps, and also a dispatch within the action (refer to fetchSalesProject action). Would it cause any issues with performance or is it frowned upon to do so? Please advise me as I am quite confused with Redux.

Thanks all for reading through, all help is appreciated :-)

Body:
There is a better way of doing this that does not force you combine two action creators. When your thunk action creator returns a promise then you can wait for it. Your current code did not return the axios promise but if you do return it you can do the following:\

const mapDispatchToProps = (dispatch) => ({
  success: (id) => {
    dispatch(fetchSalesProject(id)).then(() =>
      dispatch(//wait for fetchSalesProject to finish
        createMessage('Requirement successfully updated!')
      )
    );
  },
});

export const fetchSalesProject = (id) => (dispatch) => {
  console.log('enter sales project action');
  return axiosInstance //you did not return anything here
    .get(`/sales-project/detail/${id}/`)
    .then((res) => {
      console.log('fetched data');
      dispatch({
        type: FETCH_SALES_PROJECT,
        payload: res.data,
      });
    })
    .catch((err) => {
      dispatch(
        returnErrors(err.response.data, err.response.status)
      );
      //return rejected promise here
      return Promise.reject(err);
    });
};


问:
What is SYSNAME data type in SQL Server?
What is the SQL Server SYSNAME data type for? BOL says:

The sysname data type is used for
  table columns, variables, and stored
  procedure parameters that store object
  names.

but I don't really get that. Is there a use-case you can provide?

答:
Is there use case you can provide?

Anywhere you want to store an object name for use by database maintenance scripts.  For example, a script purges old rows from certain tables that have a date column.  It's configured with a table that gives table name, column name to filter on, and how many days of history to keep.  Another script dumps certain tables to CSV files, and again is configured with a table listing the tables to dump.  These configuration tables can use the sysname type to store table and column names.


问:
I have an issue in resolving this error. I am struggling to pass the array in the main function
```<code>#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 6

int PrintSpiral(int arr[][C], int m, int n){
    int t= 0, b = m-1, l = 0, r = n-1;
    int dir = 0;`
    while(l <= r && t <= b){
        if(dir == 0){
            for(int k = l; k <= r; k++)
                cout << arr[t][k];
            t++;
        }
        else if(dir == 1){
            for(int k = t; k <= b; k++)
                cout << arr[k][r];
            r--;
        }
        else if(dir == 2){
            for(int k = r; k >= l; k--)
                cout << arr[b][k];
            b--;
        }
        else if(dir == 3){
            for(int k = b; k >= t; k--)
                cout << arr[k][l];
            l++;
        }
        dir = (dir+1)%4;
    }
}

int main() {
    //code
    int t;
    cin>>t;
    while(t--){
        int na,ma;
        cin>>na>>ma;
        int ar[na][ma] = {{0}};
        for(int i = 0; i < na; i++){
            for(int j = 0; j < ma; j++){
                cin>>ar[i][j];
            }
        }
        PrintSpiral(ar,na,ma);
    }
    return 0;
}
</code>```

I am getting this error:

```<code>Spiral_matrix.cpp: In function 'int main()':<br/>
Spiral_matrix.cpp:47:18: error: cannot convert 'int (*)[ma]' to 'int (*)[6]'
      PrintSpiral(ar,na,ma);
                  ^~
Spiral_matrix.cpp:6:21: note:   initializing argument 1 of 'int PrintSpiral(int (*)[6], int, int)'
 int PrintSpiral(int arr[][C], int m, int n){
</code>```

enter image description here

Error Resolving the issue. Kindly look into it
The above code prints the given 2-D matrix into
Spiral form
I applied arr[][6] with random value and also i predefined column as C
and updated it again with arr[][C] still it shows an error
Apart from this i even used the value of R and C in my main function
Still it shows an error
I want a way in which i could pass my function successfully in the main function.

答:
Here's your code rewritten to use vectors instead of variable length arrays. I've omitted that parts that don't need changing (which is most of it)

```<code>#include <iostream>
#include <vector>
using namespace std;

void PrintSpiral(const vector<vector<int>>& arr){
    if (arr.size() == 0) return;
    int t= 0, b = arr.size()-1, l = 0, r = arr[0].size()-1;
    ...
}

int main() {
    ...
        int na,ma;
        cin>>na>>ma;
        vector<vector<int>> arr(na, vector<int>(ma));
        ...
        PrintSpiral(arr);
    ...
    return 0;
}
</code>```

The sooner you learn about modern C++ (std::vector is over 20 years old), the faster your progress will be. Don't program C++ as if you're still in the last millennium.

Body:
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 6

int PrintSpiral(int arr[][C], int m, int n){
    int t= 0, b = m-1, l = 0, r = n-1;
    int dir = 0;`
    while(l <= r && t <= b){
        if(dir == 0){
            for(int k = l; k <= r; k++)
                cout << arr[t][k];
            t++;
        }
        else if(dir == 1){
            for(int k = t; k <= b; k++)
                cout << arr[k][r];
            r--;
        }
        else if(dir == 2){
            for(int k = r; k >= l; k--)
                cout << arr[b][k];
            b--;
        }
        else if(dir == 3){
            for(int k = b; k >= t; k--)
                cout << arr[k][l];
            l++;
        }
        dir = (dir+1)%4;
    }
}

int main() {
    //code
    int t;
    cin>>t;
    while(t--){
        int na,ma;
        cin>>na>>ma;
        int ar[na][ma] = {{0}};
        for(int i = 0; i < na; i++){
            for(int j = 0; j < ma; j++){
                cin>>ar[i][j];
            }
        }
        PrintSpiral(ar,na,ma);
    }
    return 0;
}

I am getting this error:

Spiral_matrix.cpp: In function 'int main()':

Spiral_matrix.cpp:47:18: error: cannot convert 'int (*)[ma]' to 'int (*)[6]'
      PrintSpiral(ar,na,ma);
                  ^~
Spiral_matrix.cpp:6:21: note:   initializing argument 1 of 'int PrintSpiral(int (*)[6], int, int)'
 int PrintSpiral(int arr[][C], int m, int n){

enter image description here

Error Resolving the issue. Kindly look into it
The above code prints the given 2-D matrix into
Spiral form
I applied arr[][6] with random value and also i predefined column as C
and updated it again with arr[][C] still it shows an error
Apart from this i even used the value of R and C in my main function
Still it shows an error
I want a way in which i could pass my function successfully in the main function.

Body:
Here's your code rewritten to use vectors instead of variable length arrays. I've omitted that parts that don't need changing (which is most of it)

#include <iostream>
#include <vector>
using namespace std;

void PrintSpiral(const vector<vector<int>>& arr){
    if (arr.size() == 0) return;
    int t= 0, b = arr.size()-1, l = 0, r = arr[0].size()-1;
    ...
}

int main() {
    ...
        int na,ma;
        cin>>na>>ma;
        vector<vector<int>> arr(na, vector<int>(ma));
        ...
        PrintSpiral(arr);
    ...
    return 0;
}

The sooner you learn about modern C++ (std::vector is over 20 years old), the faster your progress will be. Don't program C++ as if you're still in the last millennium.


问:
Owin provide startup class in web.config (no automatic startup discovery)
I try to do the following in my web.config:

```<code><appSettings>
   <add key="owin:AutomaticAppStartup" value="false" />
   <add key="owin:appStartup" value="MyNamespace.MyStartupClass" />
</appSettings>
</code>```

If I understand this documentation correctly automatic startup detection should be disabled. So I do not require a startup attribute.

Unfortunately it looks like OWIN does not start. (I see this because I get the error: HTTP Error 403.14 - Forbidden. I use a controller to handle requests to the index file.)

if I use <add key="owin:AutomaticAppStartup" value="true" /> and add the startup attribute [assembly: OwinStartup(typeof(MyStartupClass))] then the application does startup as expected.

So the question is why? What can I do to resolve the issue?

I am using OWIN 3.0.0.0

Update:

This is how my startup class looks like (minified version with relevant parts):

```<code>using System.Web.Http;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
using MyOtherNamespace;

namespace MyNamespace
{
    public class MyOnlineStartup : MyOtherStartup
    {
        public new void Configuration(IAppBuilder app)
        {
            base.Configuration(app); //Call base method! This is important because otherwise ther serilization will not be correct
            HttpConfiguration config = CreateRouting();
            config.Routes.MapHttpRoute("exampleAppNone", "", new { controller = "MyIndex" }, null, null);
            config.Routes.MapHttpRoute("exampleAppIndex", "index.html", new { controller = "MyIndex" }, null, null);
            app.UseWebApi(config); // Use the WebAPI technology.
        }
    }
}
</code>```

it derives from

```<code>using System.Linq;
using System.Web.Http;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Owin;

namespace MyOtherNamespace
{
    public class MyOtherStartup
    {
        protected static HttpConfiguration CreateMyRouting()
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                "myIndex",
                "my/",
                new
                {
                    controller = "MyIndex"
                },
                null,
                null
                );
            config.Routes.MapHttpRoute(
                "myIndex2",
                "my/index.html",
                new
                {
                    controller = "MyIndex"
                },
                null,
                null
                );
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
            config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto
            return config;
        }

        public void Configuration(IAppBuilder app)
        {
            JsonSerializer serializer = Serialization.ClientJsonSerializer();
            serializer.ContractResolver = new MySerializationContractResolver(false);
            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
            app.MapSignalR("/" + MyRequestHandler.MySignalRPath, new HubConfiguration());
        }
    }
}
</code>```

答:
Sometimes if you rename your project name then also you can get this error. Please make sure to rename your assembly info & please check your project properties also. Right Click on your Project => Go To Properties => Verify your assembly name and project name.

For me this solved my issue with OWIN library.

Project Properties Assembly Name Change

Body:
I try to do the following in my web.config:

<appSettings>
   <add key="owin:AutomaticAppStartup" value="false" />
   <add key="owin:appStartup" value="MyNamespace.MyStartupClass" />
</appSettings>

If I understand this documentation correctly automatic startup detection should be disabled. So I do not require a startup attribute.

Unfortunately it looks like OWIN does not start. (I see this because I get the error: HTTP Error 403.14 - Forbidden. I use a controller to handle requests to the index file.)

if I use <add key="owin:AutomaticAppStartup" value="true" /> and add the startup attribute [assembly: OwinStartup(typeof(MyStartupClass))] then the application does startup as expected.

So the question is why? What can I do to resolve the issue?

I am using OWIN 3.0.0.0

Update:

This is how my startup class looks like (minified version with relevant parts):

using System.Web.Http;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
using MyOtherNamespace;

namespace MyNamespace
{
    public class MyOnlineStartup : MyOtherStartup
    {
        public new void Configuration(IAppBuilder app)
        {
            base.Configuration(app); //Call base method! This is important because otherwise ther serilization will not be correct
            HttpConfiguration config = CreateRouting();
            config.Routes.MapHttpRoute("exampleAppNone", "", new { controller = "MyIndex" }, null, null);
            config.Routes.MapHttpRoute("exampleAppIndex", "index.html", new { controller = "MyIndex" }, null, null);
            app.UseWebApi(config); // Use the WebAPI technology.
        }
    }
}

it derives from

using System.Linq;
using System.Web.Http;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Owin;

namespace MyOtherNamespace
{
    public class MyOtherStartup
    {
        protected static HttpConfiguration CreateMyRouting()
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                "myIndex",
                "my/",
                new
                {
                    controller = "MyIndex"
                },
                null,
                null
                );
            config.Routes.MapHttpRoute(
                "myIndex2",
                "my/index.html",
                new
                {
                    controller = "MyIndex"
                },
                null,
                null
                );
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
            config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto
            return config;
        }

        public void Configuration(IAppBuilder app)
        {
            JsonSerializer serializer = Serialization.ClientJsonSerializer();
            serializer.ContractResolver = new MySerializationContractResolver(false);
            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
            app.MapSignalR("/" + MyRequestHandler.MySignalRPath, new HubConfiguration());
        }
    }
}


问:
Add specific scala file to the build.sbt not all the directory it is in
so I have a git sub-module that I want to include some Scala files from in my project but I don't want to include the a whole directory just some specific Scala files who to change the following line or what to add in order to include some specific Scala files to the build.sbt</p>

```<code>  unmanagedSourceDirectories in Compile ++=  addons.value.map(baseDirectory.value / _ /"")
</code>```

答:
Remove command unmanagedSourceDirectories in Compile ++= ... and add command

```<code>sources in Compile ++= Seq("SpecificFile1.scala", "SpecificFile2.scala")
  .map(baseDirectory.value / "external_directory" / _)
</code>```

if you want to add only external_directory/SpecificFile1.scala, external_directory/SpecificFile2.scala.

Or keep command unmanagedSourceDirectories in Compile += baseDirectory.value / "external_directory" and add command

```<code>sources in Compile --= Seq("ExcludedSpecificFile1.scala", "ExcludedSpecificFile2.scala")
  .map(baseDirectory.value / "external_directory" / _)
</code>```

if you want to add everything from external_directory except external_directory/ExcludedSpecificFile1.scala, external_directory/ExcludedSpecificFile2.scala.

Body:
so I have a git sub-module that I want to include some Scala files from in my project but I don't want to include the a whole directory just some specific Scala files who to change the following line or what to add in order to include some specific Scala files to the build.sbt

  unmanagedSourceDirectories in Compile ++=  addons.value.map(baseDirectory.value / _ /"")

Body:
Remove command unmanagedSourceDirectories in Compile ++= ... and add command

sources in Compile ++= Seq("SpecificFile1.scala", "SpecificFile2.scala")
  .map(baseDirectory.value / "external_directory" / _)

if you want to add only external_directory/SpecificFile1.scala, external_directory/SpecificFile2.scala.

Or keep command unmanagedSourceDirectories in Compile += baseDirectory.value / "external_directory" and add command

sources in Compile --= Seq("ExcludedSpecificFile1.scala", "ExcludedSpecificFile2.scala")
  .map(baseDirectory.value / "external_directory" / _)

if you want to add everything from external_directory except external_directory/ExcludedSpecificFile1.scala, external_directory/ExcludedSpecificFile2.scala.


问:
Powershell Extract ip's from string
I would like to get from the user 2 variables:
$ip1
$ip2

and run a loop between their IP address. for example:

```<code>$ip1 = 192.168.1.10
$ip2 = 192.168.1.200
</code>```

The script assume its a class C, the i need to strip everything and get 3 variables:

```<code>$IP = 192.168.1.
$FirstIP = 10
$LastIp = 200
</code>```

At first i thought about substring ($ip.length - 3), that could give me XXX, .XX, X.X (Where X is a number) Depends on the last Octat..
Any idea how can it be done nicely?

答:
You could split the string by dot and use range operator to create an array from last elements:

$ip1.Split('.')[-1]..$ip2.Split('.')[-1] | foreach{$_}

Title: Powershell Extract ip's from string

Body:
I would like to get from the user 2 variables:
$ip1
$ip2

and run a loop between their IP address. for example:

$ip1 = 192.168.1.10
$ip2 = 192.168.1.200

The script assume its a class C, the i need to strip everything and get 3 variables:

$IP = 192.168.1.
$FirstIP = 10
$LastIp = 200

At first i thought about substring ($ip.length - 3), that could give me XXX, .XX, X.X (Where X is a number) Depends on the last Octat..
Any idea how can it be done nicely?


问:
What is the difference between header file and namespace?
I want to know the exact difference between Header file (as in MyHeader.hpp) and a namespace in c++?

答: Namespace is new word given to headerfile. To make new versions avaiable. </p>


问:
typescript: how to prevent emitting code with errors?
There is a common misconception that "Typescript is a superset of Javascript".

This is not true, here are two simple examples where valid Javascript causes the Typescript compiler to report an error:

```<code>var a = { foo: 1 };
a.bar = 2; // member does not exist on a

console.log(1 == "1"); // comparison of incompatible types
</code>```

In many cases where it reports an error, the Typescript compiler will still output Javascript. For the examples above, this might make sense. It can support an easier incremental migration to sound static typing.

However, there are also cases where the Typescript compiler catches errors that should be treated as errors and might cause dangerously unspecified behaviour in your Javascript program. For example, in ES6, module exports are read-only. You should not be able to write to exported members of a module. As of the time of this writing, node v13.14.0. does not enforce this.

module.ts:

```<code>export var num = 1;

// just as a reference, the proper way to access num
export const setNum = (newNum:number)=>{
    num=newNum;
}
export const getNum = ()=>num;
</code>```

main.ts:

```<code>import * as mod from './mod'

console.log(mod.num); // outputs 1
mod.num=2;            // compiler error
console.log(mod.num); // outputs 2
</code>```

Despite throwing an error, the compiler still transpiles to Javascript and ignores the dangerous "write to read-only".

In such a scenario, I would like to prevent the compiler from producing output. How is this possible?

答:
The typescript compiler options make it possible to specify:

```<code> --noEmitOnError
</code>```

By default this flag is set to false. But after running into a nasty side-effect of faulty code being emitted, I will always set this to true in my tsconfig.json:

```<code>{
    "compilerOptions": {
        //...
        "strict": true,
        "noEmitOnError": true
    },
    "exclude": [
        "node_modules"
    ]
}
</code>```

Body:
There is a common misconception that "Typescript is a superset of Javascript".

This is not true, here are two simple examples where valid Javascript causes the Typescript compiler to report an error:

var a = { foo: 1 };
a.bar = 2; // member does not exist on a

console.log(1 == "1"); // comparison of incompatible types

In many cases where it reports an error, the Typescript compiler will still output Javascript. For the examples above, this might make sense. It can support an easier incremental migration to sound static typing.

However, there are also cases where the Typescript compiler catches errors that should be treated as errors and might cause dangerously unspecified behaviour in your Javascript program. For example, in ES6, module exports are read-only. You should not be able to write to exported members of a module. As of the time of this writing, node v13.14.0. does not enforce this.

module.ts:

export var num = 1;

// just as a reference, the proper way to access num
export const setNum = (newNum:number)=>{
    num=newNum;
}
export const getNum = ()=>num;

main.ts:

import * as mod from './mod'

console.log(mod.num); // outputs 1
mod.num=2;            // compiler error
console.log(mod.num); // outputs 2

Despite throwing an error, the compiler still transpiles to Javascript and ignores the dangerous "write to read-only".

In such a scenario, I would like to prevent the compiler from producing output. How is this possible?

Body:
The typescript compiler options make it possible to specify:

 --noEmitOnError

By default this flag is set to false. But after running into a nasty side-effect of faulty code being emitted, I will always set this to true in my tsconfig.json:

{
    "compilerOptions": {
        //...
        "strict": true,
        "noEmitOnError": true
    },
    "exclude": [
        "node_modules"
    ]
}


问:
How can I center a splash image and text below that in Android?
I have a splash screen looking like this. How can I change the XAML so that the image and the text are moved up.  Currently they are in the area surrounded by the red outline and I would like to move them up to the area surrounded by the blue outline?

```<code><ImageView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/splash_image"
    android:layout_gravity="center"
    android:layout_marginBottom="20.0dp"
   />

<TextView
    android:id="@+id/txtAppVersion"
    android:text="XXX"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:textSize="30sp"
    android:layout_gravity="center"
    android:layout_marginBottom="100.0dp"/>
</code>```

答:
Try this

```<code> <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_marginBottom="100.0dp"
        android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/splash_image"
        android:layout_gravity="center"
        />

    <TextView
        android:id="@+id/txtAppVersion"
        android:text="XXX"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="30sp"
        android:layout_gravity="center"
        />

    </LinearLayout>
</code>```

You can always increase the margin-bottom of that linear layout which is currently 100.00dp

Body:
I have a splash screen looking like this. How can I change the XAML so that the image and the text are moved up.  Currently they are in the area surrounded by the red outline and I would like to move them up to the area surrounded by the blue outline?

<ImageView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/splash_image"
    android:layout_gravity="center"
    android:layout_marginBottom="20.0dp"
   />

<TextView
    android:id="@+id/txtAppVersion"
    android:text="XXX"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:textSize="30sp"
    android:layout_gravity="center"
    android:layout_marginBottom="100.0dp"/>

Body:
Try this

 <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_marginBottom="100.0dp"
        android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/splash_image"
        android:layout_gravity="center"
        />

    <TextView
        android:id="@+id/txtAppVersion"
        android:text="XXX"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="30sp"
        android:layout_gravity="center"
        />

    </LinearLayout>

You can always increase the margin-bottom of that linear layout which is currently 100.00dp


问:
React Native modal is not updated when Redux state is changed using hooks
I have a modal component in my React Native mobile app. It receives an array of objects from Redux state. I can delete a specific item in the array using dispatching an action using useDispatch hook. However, after sending the delete action, the component state is not updated automatically, so that I have to reopen the modal every time to see the updated list.

How can I set the modal to automatically re-render when the redux state is changed using dispatch?

SelectedItems.js

const SelectedItems = () => {
  const vegetables = useSelector(state => state.new_order.vegetables)

  return (
<Modal visible={isVisible}>
  {vegetables.map( (v,index) =>
     <VegeItem
      key={index}
      index={index}
      name={v.name}
      qty={v.qty}
      metric={v.metric}
      removeItem={(index) => {
        dispatch({
          type: 'DELETE_VEGE',
          id: index
        })
      }}
   />)}
 </View>
</Modal>
  )
}
```
<p><strong>newOrderReducer.js</strong></p>
<pre class="lang-js prettyprint-override"><code>  const newOrderReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      case 'ADD_VEGE':
        let updatedList = [...state.vegetables,action.vege]
        return {
          ...state,
          vegetables: updatedList
        }
      case 'DELETE_VEGE':
        let newVegeList = state.vegetables
        newVegeList.splice(action.id,1)
        return {
            ...state,
            vegetables: newVegeList
        }
      default:
        return state
    }
  };
</code>```

答:
while doing like so let newVegeList = state.vegetables, newVegeList is just a pointer on your state and not a shallow copy of it. Therefore, you still can't mutate it as you can't mutate state outside the return part of the reducer.

so you can do like let newVegeList = [...state.vegetables], or directly at the return

```<code>    return {
        ...state,
        vegetables: state.vegetables.filter((veg, i) => i != action.id)
    }
</code>```

you can also send veg name or whatever and modify the checker at filter

Body:
I have a modal component in my React Native mobile app. It receives an array of objects from Redux state. I can delete a specific item in the array using dispatching an action using useDispatch hook. However, after sending the delete action, the component state is not updated automatically, so that I have to reopen the modal every time to see the updated list.

How can I set the modal to automatically re-render when the redux state is changed using dispatch?

SelectedItems.js

const SelectedItems = () => {
  const vegetables = useSelector(state => state.new_order.vegetables)

  return (
<Modal visible={isVisible}>
  {vegetables.map( (v,index) =>
     <VegeItem
      key={index}
      index={index}
      name={v.name}
      qty={v.qty}
      metric={v.metric}
      removeItem={(index) => {
        dispatch({
          type: 'DELETE_VEGE',
          id: index
        })
      }}
   />)}
 </View>
</Modal>
  )
}

newOrderReducer.js

  const newOrderReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      case 'ADD_VEGE':
        let updatedList = [...state.vegetables,action.vege]
        return {
          ...state,
          vegetables: updatedList
        }
      case 'DELETE_VEGE':
        let newVegeList = state.vegetables
        newVegeList.splice(action.id,1)
        return {
            ...state,
            vegetables: newVegeList
        }
      default:
        return state
    }
  };

Body:
while doing like so let newVegeList = state.vegetables, newVegeList is just a pointer on your state and not a shallow copy of it. Therefore, you still can't mutate it as you can't mutate state outside the return part of the reducer.

so you can do like let newVegeList = [...state.vegetables], or directly at the return

    return {
        ...state,
        vegetables: state.vegetables.filter((veg, i) => i != action.id)
    }

you can also send veg name or whatever and modify the checker at filter


问:
Force a WPF control to refresh?
We have two textBlocks like this: (we used .NET FW 3.0)

```<code><TextBlock Grid.Column="0" Name="tabName" Style="{StaticResource textBlockBarStyle}" HorizontalAlignment="Left">
  <TextBlock.Margin>
      <Binding Converter="{StaticResource dpiConverter}">
          <Binding.ConverterParameter>
               <Thickness Left="3" Top="6" Right="0" Bottom="0"/>
          </Binding.ConverterParameter>
      </Binding>
  </TextBlock.Margin>
</TextBlock>
</code>```

and

```<code><TextBox  x:Name="txtBoxHelp"
          IsReadOnly="True" Style="{DynamicResource txtBoxHelpStyle}"
          IsTabStop="False"
          Text="some text" MouseLeftButtonDown="txtBoxHelp_MouseLeftButtonDown">
     <TextBox.Margin>
        <Binding Converter="{StaticResource dpiConverter}">
            <Binding.ConverterParameter>
                 <Thickness Left="7" Top="0" Right="0" Bottom="0"/>
            </Binding.ConverterParameter>
        </Binding>
     </TextBox.Margin>
</TextBox>
</code>```

These two textBlocks work well on other OS-es, but sometimes miss on the Windows XP Home Version with SP3. We have tried many ways to refresh these, but failed.

We tried:

UpdateLayout

InvalidateVisual

Changed the set Text property in code to binding mode.

How to force these controls to refresh?

答:
This works for us without the need to create a new thread. It schedules the action to start when all of the bindings have updated themselves first.</p>

```<code>           Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new Action(() =>
                    {
                        // Do something here.
                    }));
</code>```

Title: Force a WPF control to refresh?

Body:
We have two textBlocks like this: (we used .NET FW 3.0)

<TextBlock Grid.Column="0" Name="tabName" Style="{StaticResource textBlockBarStyle}" HorizontalAlignment="Left">
  <TextBlock.Margin>
      <Binding Converter="{StaticResource dpiConverter}">
          <Binding.ConverterParameter>
               <Thickness Left="3" Top="6" Right="0" Bottom="0"/>
          </Binding.ConverterParameter>
      </Binding>
  </TextBlock.Margin>
</TextBlock>

and

<TextBox  x:Name="txtBoxHelp"
          IsReadOnly="True" Style="{DynamicResource txtBoxHelpStyle}"
          IsTabStop="False"
          Text="some text" MouseLeftButtonDown="txtBoxHelp_MouseLeftButtonDown">
     <TextBox.Margin>
        <Binding Converter="{StaticResource dpiConverter}">
            <Binding.ConverterParameter>
                 <Thickness Left="7" Top="0" Right="0" Bottom="0"/>
            </Binding.ConverterParameter>
        </Binding>
     </TextBox.Margin>
</TextBox>

These two textBlocks work well on other OS-es, but sometimes miss on the Windows XP Home Version with SP3. We have tried many ways to refresh these, but failed.

We tried:

UpdateLayout

InvalidateVisual

Changed the set Text property in code to binding mode.

How to force these controls to refresh?

Body:
This works for us without the need to create a new thread. It schedules the action to start when all of the bindings have updated themselves first.

           Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new Action(() =>
                    {
                        // Do something here.
                    }));


问:
Boolean and for loop JAVA
```<code>int a=25:
for (double i=1;i<=a;i++)
{
    int b=5*i;
    boolean value= b==a;
    System.out.println(value);
 }
</code>```

This method is true when i=5 but false otherwise. So the value can be true at i=5 but my program will print for me : false-false-false-false-TRUE-false-false-false... how can I make this program to print just TRUE for me. PS: I know that false or false or TRUE or false = True.. but how can I use it in the for loop?

答:
```<code>      int a = 25;
    for (double i = 1; i <= a; i++) {
        double b = 5 * i;
        if (b == a) {
            boolean value = b == a;
            System.out.println(value);
        }
    }
</code>```

This will work

Title: Boolean and for loop JAVA

Body:
int a=25:
for (double i=1;i<=a;i++)
{
    int b=5*i;
    boolean value= b==a;
    System.out.println(value);
 }

This method is true when i=5 but false otherwise. So the value can be true at i=5 but my program will print for me : false-false-false-false-TRUE-false-false-false... how can I make this program to print just TRUE for me. PS: I know that false or false or TRUE or false = True.. but how can I use it in the for loop?

Body:
      int a = 25;
    for (double i = 1; i <= a; i++) {
        double b = 5 * i;
        if (b == a) {
            boolean value = b == a;
            System.out.println(value);
        }
    }

This will work


问:
Are lock and unlock on the same mutex sequential consistent?
For mutex lock(), the standard mentions:

Prior unlock() operations on the same mutex synchronize-with (as defined in std::memory_order) this operation.

This answer tries to explain what synchronize-with means according to the standard. However, looks like the definition is not clearly specified.

My main question is, can I ever get this output:

```<code>x: 1
y: 2
</code>```

for the following code due to memory reordering in thread A? Is the write on x in A guaranteed to be observed by B if B locks after A unlocks?

```<code>std::mutex mutex;
int x = 0, y = 0;

int main() {
  std::thread A{[] {
    x = 1;
    std::lock_guard<std::mutex> lg(std::mutex);
    y = 0;
  }};
  std::thread B{[] {
    std::lock_guard<std::mutex> lg(std::mutex);
    y = x + 2;
  }};

  A.join();
  B.join();
  std::cout << "x: " << x << std::endl;
  std::cout << "y: " << y << std::endl;
}
</code>```

If not, based on what section of the standard?
In other words, can we assume there is sequential consistency between lock/unlock?

I have also seen this related question but it is for separate mutexes.

答:
The synchronize-with relation is clearly defined. The standard states the following:

Certain library calls synchronize with other library calls performed by another thread. For example, an atomic store-release synchronizes with a load-acquire that takes its value from the store. [...] [ Note: The specifications of the synchronization operations define when one reads the value written by another. For atomic objects, the definition is clear. All operations on a given mutex occur in a single total order. Each mutex acquisition "reads the value written" by the last mutex release. — end note ]

And further:

An atomic operation A that performs a release operation on an atomic object M synchronizes with an atomic operation B that performs an acquire operation on M and takes its value from any side effect in the release
  sequence headed by A.

So in other words, if an acquire operation A "sees" the value stored by a release operation B, then A synchronizes-with B.

Consider a spin-lock where you only need a single atomic bool flag. All operations operate on that flag. In order to acquire the lock you have set the flag with an atomic read-modify-write operation. All modifications on an atomic object are totally ordered by the modification order, and it is guaranteed that a RMW operation always reads the last value (in the modification order) written before the write associated with that RMW operation.

Due to this guarantee, it is sufficient to use acquire/release semantics for the lock/unlock operations, because a successful lock operation always "sees" the value written by the previous unlock.

Regarding your question:

Is the write on x in A guaranteed to be observed by B if B locks after A unlocks?

The important part is the "if B locks after A unlocks"! If that is guaranteed, then yes, B's lock operation synchronizes-with A's unlock, thereby establishing a happens-before relation. Thus B will observe A's write. However, your code does not provide the guarantee that B locks after A, so you have a potential data race which would result in undefined behavior as correctly pointed out by @ReinstateMonica.

Update

The write to x is sequenced-before A's unlock. It doesn't matter whether the operation is outside (before) the mutex or not. In fact, theoretically the compiler could reorder the operation so that it ends up inside the mutex (though this is rather unlikely). Sequenced-before is also part of the happens-before definition, so we have the following:

```<code>std::thread A{[] {
    x = 1; // a
    std::lock_guard<std::mutex> lg(std::mutex);
    y = 0;
    // implicit unlock: b
  }};
  std::thread B{[] {
    std::lock_guard<std::mutex> lg(std::mutex); // c
    y = x + 2;
  }};
</code>```

Assuming that B locks after A unlocks we have:

a is sequenced-before b -> a happens-before b

b synchronizes-with c -> b happens-before c

And since the happens-before relation is transitive it follows that a happens-before c. So yes, this is true for all operations that are sequenced before A's unlock - regardless whether they are inside the lock or not.

Body:
For mutex lock(), the standard mentions:

Prior unlock() operations on the same mutex synchronize-with (as defined in std::memory_order) this operation.

This answer tries to explain what synchronize-with means according to the standard. However, looks like the definition is not clearly specified.

My main question is, can I ever get this output:

x: 1
y: 2

for the following code due to memory reordering in thread A? Is the write on x in A guaranteed to be observed by B if B locks after A unlocks?

std::mutex mutex;
int x = 0, y = 0;

int main() {
  std::thread A{[] {
    x = 1;
    std::lock_guard<std::mutex> lg(std::mutex);
    y = 0;
  }};
  std::thread B{[] {
    std::lock_guard<std::mutex> lg(std::mutex);
    y = x + 2;
  }};

  A.join();
  B.join();
  std::cout << "x: " << x << std::endl;
  std::cout << "y: " << y << std::endl;
}

If not, based on what section of the standard?
In other words, can we assume there is sequential consistency between lock/unlock?

I have also seen this related question but it is for separate mutexes.

Body:
The synchronize-with relation is clearly defined. The standard states the following:

Certain library calls synchronize with other library calls performed by another thread. For example, an atomic store-release synchronizes with a load-acquire that takes its value from the store. [...] [ Note: The specifications of the synchronization operations define when one reads the value written by another. For atomic objects, the definition is clear. All operations on a given mutex occur in a single total order. Each mutex acquisition "reads the value written" by the last mutex release. — end note ]

And further:

An atomic operation A that performs a release operation on an atomic object M synchronizes with an atomic operation B that performs an acquire operation on M and takes its value from any side effect in the release
  sequence headed by A.

So in other words, if an acquire operation A "sees" the value stored by a release operation B, then A synchronizes-with B.

Consider a spin-lock where you only need a single atomic bool flag. All operations operate on that flag. In order to acquire the lock you have set the flag with an atomic read-modify-write operation. All modifications on an atomic object are totally ordered by the modification order, and it is guaranteed that a RMW operation always reads the last value (in the modification order) written before the write associated with that RMW operation.

Due to this guarantee, it is sufficient to use acquire/release semantics for the lock/unlock operations, because a successful lock operation always "sees" the value written by the previous unlock.

Regarding your question:

Is the write on x in A guaranteed to be observed by B if B locks after A unlocks?

The important part is the "if B locks after A unlocks"! If that is guaranteed, then yes, B's lock operation synchronizes-with A's unlock, thereby establishing a happens-before relation. Thus B will observe A's write. However, your code does not provide the guarantee that B locks after A, so you have a potential data race which would result in undefined behavior as correctly pointed out by @ReinstateMonica.

Update

The write to x is sequenced-before A's unlock. It doesn't matter whether the operation is outside (before) the mutex or not. In fact, theoretically the compiler could reorder the operation so that it ends up inside the mutex (though this is rather unlikely). Sequenced-before is also part of the happens-before definition, so we have the following:

std::thread A{[] {
    x = 1; // a
    std::lock_guard<std::mutex> lg(std::mutex);
    y = 0;
    // implicit unlock: b
  }};
  std::thread B{[] {
    std::lock_guard<std::mutex> lg(std::mutex); // c
    y = x + 2;
  }};

Assuming that B locks after A unlocks we have:

a is sequenced-before b -> a happens-before b

b synchronizes-with c -> b happens-before c

And since the happens-before relation is transitive it follows that a happens-before c. So yes, this is true for all operations that are sequenced before A's unlock - regardless whether they are inside the lock or not.


问:
Error sending a single delete in movilizer
I'm sending a delete operation to Movilizer with only a key and the pool but it gives me this error:

Cannot delete primary group (Do not set group in delete command to delete entire entry)

Why?

答: It was because I wasn't updating my ACK. This error ocurred before and I was getting it because of the ACK. Thanks.</p>