问:
Error during Angular-cli installation
Downloading binary from https://github.com/sass/node-sass/releases/download/v4.5.0/linux-x64-51_binding.node
Cannot download "https://github.com/sass/node-sass/releases/download/v4.5.0/linux-x64-51_binding.node":

ESOCKETTIMEDOUT

Hint: If github.com is not accessible in your location
      try setting a proxy via HTTP_PROXY, e.g.

```<code>  export HTTP_PROXY=http://example.com:1234
</code>```

or configure npm proxy via

```<code>  npm config set proxy http://example.com:8080
</code>```

node-sass@4.5.0 postinstall /usr/lib/node_modules/angular-cli/node_modules/node-sass
  node scripts/build.js

Binary found at /usr/lib/node_modules/angular-cli/node_modules/node-sass/vendor/linux-x64-51/binding.node
Testing binary
Bus error (core dumped)
/usr/lib
└── (empty)

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/angular-cli/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN @angular/core@2.4.8 requires a peer of rxjs@^5.0.1 but none was installed.
npm ERR! Linux 4.4.0-64-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "angular-cli"
npm ERR! node v7.4.0
npm ERR! npm  v4.0.5
npm ERR! code ELIFECYCLE

npm ERR! node-sass@4.5.0 postinstall: node scripts/build.js
npm ERR! Exit status 135
npm ERR!
npm ERR! Failed at the node-sass@4.5.0 postinstall script 'node scripts/build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node scripts/build.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs node-sass
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.

答:
It looks like you are behind a proxy, you should get binairy locally and tell npm where it is located:

See https://github.com/sass/node-sass#binary-configuration-parameters

Easiest is to download the file to your disk and tell npm where it is

Title: Error during Angular-cli installation

Body:
Downloading binary from https://github.com/sass/node-sass/releases/download/v4.5.0/linux-x64-51_binding.node
Cannot download "https://github.com/sass/node-sass/releases/download/v4.5.0/linux-x64-51_binding.node":

ESOCKETTIMEDOUT

Hint: If github.com is not accessible in your location
      try setting a proxy via HTTP_PROXY, e.g.

  export HTTP_PROXY=http://example.com:1234

or configure npm proxy via

  npm config set proxy http://example.com:8080

node-sass@4.5.0 postinstall /usr/lib/node_modules/angular-cli/node_modules/node-sass
  node scripts/build.js

Binary found at /usr/lib/node_modules/angular-cli/node_modules/node-sass/vendor/linux-x64-51/binding.node
Testing binary
Bus error (core dumped)
/usr/lib
└── (empty)

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/angular-cli/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN @angular/core@2.4.8 requires a peer of rxjs@^5.0.1 but none was installed.
npm ERR! Linux 4.4.0-64-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "angular-cli"
npm ERR! node v7.4.0
npm ERR! npm  v4.0.5
npm ERR! code ELIFECYCLE

npm ERR! node-sass@4.5.0 postinstall: node scripts/build.js
npm ERR! Exit status 135
npm ERR!
npm ERR! Failed at the node-sass@4.5.0 postinstall script 'node scripts/build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node scripts/build.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs node-sass
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.


来源: stackexchange

问:
XSD Schema Validation seems to ignore required Attributes
I'm using XmlReader to validate my XMLfiles against my XSD schema file and it is working with one exception: It is not reporting missing required Attributes.

It does, however, report Attributes that do not conform to the XSD (name spelled wrong, disallowed contents)

For example, both of these will validate without a warning, even though both Attributes are required:

```<code><Margin Units="IN">
<Margin Units="IN" Center="true">
</code>```

Yet these will throw a warning (where Units is an Enum and Center is a Boolean):

```<code><Margin Units="IN" Center="123">
<Margin Units="abc" Center="123">
</code>```

To make matters more confusing (for me) the same files and conditions will fail validation using Notepad++ plugin "XML Tools", and will fail using XMLSpy.

It seems only C# / .Net does not throw a warning.

Here is my validation Code:

```<code>public string ValidateXML(string sXmlString)
{
    validationErr = "";
    try
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.CloseInput = true;
        settings.ValidationEventHandler += ValidationHandler;
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |
                                   XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                   XmlSchemaValidationFlags.ProcessSchemaLocation;

        StringReader r = new StringReader(sXmlString);
        XmlReader validatingReader = XmlReader.Create(r, settings);
        XmlDoc = new XmlDocument();
        XmlDoc.Load(validatingReader); //errors are put into the validationErr var in the ValidationHandler
    }
    catch (Exception exc)
    {
        validationErr = "XML EXCEPTION: " + exc.Message + Environment.NewLine + validationErr;
    }
    return validationErr;
}

private static void ValidationHandler(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
    {
        validationErr += "XML Parse Error Line: " +
                    e.Exception.LineNumber + " Position: " +
                    e.Exception.LinePosition + " Message: " +
                    e.Exception.Message + Environment.NewLine;
    }
}
</code>```

Here is my XSD:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="SampleSchema">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="Margins" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="Margins">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="Header" minOccurs="0"/>
                <xs:element ref="Footer" minOccurs="0"/>
                <xs:element ref="LeftSide" minOccurs="0"/>
                <xs:element ref="RightSide" minOccurs="0"/>
            </xs:sequence>
            <xs:attribute ref="Units" use="required"/>
            <xs:attribute ref="CenterHorizontal" use="required"/>
            <xs:attribute ref="CenterVertical" use="required"/>
            <xs:attribute ref="PriorityHorizontal" use="required"/>
            <xs:attribute ref="PriorityVertical" use="required"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="Header">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="Footer">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="LeftSide">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="RightSide">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:attribute name="Units" default="PT">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="IN"/>
                <xs:enumeration value="MM"/>
                <xs:enumeration value="PT"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
    <xs:attribute name="CenterHorizontal" type="xs:boolean" default="true">
    </xs:attribute>
    <xs:attribute name="CenterVertical" type="xs:boolean" default="true">
    </xs:attribute>
    <xs:attribute name="PriorityHorizontal" default="Left">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="Left"/>
                <xs:enumeration value="Right"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
    <xs:attribute name="PriorityVertical" default="Header">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="Header"/>
                <xs:enumeration value="Footer"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
</xs:schema>
</code>```

Here is my XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SampleSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="sample.xsd">
    <Margins Units="PT" CenterHorizontal="false" CenterVertical="false" PriorityVertical="Header">
        <Header>36</Header>
        <Footer>36</Footer>
        <LeftSide>36</LeftSide>
        <RightSide>36</RightSide>
    </Margins>
</SampleSchema>
</code>```

Am I going to have to write code to explicitly check for the Attributes in the XML file once the initial validation succeeds?

Or is there a way to get the XmlReader Validation to throw these warnings?

答:
Try to remove "default" in attribute definition. MSDN says:

…Processors of the schema should act as if the attribute was specified with the default value if it was not actually in the instance document.

Looks like this is why "required" validation does not work.

ContentLicense: CC BY-SA 3.0

Body:
I'm using XmlReader to validate my XMLfiles against my XSD schema file and it is working with one exception: It is not reporting missing required Attributes.

It does, however, report Attributes that do not conform to the XSD (name spelled wrong, disallowed contents)

For example, both of these will validate without a warning, even though both Attributes are required:

<Margin Units="IN">
<Margin Units="IN" Center="true">

Yet these will throw a warning (where Units is an Enum and Center is a Boolean):

<Margin Units="IN" Center="123">
<Margin Units="abc" Center="123">

To make matters more confusing (for me) the same files and conditions will fail validation using Notepad++ plugin "XML Tools", and will fail using XMLSpy.

It seems only C# / .Net does not throw a warning.

Here is my validation Code:

public string ValidateXML(string sXmlString)
{
    validationErr = "";
    try
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.CloseInput = true;
        settings.ValidationEventHandler += ValidationHandler;
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |
                                   XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                   XmlSchemaValidationFlags.ProcessSchemaLocation;

        StringReader r = new StringReader(sXmlString);
        XmlReader validatingReader = XmlReader.Create(r, settings);
        XmlDoc = new XmlDocument();
        XmlDoc.Load(validatingReader); //errors are put into the validationErr var in the ValidationHandler
    }
    catch (Exception exc)
    {
        validationErr = "XML EXCEPTION: " + exc.Message + Environment.NewLine + validationErr;
    }
    return validationErr;
}

private static void ValidationHandler(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
    {
        validationErr += "XML Parse Error Line: " +
                    e.Exception.LineNumber + " Position: " +
                    e.Exception.LinePosition + " Message: " +
                    e.Exception.Message + Environment.NewLine;
    }
}

Here is my XSD:

    <?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="SampleSchema">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="Margins" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="Margins">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="Header" minOccurs="0"/>
                <xs:element ref="Footer" minOccurs="0"/>
                <xs:element ref="LeftSide" minOccurs="0"/>
                <xs:element ref="RightSide" minOccurs="0"/>
            </xs:sequence>
            <xs:attribute ref="Units" use="required"/>
            <xs:attribute ref="CenterHorizontal" use="required"/>
            <xs:attribute ref="CenterVertical" use="required"/>
            <xs:attribute ref="PriorityHorizontal" use="required"/>
            <xs:attribute ref="PriorityVertical" use="required"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="Header">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="Footer">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="LeftSide">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element name="RightSide">
        <xs:simpleType>
            <xs:restriction base="xs:decimal">
                <xs:minInclusive value="0"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:attribute name="Units" default="PT">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="IN"/>
                <xs:enumeration value="MM"/>
                <xs:enumeration value="PT"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
    <xs:attribute name="CenterHorizontal" type="xs:boolean" default="true">
    </xs:attribute>
    <xs:attribute name="CenterVertical" type="xs:boolean" default="true">
    </xs:attribute>
    <xs:attribute name="PriorityHorizontal" default="Left">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="Left"/>
                <xs:enumeration value="Right"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
    <xs:attribute name="PriorityVertical" default="Header">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="Header"/>
                <xs:enumeration value="Footer"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
</xs:schema>

Here is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<SampleSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="sample.xsd">
    <Margins Units="PT" CenterHorizontal="false" CenterVertical="false" PriorityVertical="Header">
        36
        36
        <LeftSide>36</LeftSide>
        <RightSide>36</RightSide>
    </Margins>
</SampleSchema>

Am I going to have to write code to explicitly check for the Attributes in the XML file once the initial validation succeeds?

Or is there a way to get the XmlReader Validation to throw these warnings?


问:
How to add CSS configuration in reactjs Project?
I've written the webpackconfig but css doesn't seem to work properly and it is throwing and error. Following are my file's contains.

My webpack.config.js:

```<code>module: {
    loaders: [
      {
        test: /\.js?/,
        include: SRC_DIR,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015", "stage-2"]
        }
      }
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader")
      }
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("style.css", {
      allChunks: true
    })
  ]
};
</code>```

and in my Index.js I've added as :

```<code>import '../assets/css/style.css';
</code>```

Package.json :

```<code>{
  ...
  "dependencies": {...
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.3",
    "css-loader": "^0.28.7",
    "style-loader": "^0.19.0"
  }
}
</code>```

答:
As per our chat, this is what your webpack.config.js file is as below:

```<code>var path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
  entry: SRC_DIR + "/app/index.js",
  output: {
    path: DIST_DIR + "/app",
    filename: "bundle.js",
    publicPath: "/app/"
  },
  module: {
    loaders: [
      {
        test: /\.js?/,
        include: SRC_DIR,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015", "stage-2"]
        }
      }
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("css-loader!sass-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("src/components/assets/css/style.css", {
      allChunks: true
    })
  ]
};

module.exports = config;
</code>```

There are two issues with this config.

The are no commas separating the loaders objects.

You are using ExtractTextPlugin but have not imported/required it anywhere in the config.

Issue #1 is quite obvious how to solve; simply add the commas after each definition of a loader object.

Issue #2 as well, you need to install and reference ExtractTextPlugin in you webpack config file.

You can do so by running the following command in your terminal:

```<code>npm install --save-dev extract-text-webpack-plugin
</code>```

This will install the plugin to your node_modules and also list it in your package.json file under thedevDependencies` object.

And then in your webpack.config.js where you are requiring modules, also require the plugin like so:

```<code>const ExtractTextPlugin = require("extract-text-webpack-plugin");
</code>```

After making these changes, you config file should look something like this:

```<code>var path = require("path");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
  entry: SRC_DIR + "/app/index.js",
  output: {
    path: DIST_DIR + "/app",
    filename: "bundle.js",
    publicPath: "/app/"
  },
  module: {
    loaders: [
      {
        test: /\.js?/,
        include: SRC_DIR,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015", "stage-2"]
        }
      },
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("css-loader!sass-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("src/components/assets/css/style.css", {
      allChunks: true
    })
  ]
};

module.exports = config;
</code>```

Body:
I've written the webpackconfig but css doesn't seem to work properly and it is throwing and error. Following are my file's contains.

My webpack.config.js:

module: {
    loaders: [
      {
        test: /\.js?/,
        include: SRC_DIR,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015", "stage-2"]
        }
      }
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader")
      }
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("style.css", {
      allChunks: true
    })
  ]
};

and in my Index.js I've added as :

import '../assets/css/style.css';

Package.json :

{
  ...
  "dependencies": {...
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.3",
    "css-loader": "^0.28.7",
    "style-loader": "^0.19.0"
  }
}

Body:
As per our chat, this is what your webpack.config.js file is as below:

var path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
  entry: SRC_DIR + "/app/index.js",
  output: {
    path: DIST_DIR + "/app",
    filename: "bundle.js",
    publicPath: "/app/"
  },
  module: {
    loaders: [
      {
        test: /\.js?/,
        include: SRC_DIR,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015", "stage-2"]
        }
      }
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("css-loader!sass-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("src/components/assets/css/style.css", {
      allChunks: true
    })
  ]
};

module.exports = config;

There are two issues with this config.

The are no commas separating the loaders objects.

You are using ExtractTextPlugin but have not imported/required it anywhere in the config.

Issue #1 is quite obvious how to solve; simply add the commas after each definition of a loader object.

Issue #2 as well, you need to install and reference ExtractTextPlugin in you webpack config file.

You can do so by running the following command in your terminal:

npm install --save-dev extract-text-webpack-plugin

This will install the plugin to your node_modules and also list it in your package.json file under thedevDependencies` object.

And then in your webpack.config.js where you are requiring modules, also require the plugin like so:

const ExtractTextPlugin = require("extract-text-webpack-plugin");

After making these changes, you config file should look something like this:

var path = require("path");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
  entry: SRC_DIR + "/app/index.js",
  output: {
    path: DIST_DIR + "/app",
    filename: "bundle.js",
    publicPath: "/app/"
  },
  module: {
    loaders: [
      {
        test: /\.js?/,
        include: SRC_DIR,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015", "stage-2"]
        }
      },
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("css-loader!sass-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("src/components/assets/css/style.css", {
      allChunks: true
    })
  ]
};

module.exports = config;


问:
Scroll behavior of two nested RecyclerViews
I have two nested RecyclerView. One of them manages vertical swipes and one of them handles horizontal swipes. The problem I am facing is, that scrolling of the horizontal RecyclerView sometimes does not behave as expected. Sometimes it will not recognise the horizontal swipes and will just do a vertical swipe. To make the horizontal swipe it is necessary to draw a really straight line in horizontal direction. A few degrees off will be recognised as vertical swipe.Are there any parameters which can be tweaked, to make the UX better?

Outer layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:gravity="center">

<ProgressBar
    android:id="@+id/pb_new_home"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_modules"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:nestedScrollingEnabled="false"
    android:paddingBottom="@dimen/newhome_recyclerview_paddingbottom" />
</RelativeLayout>
</code>```

Inner layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/NewHomeModuleContainer">

<TextView
    android:id="@+id/tv_module_title"
    style="@style/NewHomeModuleTitle" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_horizontal_recycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/tv_show_more"
    android:layout_below="@id/tv_module_title"
    android:layout_marginBottom="-8dp"
    android:clipToPadding="false"
    android:paddingEnd="28dp"
    android:paddingRight="28dp" />

</RelativeLayout>
</code>```

答:
you need to create a self-define RecyclerView and then override onInterceptTouchEvent intercept touch event of the outter RecyclerView

```<code>boolean moveInnerRv;
private float startY;

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    float currentY = -1;
    switch(ev.getAction()){
        case MotionEvent.ACTION_DOWN:
            startY = ev.getRawY();
            break;

        case MotionEvent.ACTION_MOVE:
            currentY = ev.getRawY();
            break;

        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:

            break;

        default:
            break;
    }
    // if move distance over 100, pass touch to inner RecyclerView
    moveInnerRv = !((currentY - startY) > 100);

    return moveInnerRv;
}
</code>```

Body:
I have two nested RecyclerView. One of them manages vertical swipes and one of them handles horizontal swipes. The problem I am facing is, that scrolling of the horizontal RecyclerView sometimes does not behave as expected. Sometimes it will not recognise the horizontal swipes and will just do a vertical swipe. To make the horizontal swipe it is necessary to draw a really straight line in horizontal direction. A few degrees off will be recognised as vertical swipe.Are there any parameters which can be tweaked, to make the UX better?

Outer layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:gravity="center">

<ProgressBar
    android:id="@+id/pb_new_home"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_modules"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:nestedScrollingEnabled="false"
    android:paddingBottom="@dimen/newhome_recyclerview_paddingbottom" />
</RelativeLayout>

Inner layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/NewHomeModuleContainer">

<TextView
    android:id="@+id/tv_module_title"
    style="@style/NewHomeModuleTitle" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_horizontal_recycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/tv_show_more"
    android:layout_below="@id/tv_module_title"
    android:layout_marginBottom="-8dp"
    android:clipToPadding="false"
    android:paddingEnd="28dp"
    android:paddingRight="28dp" />

</RelativeLayout>

Body:
you need to create a self-define RecyclerView and then override onInterceptTouchEvent intercept touch event of the outter RecyclerView

boolean moveInnerRv;
private float startY;

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    float currentY = -1;
    switch(ev.getAction()){
        case MotionEvent.ACTION_DOWN:
            startY = ev.getRawY();
            break;

        case MotionEvent.ACTION_MOVE:
            currentY = ev.getRawY();
            break;

        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:

            break;

        default:
            break;
    }
    // if move distance over 100, pass touch to inner RecyclerView
    moveInnerRv = !((currentY - startY) > 100);

    return moveInnerRv;
}


问:
only do not select duplicated values mysql?
I am looking for a way to run a simple SELECT statment. I have a table which has two columns: id and email.

I want to run a SELECT statment that won't return duplicate values. For example, take the following data:

```<code>1   example@hotmail.com
2   example12@hotmail.com
3   example@hotmail.com
4   example@hotmail.com
</code>```

I want it to return only the following:

```<code>2   example12@hotmail.com
</code>```

答: select id,email from table group by email having count(*) =1;</p>

Body:
I am looking for a way to run a simple SELECT statment. I have a table which has two columns: id and email.

I want to run a SELECT statment that won't return duplicate values. For example, take the following data:

1   example@hotmail.com
2   example12@hotmail.com
3   example@hotmail.com
4   example@hotmail.com

I want it to return only the following:

2   example12@hotmail.com


问:
RecyclerView item's button does not change button's text when click on button
I have implemented one code where I am using RecyclerView which Item's have 3 button and one of them is shortlist. My issue is when someone click on that button if the response is success then button text should be changed i.e shortlisted and user can not click again. I used btnShortlist.setText("shortlisted") and it's not working

Below is my class CardAdapter

```<code>public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
 //   holder.btnShortlist.setText(superHero.getShortlist());
 //   holder.btnEI.setText(superHero.getExpress_Intrest());

    str = superHero.getShortlist();
    Log.e("sh____________",str);
    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.btnShortlist.setText("Wait...");
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);

        }
    });

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

@Override
public int getItemCount() {return superHeroes.size();}
</code>```

Class ViewHolder

```<code>class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }
</code>```

method for shortlist

```<code>    private void shortlist(final int position){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equalsIgnoreCase("success")) {
                    int selectedPosition = position;
                    btnShortlist.setText("shortlisted");
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY,matri_id_by);
                params.put(KEY_MATRI_ID_TO,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
       }
      }
     }
</code>```

答:
You need to save the state of the button that which is clicked on specific Row. Like on Button click you have to update data on SuperHero model and notify data set change.

Add below method in your RecyclerView's Adapter.

```<code> public SuperHero getItem(int position){
    return superHeroes.get(position);
}
</code>```

and your onResponse(String response)   method look like below.

```<code>  if(response.trim().equalsIgnoreCase("success")) {
        SuperHero superhero = adapter.getItem(position);
        superhero.setShortlist("shortlisted");
        notifyDataSetChanged();
    }
</code>```

where adapter is your RecyclerViewAdapter's instance.

Body:
I have implemented one code where I am using RecyclerView which Item's have 3 button and one of them is shortlist. My issue is when someone click on that button if the response is success then button text should be changed i.e shortlisted and user can not click again. I used btnShortlist.setText("shortlisted") and it's not working

Below is my class CardAdapter

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
 //   holder.btnShortlist.setText(superHero.getShortlist());
 //   holder.btnEI.setText(superHero.getExpress_Intrest());

    str = superHero.getShortlist();
    Log.e("sh____________",str);
    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.btnShortlist.setText("Wait...");
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);

        }
    });

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

@Override
public int getItemCount() {return superHeroes.size();}

Class ViewHolder

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

method for shortlist

    private void shortlist(final int position){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equalsIgnoreCase("success")) {
                    int selectedPosition = position;
                    btnShortlist.setText("shortlisted");
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY,matri_id_by);
                params.put(KEY_MATRI_ID_TO,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
       }
      }
     }

Body:
You need to save the state of the button that which is clicked on specific Row. Like on Button click you have to update data on SuperHero model and notify data set change.

Add below method in your RecyclerView's Adapter.

 public SuperHero getItem(int position){
    return superHeroes.get(position);
}

and your onResponse(String response)   method look like below.

  if(response.trim().equalsIgnoreCase("success")) {
        SuperHero superhero = adapter.getItem(position);
        superhero.setShortlist("shortlisted");
        notifyDataSetChanged();
    }

where adapter is your RecyclerViewAdapter's instance.


问:
Finding out the size of a Netezza table using UNIX SAS
What syntax / tables can be used to determine the size (Gbs) of a Netezza table?  I am accessing via UNIX SAS (either ODBC or libname engine).  I assume there is a view which will give this info?</p>

答:
So you're interested in two system views _v_obj_relation_xdb and _v_sys_object_dslice_info. The first (_v_obj_relation_xdb) contains the table information (name, type, etc.) and the second (_v_sys_object_dslice_info) contains the size per disk information. You probably want to take a look at both of those tables to get a good idea of what you're really after, but the simple query would be:

```<code>select objname, sum(used_bytes) size_in_bytes
from _V_OBJ_RELATION_XDB
join _V_SYS_OBJECT_DSLICE_INFO on (objid = tblid)
where objname = 'UPPERCASE_TABLE_NAME'
group by objname
</code>```

This returns the size of the table in bytes and I'll leave the conversion to GB as an exercise to the reader. There are some other interesting fields there so you might want to check out those views.

ContentLicense: CC BY-SA 2.5

Body:
So you're interested in two system views _v_obj_relation_xdb and _v_sys_object_dslice_info. The first (_v_obj_relation_xdb) contains the table information (name, type, etc.) and the second (_v_sys_object_dslice_info) contains the size per disk information. You probably want to take a look at both of those tables to get a good idea of what you're really after, but the simple query would be:

select objname, sum(used_bytes) size_in_bytes
from _V_OBJ_RELATION_XDB
join _V_SYS_OBJECT_DSLICE_INFO on (objid = tblid)
where objname = 'UPPERCASE_TABLE_NAME'
group by objname

This returns the size of the table in bytes and I'll leave the conversion to GB as an exercise to the reader. There are some other interesting fields there so you might want to check out those views.


问:
Retain parent instance if using SelectMany on nested collection
I have a collection of my model Person:

```<code>class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Company {get; set;}
    public IEnumerable<string> Tags {get; set;}
}
</code>```

and would transform this one by LINQ into another collection grouped by tags. How can I do that?

My approach so far:

```<code>var result = PersonCollection
    .SelectMany(m => m.Tags)
    .GroupBy(b => b);
</code>```

But this throws all informations about the person away.

答:
You need to group people by each tag. This looks best in LINQ query syntax :

```<code>var groupings =
    from p in people
    from tag in p.Tags
    group p by tag into g
    select new
    {
        Tag = g.Key,
        People = g.ToList()
    };
</code>```

Last select is just for friendly names, this would have worked as well:

```<code>var gg = from p in people
         from tag in p.Tags
         group p by tag;
</code>```

Behind the scenes this is equivalent to @Tim Schmelter's  solution

Body:
I have a collection of my model Person:

class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Company {get; set;}
    public IEnumerable<string> Tags {get; set;}
}

and would transform this one by LINQ into another collection grouped by tags. How can I do that?

My approach so far:

var result = PersonCollection
    .SelectMany(m => m.Tags)
    .GroupBy(b => b);

But this throws all informations about the person away.

Body:
You need to group people by each tag. This looks best in LINQ query syntax :

var groupings =
    from p in people
    from tag in p.Tags
    group p by tag into g
    select new
    {
        Tag = g.Key,
        People = g.ToList()
    };

Last select is just for friendly names, this would have worked as well:

var gg = from p in people
         from tag in p.Tags
         group p by tag;

Behind the scenes this is equivalent to @Tim Schmelter's  solution


问:
React-apollo v2 - Youshido GraphQlBundle - refetch two queries simultaneously
I'm trying to implement apollo to feed my customer's table component.

```<code>import CustomersTable from 'components/Customer/CustomersTable';
</code>```

This table have to be filterable, sortable and paginated. I have 200.000 customers in the MySQL table. That's why filters, sorts and pagination are compute on server side. I need to query separately customers total count for pagination, and the customers list.

```<code>import GET_CUSTOMERS_PAGINATED_QUERY from './getCustomersPaginated.graphql';
import GET_CUSTOMERS_PAGINATED_COUNT_QUERY from './getCustomersPaginatedCount.graphql';
</code>```

Unexpectedly, when the filtersInput are changed the refetch function is called twice. The first time with the correct new variables, and the second with initial variables. So the total count of customers is overwritten.

```<code>const initialFilters = {
  filterId: null,
  filterSiren: null,
  filterName: null,
  filterEmail: null,
};

const getCustomersPaginatedCountOptions = {
  name: 'customersPaginatedCount',
  options() {
    return {
      variables: {
        ...initialFilters,
      },
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginatedCount }) {
    return {
      customersPaginatedCount: customersPaginatedCount,
    };
  },
};
const getCustomersPaginatedOptions = {
  name: 'customersPaginated',
  options({ offset, limit }) {
    return {
      variables: {
        offset: offset,
        limit: limit,
        ...initialFilters,
      },
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginated }) {
    return {
      customersPaginated: customersPaginated,
    };
  },
};
</code>```

These two queries are composed as advices here (for no errors):

```<code>@compose(
  graphql(GET_CUSTOMERS_PAGINATED_QUERY, getCustomersPaginatedOptions),
  graphql(GET_CUSTOMERS_PAGINATED_COUNT_QUERY, getCustomersPaginatedCountOptions),
)
export default class CustomersTableContainer extends React.PureComponent {

  state = {
    offset: this.props.offset,
    limit: this.props.limit,
    pageSize: 10,
    currentPage: 0,
    filters: initialFilters,
    currentOnFilterChangeTimeoutID: null,
  };

  constructor(props) {
    super(props);

    this.onCurrentPageChange = this.onCurrentPageChange.bind(this);
    this.onFiltersChange = this.onFiltersChange.bind(this);
  }

  onCurrentPageChange(newPage) {
    const { customersPaginated } = this.props;
    const { limit, filters } = this.state;

    customersPaginated.refetch({
      offset: newPage * limit,
      ...filters,
    });

    this.setState({ currentPage: newPage });
  }

  onFiltersChange(args) {
    const { customersPaginated, customersPaginatedCount } = this.props;
    const { limit } = this.state;

    const newFilters = Object.assign({}, initialFilters);
    for ( const i in args ) {
      newFilters['filter' + ucfirst(args[i].columnName)] = args[i].value;
    }

    customersPaginated.refetch({
      offset: 0 * limit,
      ...newFilters,
    });

    // --- >> THE REFETCH FUNCTION IS TRIGGERED TWICE HERE ! << ---
    customersPaginatedCount.refetch({
      ...newFilters,
    });

    // here 'test' is displayed once, so onFiltersChange is called once too as expected
    console.log('test');

    this.setState({
      currentPage: 0,
      filters: newFilters,
    });
  }

  render () {
    const { customersPaginated, customersPaginatedCount } = this.props;
    const { currentPage, pageSize } = this.state;

    if (customersPaginated.error) console.error( customersPaginated.error );
    if (customersPaginatedCount.error) console.error( customersPaginatedCount.error );

    return (
      <div>
        {(customersPaginated.error || customersPaginatedCount.error) && (
          <Typography color="error" gutterBottom>
            Une erreur est survenue.
          </Typography>
        )}
        <div>
          <CustomersTable
            customers={customersPaginated.customersPaginated}
            currentPage={currentPage}
            onCurrentPageChange={this.onCurrentPageChange}
            onFiltersChange={this.onFiltersChange}
            pageSize={pageSize}
            totalCount={customersPaginatedCount.customersPaginatedCount || 0}
          />
          {(customersPaginated.loading || customersPaginatedCount.loading) && <Loading />}
        </div>
      </div>
    );
  }

  static propTypes = {
    customersPaginated: PropTypes.object.isRequired,
    customersPaginatedCount: PropTypes.object.isRequired,
    offset: PropTypes.number.isRequired,
    limit: PropTypes.number.isRequired,
  };
}
</code>```

My console logs on component load in an expected behavior :

```<code>{variables: {filterId: null, filterSiren: null, filterName: null, filterEmail: null}, operationName: "getCustomersPaginatedCount"
{variables: {filterId: null, filterSiren: null, filterName: null, filterEmail: null}, operationName: "getCustomersPaginated"
</code>```

My console logs on a filter input change in an unexpected behavior :

```<code>{variables: {filterId: null, filterSiren: null, filterName: "example of customer name", filterEmail: null}, operationName: "getCustomersPaginated"
{variables: {filterId: null, filterSiren: null, filterName: "example of customer name", filterEmail: null}, operationName: "getCustomersPaginatedCount"
{variables: {filterId: null, filterSiren: null, filterName: null, filterEmail: null}, operationName: "getCustomersPaginatedCount"
</code>```

getCustomersPaginated.graphql :

```<code>query getCustomersPaginated(
    $filterId: Int,
    $filterSiren: String,
    $filterName: String,
    $filterEmail: String,
    $offset: Int,
    $limit: Int
  ) {
    customersPaginated(
      filterId: $filterId,
      filterSiren: $filterSiren,
      filterName: $filterName,
      filterEmail: $filterEmail,
      offset: $offset,
      limit: $limit
    ) {
    id
    name
    siren
    email
    activity {
      id
      name
      shortName
      code
    }
    salesFollower {
      id
      username
      firstname
      lastname
      email
      initials
      enabled
    }
    customerGroup {
      id
      name
      code
      enabled
    }
    coreBusiness {
      id
      name
      codeApe
      codeNaf
    }
  }
}
</code>```

getCustomersPaginatedCount.graphql :

```<code>query getCustomersPaginatedCount(
  $filterId: Int,
  $filterSiren: String,
  $filterName: String,
  $filterEmail: String
) {
  customersPaginatedCount(
    filterId: $filterId,
    filterSiren: $filterSiren,
    filterName: $filterName,
    filterEmail: $filterEmail,
  )
}
</code>```

My environnement :

Front : reactjs with react-apollo

Back : PHP 7 with Symfony3 and Youshido\GraphQLBundle

I begun react this year and apollo this month.
Maybe I'm not using refetch like I should, maybe there is a better way, or maybe there is a bug (I updated apollo-client-preset from 1.0.2 to 1.0.3 without seeing any changes).
Maybe there's a solution on Youshido's side to be able to fetch the customers's list and customers's count in one query.

Thanks for your help.

答:
In some situations the refetch function is not necessary.
Thanks to @stelmakh for his help on this issue !!

My new code :
Child :

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { compose, graphql } from 'react-apollo';
import { ucfirst } from 'utils/string';

import CustomersTable from 'components/Customer/CustomersTable';
import Typography from 'material-ui/Typography';

import Loading from 'components/Loading/Loading';

import GET_CUSTOMERS_PAGINATED_QUERY from './getCustomersPaginated.graphql';
import GET_CUSTOMERS_PAGINATED_COUNT_QUERY from './getCustomersPaginatedCount.graphql';

const getCustomersPaginatedCountOptions = {
  name: 'customersPaginatedCount',
  options({ variables }) {
    return {
      variables: variables,
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginatedCount }) {
    return { customersPaginatedCount: customersPaginatedCount };
  },
};
const getCustomersPaginatedOptions = {
  name: 'customersPaginated',
  options({ variables }) {
    return {
      variables: variables,
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginated }) {
    return { customersPaginated: customersPaginated };
  },
};

@compose(
  graphql(GET_CUSTOMERS_PAGINATED_QUERY, getCustomersPaginatedOptions),
  graphql(GET_CUSTOMERS_PAGINATED_COUNT_QUERY, getCustomersPaginatedCountOptions),
)
export default class CustomersTableContainer extends React.PureComponent {

  state = {
    currentOnFilterChangeTimeoutID: null,
  };

  constructor(props) {
    super(props);

    this.onCurrentPageChange = this.onCurrentPageChange.bind(this);
    this.onSortingChange = this.onSortingChange.bind(this);
    this.onFiltersChange = this.onFiltersChange.bind(this);
  }

  onCurrentPageChange(newPage) {
    const { onChange, variables } = this.props;

    onChange({
      currentPage: newPage,
      'offset': newPage * variables.limit,
    });
  }

  onFiltersChange(args) {
    clearTimeout(this.state.currentOnFilterChangeTimeoutID);

    const newCurrentOnFilterChangeTimeoutID = setTimeout(() => {
      const { onChange, variables } = this.props;

      const newVariables = Object.assign({}, variables);

      if (args.length > 0) {
        for ( const i in args ) {
          newVariables['filter' + ucfirst(args[i].columnName)] = args[i].value;
        }
      } else {
        for ( const i in newVariables ) {
          if (i.substr(0, 6) === 'filter') newVariables[i] = null;
        }
      }

      onChange({
        ...newVariables,
        'currentPage': 0,
        'offset': 0 * variables.limit,
      });
    }, 1000);

    this.setState({ currentOnFilterChangeTimeoutID: newCurrentOnFilterChangeTimeoutID });
  }

  render () {
    const { variables, customersPaginated, customersPaginatedCount } = this.props;

    if (customersPaginated.error) console.error( customersPaginated.error );
    if (customersPaginatedCount.error) console.error( customersPaginatedCount.error );

    return (
      <div>
        {(customersPaginated.error || customersPaginatedCount.error) && (
          <Typography color="error" gutterBottom>
            Une erreur est survenue.
          </Typography>
        )}
        <div>
          <CustomersTable
            customers={customersPaginated.customersPaginated}
            currentPage={variables.currentPage}
            onCurrentPageChange={this.onCurrentPageChange}
            onSortingChange={this.onSortingChange}
            onFiltersChange={this.onFiltersChange}
            pageSize={variables.pageSize}
            totalCount={customersPaginatedCount.customersPaginatedCount || 0}
          />
          {(customersPaginated.loading || customersPaginatedCount.loading) && <Loading />}
        </div>
      </div>
    );
  }

  static propTypes = {
    customersPaginated: PropTypes.object.isRequired,
    customersPaginatedCount: PropTypes.object.isRequired,
    variables: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
  };
}
</code>```

Parent :

```<code>import React from 'react';

import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import AddIcon from 'material-ui-icons/Add';

import CustomersTableContainer from 'containers/Customer/CustomersTableContainer';

export default class CustomersPage extends React.PureComponent {

  constructor(props) {
    super(props);

    this.state = {
      customersTableVariables: {
        filterId: null,
        filterSiren: null,
        filterName: null,
        filterEmail: null,
        pageSize: 10,
        currentPage: 0,
        offset: 0,
        limit: 10,
      },
    };

    this.onCustomersChange = this.onCustomersChange.bind(this);
  }

  onCustomersChange (newVariables) {
    this.setState({
      customersTableVariables: Object.assign({}, this.state.customersTableVariables, newVariables)
    });
  }

  render () {
    const { customersTableVariables } = this.state;
    return (
      <div>
        <Typography align="right">
          <Button fab color="primary" aria-label="add" href="/customer/new">
            <AddIcon />
          </Button>
        </Typography>
        <Typography type="title" gutterBottom>
          Clients/Prospects
        </Typography>
        <CustomersTableContainer variables={customersTableVariables} onChange={this.onCustomersChange} />
      </div>
    );
  }
}
</code>```

Body:
I'm trying to implement apollo to feed my customer's table component.

import CustomersTable from 'components/Customer/CustomersTable';

This table have to be filterable, sortable and paginated. I have 200.000 customers in the MySQL table. That's why filters, sorts and pagination are compute on server side. I need to query separately customers total count for pagination, and the customers list.

import GET_CUSTOMERS_PAGINATED_QUERY from './getCustomersPaginated.graphql';
import GET_CUSTOMERS_PAGINATED_COUNT_QUERY from './getCustomersPaginatedCount.graphql';

Unexpectedly, when the filtersInput are changed the refetch function is called twice. The first time with the correct new variables, and the second with initial variables. So the total count of customers is overwritten.

const initialFilters = {
  filterId: null,
  filterSiren: null,
  filterName: null,
  filterEmail: null,
};

const getCustomersPaginatedCountOptions = {
  name: 'customersPaginatedCount',
  options() {
    return {
      variables: {
        ...initialFilters,
      },
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginatedCount }) {
    return {
      customersPaginatedCount: customersPaginatedCount,
    };
  },
};
const getCustomersPaginatedOptions = {
  name: 'customersPaginated',
  options({ offset, limit }) {
    return {
      variables: {
        offset: offset,
        limit: limit,
        ...initialFilters,
      },
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginated }) {
    return {
      customersPaginated: customersPaginated,
    };
  },
};

These two queries are composed as advices here (for no errors):

@compose(
  graphql(GET_CUSTOMERS_PAGINATED_QUERY, getCustomersPaginatedOptions),
  graphql(GET_CUSTOMERS_PAGINATED_COUNT_QUERY, getCustomersPaginatedCountOptions),
)
export default class CustomersTableContainer extends React.PureComponent {

  state = {
    offset: this.props.offset,
    limit: this.props.limit,
    pageSize: 10,
    currentPage: 0,
    filters: initialFilters,
    currentOnFilterChangeTimeoutID: null,
  };

  constructor(props) {
    super(props);

    this.onCurrentPageChange = this.onCurrentPageChange.bind(this);
    this.onFiltersChange = this.onFiltersChange.bind(this);
  }

  onCurrentPageChange(newPage) {
    const { customersPaginated } = this.props;
    const { limit, filters } = this.state;

    customersPaginated.refetch({
      offset: newPage * limit,
      ...filters,
    });

    this.setState({ currentPage: newPage });
  }

  onFiltersChange(args) {
    const { customersPaginated, customersPaginatedCount } = this.props;
    const { limit } = this.state;

    const newFilters = Object.assign({}, initialFilters);
    for ( const i in args ) {
      newFilters['filter' + ucfirst(args[i].columnName)] = args[i].value;
    }

    customersPaginated.refetch({
      offset: 0 * limit,
      ...newFilters,
    });

    // --- >> THE REFETCH FUNCTION IS TRIGGERED TWICE HERE ! << ---
    customersPaginatedCount.refetch({
      ...newFilters,
    });

    // here 'test' is displayed once, so onFiltersChange is called once too as expected
    console.log('test');

    this.setState({
      currentPage: 0,
      filters: newFilters,
    });
  }

  render () {
    const { customersPaginated, customersPaginatedCount } = this.props;
    const { currentPage, pageSize } = this.state;

    if (customersPaginated.error) console.error( customersPaginated.error );
    if (customersPaginatedCount.error) console.error( customersPaginatedCount.error );

    return (

        {(customersPaginated.error || customersPaginatedCount.error) && (
          <Typography color="error" gutterBottom>
            Une erreur est survenue.
          </Typography>
        )}

          <CustomersTable
            customers={customersPaginated.customersPaginated}
            currentPage={currentPage}
            onCurrentPageChange={this.onCurrentPageChange}
            onFiltersChange={this.onFiltersChange}
            pageSize={pageSize}
            totalCount={customersPaginatedCount.customersPaginatedCount || 0}
          />
          {(customersPaginated.loading || customersPaginatedCount.loading) && <Loading />}

    );
  }

  static propTypes = {
    customersPaginated: PropTypes.object.isRequired,
    customersPaginatedCount: PropTypes.object.isRequired,
    offset: PropTypes.number.isRequired,
    limit: PropTypes.number.isRequired,
  };
}

My console logs on component load in an expected behavior :

{variables: {filterId: null, filterSiren: null, filterName: null, filterEmail: null}, operationName: "getCustomersPaginatedCount"
{variables: {filterId: null, filterSiren: null, filterName: null, filterEmail: null}, operationName: "getCustomersPaginated"

My console logs on a filter input change in an unexpected behavior :

{variables: {filterId: null, filterSiren: null, filterName: "example of customer name", filterEmail: null}, operationName: "getCustomersPaginated"
{variables: {filterId: null, filterSiren: null, filterName: "example of customer name", filterEmail: null}, operationName: "getCustomersPaginatedCount"
{variables: {filterId: null, filterSiren: null, filterName: null, filterEmail: null}, operationName: "getCustomersPaginatedCount"

getCustomersPaginated.graphql :

query getCustomersPaginated(
    $filterId: Int,
    $filterSiren: String,
    $filterName: String,
    $filterEmail: String,
    $offset: Int,
    $limit: Int
  ) {
    customersPaginated(
      filterId: $filterId,
      filterSiren: $filterSiren,
      filterName: $filterName,
      filterEmail: $filterEmail,
      offset: $offset,
      limit: $limit
    ) {
    id
    name
    siren
    email
    activity {
      id
      name
      shortName
      code
    }
    salesFollower {
      id
      username
      firstname
      lastname
      email
      initials
      enabled
    }
    customerGroup {
      id
      name
      code
      enabled
    }
    coreBusiness {
      id
      name
      codeApe
      codeNaf
    }
  }
}

getCustomersPaginatedCount.graphql :

query getCustomersPaginatedCount(
  $filterId: Int,
  $filterSiren: String,
  $filterName: String,
  $filterEmail: String
) {
  customersPaginatedCount(
    filterId: $filterId,
    filterSiren: $filterSiren,
    filterName: $filterName,
    filterEmail: $filterEmail,
  )
}

My environnement :

Front : reactjs with react-apollo

Back : PHP 7 with Symfony3 and Youshido\GraphQLBundle

I begun react this year and apollo this month.
Maybe I'm not using refetch like I should, maybe there is a better way, or maybe there is a bug (I updated apollo-client-preset from 1.0.2 to 1.0.3 without seeing any changes).
Maybe there's a solution on Youshido's side to be able to fetch the customers's list and customers's count in one query.

Thanks for your help.

Body:
In some situations the refetch function is not necessary.
Thanks to @stelmakh for his help on this issue !!

My new code :
Child :

import React from 'react';
import PropTypes from 'prop-types';
import { compose, graphql } from 'react-apollo';
import { ucfirst } from 'utils/string';

import CustomersTable from 'components/Customer/CustomersTable';
import Typography from 'material-ui/Typography';

import Loading from 'components/Loading/Loading';

import GET_CUSTOMERS_PAGINATED_QUERY from './getCustomersPaginated.graphql';
import GET_CUSTOMERS_PAGINATED_COUNT_QUERY from './getCustomersPaginatedCount.graphql';

const getCustomersPaginatedCountOptions = {
  name: 'customersPaginatedCount',
  options({ variables }) {
    return {
      variables: variables,
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginatedCount }) {
    return { customersPaginatedCount: customersPaginatedCount };
  },
};
const getCustomersPaginatedOptions = {
  name: 'customersPaginated',
  options({ variables }) {
    return {
      variables: variables,
      fetchPolicy: 'network-only',
    };
  },
  props({ customersPaginated }) {
    return { customersPaginated: customersPaginated };
  },
};

@compose(
  graphql(GET_CUSTOMERS_PAGINATED_QUERY, getCustomersPaginatedOptions),
  graphql(GET_CUSTOMERS_PAGINATED_COUNT_QUERY, getCustomersPaginatedCountOptions),
)
export default class CustomersTableContainer extends React.PureComponent {

  state = {
    currentOnFilterChangeTimeoutID: null,
  };

  constructor(props) {
    super(props);

    this.onCurrentPageChange = this.onCurrentPageChange.bind(this);
    this.onSortingChange = this.onSortingChange.bind(this);
    this.onFiltersChange = this.onFiltersChange.bind(this);
  }

  onCurrentPageChange(newPage) {
    const { onChange, variables } = this.props;

    onChange({
      currentPage: newPage,
      'offset': newPage * variables.limit,
    });
  }

  onFiltersChange(args) {
    clearTimeout(this.state.currentOnFilterChangeTimeoutID);

    const newCurrentOnFilterChangeTimeoutID = setTimeout(() => {
      const { onChange, variables } = this.props;

      const newVariables = Object.assign({}, variables);

      if (args.length > 0) {
        for ( const i in args ) {
          newVariables['filter' + ucfirst(args[i].columnName)] = args[i].value;
        }
      } else {
        for ( const i in newVariables ) {
          if (i.substr(0, 6) === 'filter') newVariables[i] = null;
        }
      }

      onChange({
        ...newVariables,
        'currentPage': 0,
        'offset': 0 * variables.limit,
      });
    }, 1000);

    this.setState({ currentOnFilterChangeTimeoutID: newCurrentOnFilterChangeTimeoutID });
  }

  render () {
    const { variables, customersPaginated, customersPaginatedCount } = this.props;

    if (customersPaginated.error) console.error( customersPaginated.error );
    if (customersPaginatedCount.error) console.error( customersPaginatedCount.error );

    return (
      <div>
        {(customersPaginated.error || customersPaginatedCount.error) && (
          <Typography color="error" gutterBottom>
            Une erreur est survenue.
          </Typography>
        )}
        <div>
          <CustomersTable
            customers={customersPaginated.customersPaginated}
            currentPage={variables.currentPage}
            onCurrentPageChange={this.onCurrentPageChange}
            onSortingChange={this.onSortingChange}
            onFiltersChange={this.onFiltersChange}
            pageSize={variables.pageSize}
            totalCount={customersPaginatedCount.customersPaginatedCount || 0}
          />
          {(customersPaginated.loading || customersPaginatedCount.loading) && <Loading />}
        </div>
      </div>
    );
  }

  static propTypes = {
    customersPaginated: PropTypes.object.isRequired,
    customersPaginatedCount: PropTypes.object.isRequired,
    variables: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
  };
}

Parent :

import React from 'react';

import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import AddIcon from 'material-ui-icons/Add';

import CustomersTableContainer from 'containers/Customer/CustomersTableContainer';

export default class CustomersPage extends React.PureComponent {

  constructor(props) {
    super(props);

    this.state = {
      customersTableVariables: {
        filterId: null,
        filterSiren: null,
        filterName: null,
        filterEmail: null,
        pageSize: 10,
        currentPage: 0,
        offset: 0,
        limit: 10,
      },
    };

    this.onCustomersChange = this.onCustomersChange.bind(this);
  }

  onCustomersChange (newVariables) {
    this.setState({
      customersTableVariables: Object.assign({}, this.state.customersTableVariables, newVariables)
    });
  }

  render () {
    const { customersTableVariables } = this.state;
    return (
      <div>
        <Typography align="right">
          <Button fab color="primary" aria-label="add" href="/customer/new">
            <AddIcon />
          </Button>
        </Typography>
        <Typography type="title" gutterBottom>
          Clients/Prospects
        </Typography>
        <CustomersTableContainer variables={customersTableVariables} onChange={this.onCustomersChange} />
      </div>
    );
  }
}


问:
Case sensitive duplicate values in oracle
I have a table with the below sample records

```<code>Name    Profession      University
-----   --------------  ---------------
Ram     Student         xxxUniversity
Ravi    Professor       xyzUniversity
Reshma  Professor       abcUniversity
Ram     StudenT         xxxUniversity
</code>```

As seen above "Ram" has case sensitive duplicate records. My Oracle query should return distinct records and one record for "Ram", which has the maximum number of uppercase character in Profession column.

Expected result

```<code>    Name    Profession      University
    -----   --------------  ---------------
    Ravi    Professor       xyzUniversity
    Reshma  Professor       abcUniversity
    Ram     StudenT         xxxUniversity
</code>```

答:
Try this :</p>

```<code>SELECT name,
       Profession,
       university
FROM
(SELECT name,
       Profession,
       university,
       ROW_NUMBER() OVER (PARTITION BY NAME,UPPER(PROFESSION) ORDER BY REGEXP_COUNT (Profession, '[A-Z]') DESC) RN
  FROM table1)
WHERE RN=1;
</code>```

Body:
I have a table with the below sample records

Name    Profession      University
-----   --------------  ---------------
Ram     Student         xxxUniversity
Ravi    Professor       xyzUniversity
Reshma  Professor       abcUniversity
Ram     StudenT         xxxUniversity

As seen above "Ram" has case sensitive duplicate records. My Oracle query should return distinct records and one record for "Ram", which has the maximum number of uppercase character in Profession column.

Expected result

    Name    Profession      University
    -----   --------------  ---------------
    Ravi    Professor       xyzUniversity
    Reshma  Professor       abcUniversity
    Ram     StudenT         xxxUniversity

Body:
Try this :

SELECT name,
       Profession,
       university
FROM
(SELECT name,
       Profession,
       university,
       ROW_NUMBER() OVER (PARTITION BY NAME,UPPER(PROFESSION) ORDER BY REGEXP_COUNT (Profession, '[A-Z]') DESC) RN
  FROM table1)
WHERE RN=1;


问:
Modelbinding an optional array of a custom model bound type
I'm stuck with binding an optional array in an ASP.NET Core Controller. The array contains elements of a custom type. Single elements of this type are bound with a custom model binder and validated in it.

Sample repo here: https://github.com/MarcusKohnert/OptionalArrayModelBinding

I get only two tests out of three working in the sample test project:
https://github.com/MarcusKohnert/OptionalArrayModelBinding/blob/master/OptionalArrayModelBindingTest/TestOptionalArrayCustomModelBinder.cs

```<code>public class TestOptionalArrayCustomModelBinder
{
    private readonly TestServer server;
    private readonly HttpClient client;

    public TestOptionalArrayCustomModelBinder()
    {
        server = new TestServer(new WebHostBuilder().UseStartup<Startup>());

        client = server.CreateClient();
    }

    [Fact]
    public async Task SuccessWithoutProvidingIds()
    {
        var response = await client.GetAsync("/api/values");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task SuccessWithValidIds()
    {
        var response = await client.GetAsync("/api/values?ids=aaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task FailureWithOneInvalidId()
    {
        var response = await client.GetAsync("/api/values?ids=xaaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
    }
}
</code>```

Controller:

```<code>[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet]
    public IActionResult Get(CustomIdentifier[] ids)
    {
        if (this.ModelState.IsValid == false) return this.BadRequest();

        return this.Ok(ids);
    }
}
</code>```

Startup:

```<code>public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.ModelBinderProviders.Insert(0, new CutomIdentifierModelBinderProvider());
            //options.ModelBinderProviders.Add(new CutomIdentifierModelBinderProvider());
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}
</code>```

ModelBinder:

```<code>public class CutomIdentifierModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        //if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        //{
        //    return new ArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        //}

        if (context.Metadata.ModelType == typeof(CustomIdentifier))
        {
            return new BinderTypeModelBinder(typeof(CustomIdentifierModelBinder));
        }

        return null;
    }
}

public class CustomIdentifierModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
        var parseResult    = CustomIdentifier.TryParse(attemptedValue);

        if (parseResult.Failed)
        {
            bindingContext.Result = ModelBindingResult.Failed();
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, parseResult.Message.Message);
        }
        else
        {
            bindingContext.Model  = parseResult.Value;
            bindingContext.Result = ModelBindingResult.Success(parseResult.Value);
        }

        return Task.CompletedTask;
    }
}
</code>```

The MVC default ArrayModelBinder of T binds optional arrays correctly and sets ModelState.IsValid to true. If I use my own CustomIdentifierModelBinder however ModelState.IsValid will be false. Empty arrays are not recognized as valid.

How can I solve this problem? Thanks in advance.

答:
You are very close. Just customize behavior of built-in ArrayModelBinder for the case of missing parameter. If extracted value is an empty string just fill the model with an empty array. In all other cases you could call usual ArrayModelBinder.

Here is a working sample that passes all your 3 tests:

```<code>public class CutomIdentifierModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        {
            return new CustomArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        }

        return null;
    }
}

public class CustomArrayModelBinder<T> : IModelBinder
{
    private readonly ArrayModelBinder<T> innerModelBinder;

    public CustomArrayModelBinder(IModelBinder elemeBinder)
    {
        innerModelBinder = new ArrayModelBinder<T>(elemeBinder);
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();

        if (String.IsNullOrEmpty(attemptedValue))
        {
            bindingContext.Model = new T[0];
            bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
            return Task.CompletedTask;
        }

        return innerModelBinder.BindModelAsync(bindingContext);
    }
}
</code>```

Body:
I'm stuck with binding an optional array in an ASP.NET Core Controller. The array contains elements of a custom type. Single elements of this type are bound with a custom model binder and validated in it.

Sample repo here: https://github.com/MarcusKohnert/OptionalArrayModelBinding

I get only two tests out of three working in the sample test project:
https://github.com/MarcusKohnert/OptionalArrayModelBinding/blob/master/OptionalArrayModelBindingTest/TestOptionalArrayCustomModelBinder.cs

public class TestOptionalArrayCustomModelBinder
{
    private readonly TestServer server;
    private readonly HttpClient client;

    public TestOptionalArrayCustomModelBinder()
    {
        server = new TestServer(new WebHostBuilder().UseStartup<Startup>());

        client = server.CreateClient();
    }

    [Fact]
    public async Task SuccessWithoutProvidingIds()
    {
        var response = await client.GetAsync("/api/values");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task SuccessWithValidIds()
    {
        var response = await client.GetAsync("/api/values?ids=aaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task FailureWithOneInvalidId()
    {
        var response = await client.GetAsync("/api/values?ids=xaaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
    }
}

Controller:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet]
    public IActionResult Get(CustomIdentifier[] ids)
    {
        if (this.ModelState.IsValid == false) return this.BadRequest();

        return this.Ok(ids);
    }
}

Startup:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.ModelBinderProviders.Insert(0, new CutomIdentifierModelBinderProvider());
            //options.ModelBinderProviders.Add(new CutomIdentifierModelBinderProvider());
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

ModelBinder:

public class CutomIdentifierModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        //if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        //{
        //    return new ArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        //}

        if (context.Metadata.ModelType == typeof(CustomIdentifier))
        {
            return new BinderTypeModelBinder(typeof(CustomIdentifierModelBinder));
        }

        return null;
    }
}

public class CustomIdentifierModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
        var parseResult    = CustomIdentifier.TryParse(attemptedValue);

        if (parseResult.Failed)
        {
            bindingContext.Result = ModelBindingResult.Failed();
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, parseResult.Message.Message);
        }
        else
        {
            bindingContext.Model  = parseResult.Value;
            bindingContext.Result = ModelBindingResult.Success(parseResult.Value);
        }

        return Task.CompletedTask;
    }
}

The MVC default ArrayModelBinder of T binds optional arrays correctly and sets ModelState.IsValid to true. If I use my own CustomIdentifierModelBinder however ModelState.IsValid will be false. Empty arrays are not recognized as valid.

How can I solve this problem? Thanks in advance.

Body:
You are very close. Just customize behavior of built-in ArrayModelBinder for the case of missing parameter. If extracted value is an empty string just fill the model with an empty array. In all other cases you could call usual ArrayModelBinder.

Here is a working sample that passes all your 3 tests:

public class CutomIdentifierModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        {
            return new CustomArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        }

        return null;
    }
}

public class CustomArrayModelBinder<T> : IModelBinder
{
    private readonly ArrayModelBinder<T> innerModelBinder;

    public CustomArrayModelBinder(IModelBinder elemeBinder)
    {
        innerModelBinder = new ArrayModelBinder<T>(elemeBinder);
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();

        if (String.IsNullOrEmpty(attemptedValue))
        {
            bindingContext.Model = new T[0];
            bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
            return Task.CompletedTask;
        }

        return innerModelBinder.BindModelAsync(bindingContext);
    }
}


问:
How to force a usage style for a singleton class
Suppose we have a singleton class, where the Instance function(function which returns the singleton instance of the class) has been overloaded. One version takes some parameters and does the object initializing in the class constructor, the other version does not take any parameters.

```<code>1.    myClass::Instance ( int x, int y );
2.    myClass::Instance ( );
</code>```

What we want to achieve is that the user of the class should always call (1) first, and any subsequent calls should be made only to the (2). User should not be allowed to make first call to (2) and once call to (1) is done no subsequent calls to (1) be allowed.

Is it possible to achieve this without putting the burden of checking NULL pointer on the user of the class ?

答:
You can use std::call_once for this (http://en.cppreference.com/w/cpp/thread/call_once). You will require a once_flag (http://en.cppreference.com/w/cpp/thread/once_flag) private member (say m_once_flag).

In 1: You wrap your implementation around a call_once with m_once_flag as first parameter.

In 2: You call 1.

The call_once will take care that the function is only executed the first time round.

Body:
Suppose we have a singleton class, where the Instance function(function which returns the singleton instance of the class) has been overloaded. One version takes some parameters and does the object initializing in the class constructor, the other version does not take any parameters.

1.    myClass::Instance ( int x, int y );
2.    myClass::Instance ( );

What we want to achieve is that the user of the class should always call (1) first, and any subsequent calls should be made only to the (2). User should not be allowed to make first call to (2) and once call to (1) is done no subsequent calls to (1) be allowed.

Is it possible to achieve this without putting the burden of checking NULL pointer on the user of the class ?


问:
How do you make a blurry background and in focus div
Im trying to make this effect.

Blurry background : in focus login div form

I manage to make everything blurry with filter: blur() . But I don't know how to remove the blur effect from my login form with id = newlogin .

```<code> <style>
    body{
      filter: blur(4px);
    }

    #newlogin{
      filter: blur(-4px);
    }
    </style>
</code>```

答: I came up with an idea but idk if it is applicable to your code. Detach the focused div and then insert a glass to your body. Glass will cover whole body and  will be blur. Then attach your detached div to your glass</p>


问:
PyGTK TextView that only accepts single lines
I feel rather silly to ask this, but how does one create a TextView that only accepts single lines? Most other gui toolkits have a method such as "setMultiline" etc, but PyGTK seems to really enjoy multiple lines. Some other languages have "TextFields" for these simpler text boxes.

http://www.pygtk.org/docs/pygtk/class-gtktextview.html#method-gtktextview--set-justification

答:
use gtk.Entry?

http://www.pygtk.org/docs/pygtk/class-gtkentry.html


问:
How can I make a clickable UILabel in Swift 3?
I'm trying to make a clickable UILabel by following this code:

```<code>class ViewNotificationsDetails: UIViewController {
   @IBOutlet weak var back: UILabel!

      override func viewDidLoad() {
          super.viewDidLoad()

          let tap = UITapGestureRecognizer(target: self, action: #selector(ViewNotificationsDetails.tapFunction))
          back.isUserInteractionEnabled = true
          back.addGestureRecognizer(tap)
      }

      @objc func tapFunction(sender:UITapGestureRecognizer) {
          print("tap working")
      }
}
</code>```

But when executing the code, I get the error ->

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value on the line "back.isUserInteractionEnabled = true".

What could be the problem?

答:
Problem is with your Label memory allocation. You have created IBOutlet of label but not connected it with Interface from your Storyboard/XIB view controller.

Go to your Interface Builder: (Storyboard/XIB) View Controller ▶ Select 'Connection Inspector' ▶ Connect label outlet 'back' with Label interface element

Body:
I'm trying to make a clickable UILabel by following this code:

class ViewNotificationsDetails: UIViewController {
   @IBOutlet weak var back: UILabel!

      override func viewDidLoad() {
          super.viewDidLoad()

          let tap = UITapGestureRecognizer(target: self, action: #selector(ViewNotificationsDetails.tapFunction))
          back.isUserInteractionEnabled = true
          back.addGestureRecognizer(tap)
      }

      @objc func tapFunction(sender:UITapGestureRecognizer) {
          print("tap working")
      }
}

But when executing the code, I get the error ->

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value on the line "back.isUserInteractionEnabled = true".

What could be the problem?


问:
Why 'datas' array is always empty?
My code

```<code> $.getJSON('/load4',
    function (data) {
        for (var i = 0; i < data.length; i++) {
            var counter = data[i];
            datas.push([counter.Id, counter.login.substr(0, 25),'3', counter.hash , 'MA']);
        }
    });
console.log("Datas " + datas);
</code>```

I'm trying to fill my array like [[a,b],[a,c]], but can't.

```<code>datas[i] = [counter.Id, counter.login.substr(0, 25),'3', counter.hash , 'MA'];
</code>```

Also doesn't work.

答:
You have to put console.log inside your function instead of outside.

```<code>$.getJSON('/load4',
  function(data) {
    var datas = [];
    for (var i = 0; i < data.length; i++) {
      var counter = data[i];
      datas.push([counter.Id, counter.login.substr(0, 25), '3', counter.hash, 'MA']);
    }
    console.log("Datas " + datas);
  });
</code>```

Title: Why 'datas' array is always empty?

Body:
My code

 $.getJSON('/load4',
    function (data) {
        for (var i = 0; i < data.length; i++) {
            var counter = data[i];
            datas.push([counter.Id, counter.login.substr(0, 25),'3', counter.hash , 'MA']);
        }
    });
console.log("Datas " + datas);

I'm trying to fill my array like [[a,b],[a,c]], but can't.

datas[i] = [counter.Id, counter.login.substr(0, 25),'3', counter.hash , 'MA'];

Also doesn't work.

Body:
You have to put console.log inside your function instead of outside.

$.getJSON('/load4',
  function(data) {
    var datas = [];
    for (var i = 0; i < data.length; i++) {
      var counter = data[i];
      datas.push([counter.Id, counter.login.substr(0, 25), '3', counter.hash, 'MA']);
    }
    console.log("Datas " + datas);
  });


问:
more score for searches closer to the beginning of the sentence (script_exception)
how do I give more score for searches closer to the beginning of the sentence

```<code>query: ipad

phrase2: Apple other word Ipad pro 1
phrase1: Apple pro ipad
phrase2: Apple pro 1
phrase3: Ipad pro 1

GET _search
{
    "query": {
        "match" : {
            "name" : {
              "query" : "ipad"
            }
            ** (....) **
        }
    }
}
</code>```

applying to query order by score result:

```<code>phrase3
phrase1
phrase2
</code>```

I did this script but it does not work

```<code>GET /store/products/_search
{
   "_source": "name",
    "query": {

      "function_score": {
        "query": {
            "query_string" : {
              "query": "apple"
              , "fields":[
                  "name"
               ]
        }
        },
        "functions": [
         {
               "script_score":{
                  "script": "def termInfo = [];  termInfo = _index['name'].get('apple',_POSITIONS); positions = [];score = 0;for (pos in termInfo) { if(positions.contains(pos.position)){ next;} score = score +  pos.position;positions.add(pos.position)}return positions.size();"
               }
            }
        ],"boost_mode":"replace"
      }
    }
}
</code>```

I can not access the variables "_index ..."
Running the script displays this error

```<code>{
  "error": {
    "root_cause": [
      {
        "type": "script_exception",
        "reason": "compile error",
        "script_stack": [
          "... rmInfo = [];  termInfo = _index['name'].get('apple ...",
          "                             ^---- HERE"
        ], ...
</code>```

My version of eslastic search is 5.0

答:
I think you're missing the "inline" property as in the ES5 documentation
https://www.elastic.co/guide/en/elasticsearch/reference/5.5/query-dsl-function-score-query.html#function-script-score

Try this

```<code>"script_score":{
                  "script": {
"inline": "def termInfo = [];  termInfo = _index['name'].get('apple',_POSITIONS); positions = [];score = 0;for (pos in termInfo) { if(positions.contains(pos.position)){ next;} score = score +  pos.position;positions.add(pos.position)}return positions.size();"
               }
}
</code>```

Body:
how do I give more score for searches closer to the beginning of the sentence

query: ipad

phrase2: Apple other word Ipad pro 1
phrase1: Apple pro ipad
phrase2: Apple pro 1
phrase3: Ipad pro 1

GET _search
{
    "query": {
        "match" : {
            "name" : {
              "query" : "ipad"
            }
            ** (....) **
        }
    }
}

applying to query order by score result:

phrase3
phrase1
phrase2

I did this script but it does not work

GET /store/products/_search
{
   "_source": "name",
    "query": {

      "function_score": {
        "query": {
            "query_string" : {
              "query": "apple"
              , "fields":[
                  "name"
               ]
        }
        },
        "functions": [
         {
               "script_score":{
                  "script": "def termInfo = [];  termInfo = _index['name'].get('apple',_POSITIONS); positions = [];score = 0;for (pos in termInfo) { if(positions.contains(pos.position)){ next;} score = score +  pos.position;positions.add(pos.position)}return positions.size();"
               }
            }
        ],"boost_mode":"replace"
      }
    }
}

I can not access the variables "_index ..."
Running the script displays this error

{
  "error": {
    "root_cause": [
      {
        "type": "script_exception",
        "reason": "compile error",
        "script_stack": [
          "... rmInfo = [];  termInfo = _index['name'].get('apple ...",
          "                             ^---- HERE"
        ], ...

My version of eslastic search is 5.0

Body:
I think you're missing the "inline" property as in the ES5 documentation
https://www.elastic.co/guide/en/elasticsearch/reference/5.5/query-dsl-function-score-query.html#function-script-score

Try this

"script_score":{
                  "script": {
"inline": "def termInfo = [];  termInfo = _index['name'].get('apple',_POSITIONS); positions = [];score = 0;for (pos in termInfo) { if(positions.contains(pos.position)){ next;} score = score +  pos.position;positions.add(pos.position)}return positions.size();"
               }
}