问:
Setting a LinearGradientBrush instead of a solid color to a storyboard.targetProperty in a VisualState
I'm wondering how I can set a Storyboard.TargetProperty to a LinearGradientBrush instead of a solid color.
I'm new to VisualStates so please let me know if I'm not given enough information for my question. Mostly I just want to set a Gradient instead of a solid color and can't figure out how. Thanks for any help. I'm working from an example I found at http://msdn.microsoft.com/en-us/library/ms753328.aspx.</p>

```<code> <VisualState x:Name="Disabled">
    <Storyboard>
        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).
                  (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                            Storyboard.TargetName="Border">
                <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledControlDarkColor}" />
              </ColorAnimationUsingKeyFrames>
              <ColorAnimationUsingKeyFrames
                  Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
                                            Storyboard.TargetName="Border">
                <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledForegroundColor}" />
              </ColorAnimationUsingKeyFrames>
              <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).
                  (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                            Storyboard.TargetName="Border">
                <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledBorderDarkColor}" />
              </ColorAnimationUsingKeyFrames>
            </Storyboard>
          </VisualState>
</code>```

答:
The code you pasted animates certain stops in the existing gradient which is applied as the Background property. If you just want to replace the whole Background with a new brush (which happens to be a LinearGradientBrush) you can do so using a ObjectAnimationUsingKeyFrames.

The documentation even gives this example:

```<code>      <Storyboard>

        <!-- ObjectAnimationUsingKeyFrames is used to animate properties that take
             an object as a value. This animation lasts for 4 seconds using 3 KeyFrames which
             swap different brush objects at regular intervals, making the background of the Page
             change. -->
        <ObjectAnimationUsingKeyFrames
          Storyboard.TargetProperty="Background"
          Duration="0:0:4" RepeatBehavior="Forever">
        <ObjectAnimationUsingKeyFrames.KeyFrames>

          <!-- Note: Only discrete interpolation (DiscreteObjectKeyFrame) is available for
          use with ObjectAnimationUsingKeyFrames which merely swaps objects according to
          a specified timeline. Other types of interpolation are too problematic to apply
          to objects.  -->

          <!-- Using a DiscreteObjectKeyFrame, the Page Background suddenly changes
               to a LinearGradientBrush after the first second of the animation. -->
          <DiscreteObjectKeyFrame KeyTime="0:0:1">
            <DiscreteObjectKeyFrame.Value>
              <LinearGradientBrush>
                <LinearGradientBrush.GradientStops>
                  <GradientStop Color="Yellow" Offset="0.0" />
                  <GradientStop Color="Orange" Offset="0.5" />
                  <GradientStop Color="Red" Offset="1.0" />
                </LinearGradientBrush.GradientStops>
              </LinearGradientBrush>
            </DiscreteObjectKeyFrame.Value>
          </DiscreteObjectKeyFrame>

          <!-- ... -->
</code>```

Body:
I'm wondering how I can set a Storyboard.TargetProperty to a LinearGradientBrush instead of a solid color.
I'm new to VisualStates so please let me know if I'm not given enough information for my question. Mostly I just want to set a Gradient instead of a solid color and can't figure out how. Thanks for any help. I'm working from an example I found at http://msdn.microsoft.com/en-us/library/ms753328.aspx.

 <VisualState x:Name="Disabled">
    <Storyboard>
        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).
                  (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                            Storyboard.TargetName="Border">
                <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledControlDarkColor}" />
              </ColorAnimationUsingKeyFrames>
              <ColorAnimationUsingKeyFrames
                  Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
                                            Storyboard.TargetName="Border">
                <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledForegroundColor}" />
              </ColorAnimationUsingKeyFrames>
              <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).
                  (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                            Storyboard.TargetName="Border">
                <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledBorderDarkColor}" />
              </ColorAnimationUsingKeyFrames>
            </Storyboard>
          </VisualState>

Body:
The code you pasted animates certain stops in the existing gradient which is applied as the Background property. If you just want to replace the whole Background with a new brush (which happens to be a LinearGradientBrush) you can do so using a ObjectAnimationUsingKeyFrames.

The documentation even gives this example:

      <Storyboard>

        <!-- ObjectAnimationUsingKeyFrames is used to animate properties that take
             an object as a value. This animation lasts for 4 seconds using 3 KeyFrames which
             swap different brush objects at regular intervals, making the background of the Page
             change. -->
        <ObjectAnimationUsingKeyFrames
          Storyboard.TargetProperty="Background"
          Duration="0:0:4" RepeatBehavior="Forever">
        <ObjectAnimationUsingKeyFrames.KeyFrames>

          <!-- Note: Only discrete interpolation (DiscreteObjectKeyFrame) is available for
          use with ObjectAnimationUsingKeyFrames which merely swaps objects according to
          a specified timeline. Other types of interpolation are too problematic to apply
          to objects.  -->

          <!-- Using a DiscreteObjectKeyFrame, the Page Background suddenly changes
               to a LinearGradientBrush after the first second of the animation. -->
          <DiscreteObjectKeyFrame KeyTime="0:0:1">
            <DiscreteObjectKeyFrame.Value>
              <LinearGradientBrush>
                <LinearGradientBrush.GradientStops>
                  <GradientStop Color="Yellow" Offset="0.0" />
                  <GradientStop Color="Orange" Offset="0.5" />
                  <GradientStop Color="Red" Offset="1.0" />
                </LinearGradientBrush.GradientStops>
              </LinearGradientBrush>
            </DiscreteObjectKeyFrame.Value>
          </DiscreteObjectKeyFrame>

          <!-- ... -->


来源: stackexchange

问:
Error in Entry module not found and in webpack
I'm new to JavaScript and follow a clear node-tutorial on Github.
But whatever I've tried in all modules, I keep getting this error message when I run yarn dev:wds

```<code>    ERROR in Entry module not found: Error: Can't resolve './src' in 'C:\Users\Renate\projects'
    ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src Module not found:
    Error: Can't resolve './src'  in 'C:\Users\Renate\projects'  @ multi (webpack)-dev-
    server/client?http://localhost:8
</code>```

I've tried this solution, but reinstalling babel-loader 7 did not solve my problem. I've also tried to re-intall the entire webpack-module, but that did not solve my problem either.

My webpack.config.babel.js file:

// @flow

import path from 'path'
import webpack from 'webpack'

import { WDS_PORT } from './src/shared/config'
import { isProd } from './src/shared/util'

export default {
  entry: [
    'react-hot-loader/patch',
    './src/client',
  ],
  output: {
    filename: 'js/bundle.js',
    path: path.resolve(__dirname, 'dist/'),
    publicPath: isProd ? '/static/' : `http://localhost:${WDS_PORT}/dist/`,
  },
  module: {
    rules: [
      { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ },
    ],
  },
  devtool: isProd ? false : 'source-map',
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  devServer: {
    port: WDS_PORT,
    hot: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
}```
</div>
</div>
</p>

<p>My babelrc.json file:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "presets": [
    "env",
    "flow",
    "react"
  ],
  "plugins": [
    "flow-react-proptypes"
  ]
}</code>```

My package.json file

{
  "name": "your-project",
  "version": "1.0.0",
  "license": "MIT",
  "browserslist": [
    "> 1%"
  ],
  "scripts": {
    "start": "yarn dev:start",
    "dev:start": "nodemon -e js,jsx --ignore lib --ignore dist --exec babel-node src/server",
    "dev:wds": "webpack-dev-server --progress",
    "prod:build": "rimraf lib dist && babel src -d lib --ignore .test.js && cross-env NODE_ENV=production webpack -p --progress",
    "prod:start": "cross-env NODE_ENV=production pm2 start lib/server && pm2 logs",
    "prod:stop": "pm2 delete server",
    "lint": "eslint src webpack.config.babel.js",
    "test": "yarn lint && flow && jest --coverage",
    "precommit": "yarn test",
    "prepush": "yarn test && yarn prod:build"
  },
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "compression": "^1.7.4",
    "express": "^4.17.1",
    "immutable": "4.0.0-rc.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.5.3",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-actions": "^2.6.5"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/node": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-flow": "^7.8.3",
    "@babel/preset-react": "^7.8.3",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^10.0.3",
    "babel-jest": "^25.1.0",
    "babel-loader": "7",
    "babel-plugin-flow-react-proptypes": "^25.1.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-flow": "^6.23.0",
    "babel-preset-react": "^6.24.1",
    "cross-env": "^7.0.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-plugin-compat": "^3.5.1",
    "eslint-plugin-flowtype": "^4.6.0",
    "eslint-plugin-import": "2.18.2",
    "eslint-plugin-jsx-a11y": "6.2.3",
    "eslint-plugin-react": "^7.18.3",
    "eslint-plugin-react-hooks": "1.7.0",
    "flow-bin": "^0.118.0",
    "husky": "^4.2.1",
    "jest": "^25.1.0",
    "nodemon": "^2.0.2",
    "pm2": "^4.2.3",
    "rimraf": "^3.0.2",
    "webpack": "^4.41.6",
    "webpack-babel-env-deps": "^1.6.3",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.3"
  },
  "type": "module"
}```
</div>
</div>
</p>

<p>My eslintrc.json file</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
{
  "extends": [
    "airbnb",
    "plugin:flowtype/recommended"
  ],
  "plugins": [
    "flowtype",
    "compat"
  ],
  "env": {
    "browser": true,
    "jest": true
  },
  "rules": {
    "semi": [2, "never"],
    "no-unexpected-multiline": 2,
    "compat/compat": 2,
    "linebreak-style": [2, "windows"]
  },
  "parser": "babel-eslint"
}</code>```

for reference, please find attached snapshot of my folder structure here.

And if you check this Github page or this, you will see there are more with the same problem, but no solution worked for me so far. Hope you can help me!

update

I've also tried the suggestion of Alex (see answer here below), did not work.

```<code>    ...
    entry: [
       'react-hot-loader/patch',
       path.resolve(__dirname, './src/client')
       ],

    ...
</code>```

答:
I checked your repo and I solved the webpack issue. the main issue was everytime you imported a jsx file, you need to write the extention as jsx. and also there were some errors inside components so some of the components were not resolved. here is one in button.jsx

```<code>// type Props = {
//   label: string,
//   handleClick: Function,
// }
</code>```

and also since implementation of many packages changed, bundle.js is giving error. for example for react hot reload package, there is no need to import this :

```<code> import { AppContainer } from 'react-hot-loader'
</code>```

check the documentation.

also many babel packages were old version. so i Installed the new packages. you can check the package.json.

implementation of webpack config was also wrong. in webpack.config.js entry point takes relative path but output point takes absolute path. I organized the webpack.config.js.

this project also implements server-side code but for this, you need another webpack.config.js for dev. and also for server-side rendering, you need to use ReactDOM.hydrate and also there are too many important things that this project did not implement. here is the repo:

modified repo

ContentLicense: CC BY-SA 4.0

Body:
I'm new to JavaScript and follow a clear node-tutorial on Github.
But whatever I've tried in all modules, I keep getting this error message when I run yarn dev:wds

    ERROR in Entry module not found: Error: Can't resolve './src' in 'C:\Users\Renate\projects'
    ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src Module not found:
    Error: Can't resolve './src'  in 'C:\Users\Renate\projects'  @ multi (webpack)-dev-
    server/client?http://localhost:8

I've tried this solution, but reinstalling babel-loader 7 did not solve my problem. I've also tried to re-intall the entire webpack-module, but that did not solve my problem either.

My webpack.config.babel.js file:

// @flow

import path from 'path'
import webpack from 'webpack'

import { WDS_PORT } from './src/shared/config'
import { isProd } from './src/shared/util'

export default {
  entry: [
    'react-hot-loader/patch',
    './src/client',
  ],
  output: {
    filename: 'js/bundle.js',
    path: path.resolve(__dirname, 'dist/'),
    publicPath: isProd ? '/static/' : `http://localhost:${WDS_PORT}/dist/`,
  },
  module: {
    rules: [
      { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ },
    ],
  },
  devtool: isProd ? false : 'source-map',
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  devServer: {
    port: WDS_PORT,
    hot: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
}

My babelrc.json file:

{
  "presets": [
    "env",
    "flow",
    "react"
  ],
  "plugins": [
    "flow-react-proptypes"
  ]
}

My package.json file

{
  "name": "your-project",
  "version": "1.0.0",
  "license": "MIT",
  "browserslist": [
    "> 1%"
  ],
  "scripts": {
    "start": "yarn dev:start",
    "dev:start": "nodemon -e js,jsx --ignore lib --ignore dist --exec babel-node src/server",
    "dev:wds": "webpack-dev-server --progress",
    "prod:build": "rimraf lib dist && babel src -d lib --ignore .test.js && cross-env NODE_ENV=production webpack -p --progress",
    "prod:start": "cross-env NODE_ENV=production pm2 start lib/server && pm2 logs",
    "prod:stop": "pm2 delete server",
    "lint": "eslint src webpack.config.babel.js",
    "test": "yarn lint && flow && jest --coverage",
    "precommit": "yarn test",
    "prepush": "yarn test && yarn prod:build"
  },
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "compression": "^1.7.4",
    "express": "^4.17.1",
    "immutable": "4.0.0-rc.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.5.3",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-actions": "^2.6.5"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/node": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-flow": "^7.8.3",
    "@babel/preset-react": "^7.8.3",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^10.0.3",
    "babel-jest": "^25.1.0",
    "babel-loader": "7",
    "babel-plugin-flow-react-proptypes": "^25.1.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-flow": "^6.23.0",
    "babel-preset-react": "^6.24.1",
    "cross-env": "^7.0.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-plugin-compat": "^3.5.1",
    "eslint-plugin-flowtype": "^4.6.0",
    "eslint-plugin-import": "2.18.2",
    "eslint-plugin-jsx-a11y": "6.2.3",
    "eslint-plugin-react": "^7.18.3",
    "eslint-plugin-react-hooks": "1.7.0",
    "flow-bin": "^0.118.0",
    "husky": "^4.2.1",
    "jest": "^25.1.0",
    "nodemon": "^2.0.2",
    "pm2": "^4.2.3",
    "rimraf": "^3.0.2",
    "webpack": "^4.41.6",
    "webpack-babel-env-deps": "^1.6.3",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.3"
  },
  "type": "module"
}

My eslintrc.json file

{
  "extends": [
    "airbnb",
    "plugin:flowtype/recommended"
  ],
  "plugins": [
    "flowtype",
    "compat"
  ],
  "env": {
    "browser": true,
    "jest": true
  },
  "rules": {
    "semi": [2, "never"],
    "no-unexpected-multiline": 2,
    "compat/compat": 2,
    "linebreak-style": [2, "windows"]
  },
  "parser": "babel-eslint"
}

for reference, please find attached snapshot of my folder structure here.

And if you check this Github page or this, you will see there are more with the same problem, but no solution worked for me so far. Hope you can help me!

update

I've also tried the suggestion of Alex (see answer here below), did not work.

    ...
    entry: [
       'react-hot-loader/patch',
       path.resolve(__dirname, './src/client')
       ],

    ...

Body:
I checked your repo and I solved the webpack issue. the main issue was everytime you imported a jsx file, you need to write the extention as jsx. and also there were some errors inside components so some of the components were not resolved. here is one in button.jsx

// type Props = {
//   label: string,
//   handleClick: Function,
// }

and also since implementation of many packages changed, bundle.js is giving error. for example for react hot reload package, there is no need to import this :

 import { AppContainer } from 'react-hot-loader'

check the documentation.

also many babel packages were old version. so i Installed the new packages. you can check the package.json.

implementation of webpack config was also wrong. in webpack.config.js entry point takes relative path but output point takes absolute path. I organized the webpack.config.js.

this project also implements server-side code but for this, you need another webpack.config.js for dev. and also for server-side rendering, you need to use ReactDOM.hydrate and also there are too many important things that this project did not implement. here is the repo:

modified repo


问:
Finding appropriate text
```<code>   <div class="product-name">
                        CLR2811
                    </div>
</code>```

I want to scrape this Product name. My Code :

```<code>ProductTitle = page_soup.find("div",attrs = {'class':'product-name'})
</code>```

This Should Probably return me the right things i-e CLR2811 but when I print ProductTitle its returns me.

```<code><div class="product-name">

                        </div>
</code>```

Just the name is missing
URL = http://www.coolline-group.com/product-details.php?pid=5a3c8ac755d2f

答:
As @AlexDotis pointed you, you need to use the element's text attribute:

```<code>from bs4 import BeautifulSoup
import requests

headers = requests.utils.default_headers()
headers.update({ 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'})
url = "http://www.coolline-group.com/product-details.php?pid=5a3c8ac755d2f"
req = requests.get(url, headers)
soup = BeautifulSoup(req.content, 'html.parser')

name = soup.find("div",attrs = {'class':'product-name'})
print (name.text.strip())
</code>```

Output:

```<code>CLR2811
</code>```

Title: Finding appropriate text

Body:
                        CLR2811

I want to scrape this Product name. My Code :

ProductTitle = page_soup.find("div",attrs = {'class':'product-name'})

This Should Probably return me the right things i-e CLR2811 but when I print ProductTitle its returns me.

Just the name is missing
URL = http://www.coolline-group.com/product-details.php?pid=5a3c8ac755d2f

Body:
As @AlexDotis pointed you, you need to use the element's text attribute:

from bs4 import BeautifulSoup
import requests

headers = requests.utils.default_headers()
headers.update({ 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'})
url = "http://www.coolline-group.com/product-details.php?pid=5a3c8ac755d2f"
req = requests.get(url, headers)
soup = BeautifulSoup(req.content, 'html.parser')

name = soup.find("div",attrs = {'class':'product-name'})
print (name.text.strip())

Output:

CLR2811


问:
First empty row of openpyxl sheet is [] rather than [None]
I made Google spreadsheet similar to the image below and downloaded it as an xlsx.

As you can see, the first row of the sheet is fully empty.

import openpyxl
import numpy as np

sheet = openpyxl.load_workbook("sheet.xlsx", read_only=True)
ws = sheet['Sheet 1']
arr = np.array([[cell.value for cell in row] for row in ws.iter_rows()])
print(arr)
```

<p>I expected this.</p>

```[[None None None None None]
 [None 1.0 1.0 1.0 1.0]
 [None 2.0 2.0 2.0 2.0]
 [None 3.0 3.0 3.0 3.0]
 [None 4.0 4.0 4.0 4.0]]
```

<p>but it actually output this:</p>

<pre class="lang-py prettyprint-override"><code>[list([]) list([None, 1.0, 1.0, 1.0, 1.0])
 list([None, 2.0, 2.0, 2.0, 2.0]) list([None, 3.0, 3.0, 3.0, 3.0])
 list([None, 4.0, 4.0, 4.0, 4.0])]
</code>```

I tried to change it; I added one more empty row and ran the program again:

and it is showing this:

[list([]) list([None, None, None, None, None])
 list([None, 1.0, 1.0, 1.0, 1.0]) list([None, 2.0, 2.0, 2.0, 2.0])
 list([None, 3.0, 3.0, 3.0, 3.0]) list([None, 4.0, 4.0, 4.0, 4.0])]
```

<p>First row and Second row are exactly same(fully empty). but result like below.</p>

<p>WHAT? Why is it different?!</p>

<pre class="lang-py prettyprint-override"><code>FIRST_ROW = list([])
SECOND_ROW = list([None, None, None, None, None])
</code>```

Finally I found that it gives this expected result when I remove read_only parameter from load_workbook()!

But I need to use the read_only option because the xlsx file that I want to load is a VERY BIG FILE.

答: In read-only mode, openpyxl returns exactly what it finds in the file, which in the first row is no cells at all. Because Google Sheets does not save the dimensions of the worksheet then there is no way to know how wide rows should be. This is fine as long as you intend to loop over the rows (which is the best way to proceed), but if you want a reliable number of cells in a row then you will have to set min_col and max_col parameters in ws.iter_rows()

Body:
I made Google spreadsheet similar to the image below and downloaded it as an xlsx.

As you can see, the first row of the sheet is fully empty.

import openpyxl
import numpy as np

sheet = openpyxl.load_workbook("sheet.xlsx", read_only=True)
ws = sheet['Sheet 1']
arr = np.array([[cell.value for cell in row] for row in ws.iter_rows()])
print(arr)

I expected this.

[[None None None None None]
 [None 1.0 1.0 1.0 1.0]
 [None 2.0 2.0 2.0 2.0]
 [None 3.0 3.0 3.0 3.0]
 [None 4.0 4.0 4.0 4.0]]

but it actually output this:

[list([]) list([None, 1.0, 1.0, 1.0, 1.0])
 list([None, 2.0, 2.0, 2.0, 2.0]) list([None, 3.0, 3.0, 3.0, 3.0])
 list([None, 4.0, 4.0, 4.0, 4.0])]

I tried to change it; I added one more empty row and ran the program again:

and it is showing this:

[list([]) list([None, None, None, None, None])
 list([None, 1.0, 1.0, 1.0, 1.0]) list([None, 2.0, 2.0, 2.0, 2.0])
 list([None, 3.0, 3.0, 3.0, 3.0]) list([None, 4.0, 4.0, 4.0, 4.0])]

First row and Second row are exactly same(fully empty). but result like below.

WHAT? Why is it different?!

FIRST_ROW = list([])
SECOND_ROW = list([None, None, None, None, None])

Finally I found that it gives this expected result when I remove read_only parameter from load_workbook()!

But I need to use the read_only option because the xlsx file that I want to load is a VERY BIG FILE.


问:
REPLACEMENT SELECTION SORT:
I am working on Replacement Selection sort project but i keep getting the error Exception in thread main Java.lang.ArrayIndexOutOfBoundsException:10 at ReplacementSelection.swap(ReplacementSelection.java:42) at ReplacementSelection.siftDown(ReplacementSelection.java:69) at Replacement..</p>

```<code>class ReplacementSelection {
    static int[] array = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

    public static void sort() {

        System.out.println("before:" + Arrays.toString(array));

        for (int i = array.length/2; i >= 0; i--) {
            siftDown(i);
        }

        int count = array.length-1;
        while (count > 0)
        {
            swap(array[0], array[count]);
            --count;
            siftDown(0);
        }

        System.out.println("after:" + Arrays.toString(array));
    }

    public static void swap(int i, int j)
    {
        int tmp;
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void siftDown(int index)
    {
        int count = array.length;
        // Left child is at index*2+1. Right child is at index*2+2;
        while (true)
        {
            // first find the largest child
            int largestChild = index*2+1;
            // if left child is larger than count, then done
            if (largestChild >= count)
            {
                break;
            }
            // compare with right child
            if (largestChild+1 < count && array[largestChild] < array[largestChild+1])
            {
                ++largestChild;
            }

            // If item is smaller than the largest child, then swap and continue.
            if (array[index] < array[largestChild])
            {
                swap(array[index], array[largestChild]);
                index = largestChild;
            }
            else
            {
                break;
            }
        }
    }

    public static void main(String[] args){
        ReplacementSelection a = new ReplacementSelection();
        a.sort();
    }
}
</code>```

答:
As @Pajacar123 mentioned, you should learn to use debugger.

In line

swap(array[index], array[largestChild]);

You are passing value from array which is at last index of table(index 9 value 10). Then when in method sawp in line   array[i] = array[j];

j value is 10 while max index of table is 9. That causes exception. You are trying to refer to not existing elemnt.

Title: REPLACEMENT SELECTION SORT:

Body:
I am working on Replacement Selection sort project but i keep getting the error Exception in thread main Java.lang.ArrayIndexOutOfBoundsException:10 at ReplacementSelection.swap(ReplacementSelection.java:42) at ReplacementSelection.siftDown(ReplacementSelection.java:69) at Replacement..

class ReplacementSelection {
    static int[] array = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

    public static void sort() {

        System.out.println("before:" + Arrays.toString(array));

        for (int i = array.length/2; i >= 0; i--) {
            siftDown(i);
        }

        int count = array.length-1;
        while (count > 0)
        {
            swap(array[0], array[count]);
            --count;
            siftDown(0);
        }

        System.out.println("after:" + Arrays.toString(array));
    }

    public static void swap(int i, int j)
    {
        int tmp;
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void siftDown(int index)
    {
        int count = array.length;
        // Left child is at index*2+1. Right child is at index*2+2;
        while (true)
        {
            // first find the largest child
            int largestChild = index*2+1;
            // if left child is larger than count, then done
            if (largestChild >= count)
            {
                break;
            }
            // compare with right child
            if (largestChild+1 < count && array[largestChild] < array[largestChild+1])
            {
                ++largestChild;
            }

            // If item is smaller than the largest child, then swap and continue.
            if (array[index] < array[largestChild])
            {
                swap(array[index], array[largestChild]);
                index = largestChild;
            }
            else
            {
                break;
            }
        }
    }

    public static void main(String[] args){
        ReplacementSelection a = new ReplacementSelection();
        a.sort();
    }
}


问:
How to use arguments from previous command?
I know that Esc + . gives you the last argument of the last command.

But I'm interested in first argument of the last command.
Is there a key binding to do so?

On the same lines, is there a generic way of getting the nth argument from the last command?
I know that in a bash script, you can use $0, $1 etc., but these don't work on the commandline.

Also, what about iterating through the 0th argument of previous commands, like we can do with the last argument by continuously pressing Esc + .?

答: If you are on a mac you will tend to get extended characters with ctrl+letter. I have my right-of-space-bar-option key defined as meta in my terminal (iTerm2) set up. This means I use the key to navigate by word and pull parameters from previous commands.</p>

ContentLicense: CC BY-SA 3.0


问:
How to print out a list with missing numbers?
I have a piece of code that is supposed to print out a list of numbers and also # for every time there is a duplicate number on the list, printing it out should look like this:

list = [6,7,7,9]

6#

7##

8

9#

Here is what i have so far:

```<code>def print_list(list1):
    list2 = [int(i) for i in list1]
    full_set = [x for x in range(list2[0], list2[-1] + 1)]
    list2.extend(full_set)
    list3 = list(set(list2))
    result = sorted([(x, list2.count(x)) for x in list3], key=lambda y: y[1])
    result.sort()
    for elem in result:
        print("{0:>2}".format(elem[0]), "{}".format(elem[1]*"#"))
</code>```

And it comes out wrong:

6 ##

 7 ###

 8 #

 9 ##

Any help is appreciated!

答:
list2.extend(full_set) adds one extra number for each number in the range. You need to reduce 1 from the count of elements in result. You can do it in the list creation

```<code>result = sorted([(x, list2.count(x) - 1) for x in list3], key=lambda y: y[1])
</code>```

or in the print

```<code>for elem in result:
    print("{0:>2}".format(elem[0]), "{}".format((elem[1] - 1)*"#"))
</code>```

output

```<code>6 #
7 ##
8
9 #
</code>```

Body:
I have a piece of code that is supposed to print out a list of numbers and also # for every time there is a duplicate number on the list, printing it out should look like this:

list = [6,7,7,9]

6#

7##

8

9#

Here is what i have so far:

def print_list(list1):
    list2 = [int(i) for i in list1]
    full_set = [x for x in range(list2[0], list2[-1] + 1)]
    list2.extend(full_set)
    list3 = list(set(list2))
    result = sorted([(x, list2.count(x)) for x in list3], key=lambda y: y[1])
    result.sort()
    for elem in result:
        print("{0:>2}".format(elem[0]), "{}".format(elem[1]*"#"))

And it comes out wrong:

6 ##

 7 ###

 8 #

 9 ##

Any help is appreciated!

Body:
list2.extend(full_set) adds one extra number for each number in the range. You need to reduce 1 from the count of elements in result. You can do it in the list creation

result = sorted([(x, list2.count(x) - 1) for x in list3], key=lambda y: y[1])

or in the print

for elem in result:
    print("{0:>2}".format(elem[0]), "{}".format((elem[1] - 1)*"#"))

output

6 #
7 ##
8
9 #


问:
UI not showing up in fragment (RecyclerView)
I created a fragment with RecyclerView with two View Type (Header of the recycler,The rows)
and the model for the recycler so simple it is about product stuff,
finally the adapter with two holder types for the recycler.
 Now I tried to run the emulator calling the fragment but the Ui inside the recycler not showing up,
I was working with this process to create recyclerView with many View types many times and it just working fine.
but now the UI not showing up and no error appears .

the Fragment code

```<code>public class SelectedCategoryFragment extends Fragment implements SelectedCtategoryAdapter.onRowListener {
private RecyclerView productRecyclerView;
private ArrayList<SelectedCategoryModel> categoryModelArrayList = new ArrayList<>();

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

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_selected_category, container, false);
    initialize(v);
    setUpProductRecycler();

    return v;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void setUpProductRecycler() {
    productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(Objects.requireNonNull(getActivity()),
            LinearLayoutManager.VERTICAL);
    dividerItemDecoration.setDrawable(getActivity().getResources().getDrawable(R.drawable.slide_menu_divider));

    productRecyclerView.addItemDecoration(dividerItemDecoration);

    SelectedCtategoryAdapter selectedCtategoryAdapter = new SelectedCtategoryAdapter(productList(), this);

    productRecyclerView.setAdapter(selectedCtategoryAdapter);
}

private ArrayList<SelectedCategoryModel> productList() {

    SelectedCategoryModel p1 = new SelectedCategoryModel("category Name", "", "", "", R.drawable.sweets);
    categoryModelArrayList.add(p1);

    SelectedCategoryModel p2 = new SelectedCategoryModel("sweets", "sweets1", "30", "3", R.drawable.logo);
    categoryModelArrayList.add(p2);

    SelectedCategoryModel p3 = new SelectedCategoryModel("category Name", "sweets2", "44", "", R.drawable.sweets);
    categoryModelArrayList.add(p3);

    SelectedCategoryModel p4 = new SelectedCategoryModel("category Name", "sweets3", "88", "", R.drawable.sweets);
    categoryModelArrayList.add(p4);

    SelectedCategoryModel p5 = new SelectedCategoryModel("category Name", "sweets4", "101", "", R.drawable.sweets);
    categoryModelArrayList.add(p5);

    SelectedCategoryModel p6 = new SelectedCategoryModel("category Name", "sweets5", "45", "", R.drawable.sweets);
    categoryModelArrayList.add(p6);

    SelectedCategoryModel p7 = new SelectedCategoryModel("category Name", "sweets6", "90", "", R.drawable.sweets);
    categoryModelArrayList.add(p7);

    return categoryModelArrayList;
}

private void initialize(View v) {
    productRecyclerView = v.findViewById(R.id.product_recyclerview);
}

@Override
public void onRowClick(int position) {

}
}
</code>```

```<code>**the model**
</code>```

```<code>public class SelectedCategoryModel {

private String productName,productDesc,productRate,deliveryCost;
private int productPhoto;

public SelectedCategoryModel(String productName, String productDesc, String productRate, String deliveryCost, int productPhoto) {
    this.productName = productName;
    this.productDesc = productDesc;
    this.productRate = productRate;
    this.deliveryCost = deliveryCost;
    this.productPhoto = productPhoto;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public String getProductDesc() {
    return productDesc;
}

public void setProductDesc(String productDesc) {
    this.productDesc = productDesc;
}

public String getProductRate() {
    return productRate;
}

public void setProductRate(String productRate) {
    this.productRate = productRate;
}

public String getDeliveryCost() {
    return deliveryCost;
}

public void setDeliveryCost(String deliveryCost) {
    this.deliveryCost = deliveryCost;
}

public int getProductPhoto() {
    return productPhoto;
}

public void setProductPhoto(int productPhoto) {
    this.productPhoto = productPhoto;
}
}
</code>```

adapter

```<code>public class SelectedCtategoryAdapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private static final int header_type = 0;
    private static final int row_type = 1;
    private ArrayList<SelectedCategoryModel>arrayList=new ArrayList<>();
    public int index = -1;
    public SelectedCtategoryAdapter.onRowListener onRowListener;

    public SelectedCtategoryAdapter() {
    }

public SelectedCtategoryAdapter(ArrayList<SelectedCategoryModel> arrayList, SelectedCtategoryAdapter.onRowListener onRowListener) {
    this.arrayList = arrayList;
    this.onRowListener = onRowListener;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view;
    RecyclerView.ViewHolder recyclerViewHolder;
    if (viewType == header_type) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
        recyclerViewHolder = new HeaderHolder(view, viewType, onRowListener);
        return recyclerViewHolder;

    } else if (viewType == row_type) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items, parent, false);
        recyclerViewHolder = new RowHolder(view, viewType, onRowListener);
        return recyclerViewHolder;

    }
    return null;
}

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

    if (holder instanceof SelectedCtategoryAdapter.HeaderHolder) {
        SelectedCtategoryAdapter.HeaderHolder headerHolder = (SelectedCtategoryAdapter.HeaderHolder) holder;
        headerHolder.header.setBackgroundResource(arrayList.get(position).getProductPhoto());

    } else if (holder instanceof SelectedCtategoryAdapter.RowHolder) {
        SelectedCtategoryAdapter.RowHolder rowHolder = (SelectedCtategoryAdapter.RowHolder) holder;
        Log.i("position>>", position + "");
        rowHolder.productName.setText(arrayList.get(position).getProductName());
        rowHolder.productDesc.setText(arrayList.get(position).getProductDesc());
        rowHolder.productRate.setText(arrayList.get(position).getProductRate());
        rowHolder.deliveryCost.setText(arrayList.get(position).getDeliveryCost());
        rowHolder.productPhoto.setImageResource(arrayList.get(position).getProductPhoto());
        rowHolder.categoryProductRow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                onRowListener.onRowClick(position);
                index = position;
                notifyDataSetChanged();

            }
        });
        if (index == position) {
            rowHolder.categoryProductRow.setBackgroundColor(Color.parseColor("#A4CD39"));
        } else {
            rowHolder.categoryProductRow.setBackgroundColor(Color.parseColor("#90a3a3a3"));

        }
    }

}

@Override
public int getItemCount() {
    return 0;
}

public class HeaderHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    SelectedCtategoryAdapter.onRowListener onRowListener;
    TextView headerTitle;
    LinearLayout header;
    public HeaderHolder(View v, int viewtype, SelectedCtategoryAdapter.onRowListener onRowListener) {
        super(v);
        headerTitle = v.findViewById(R.id.category_Header_title);
        header = v.findViewById(R.id.category_Header);
        this.onRowListener = onRowListener;
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        onRowListener.onRowClick(getAdapterPosition());
    }
}

public class RowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    ImageView productPhoto;
    TextView productName,productDesc,productRate,deliveryCost;
    SelectedCtategoryAdapter.onRowListener onRowListener;
    LinearLayout categoryProductRow;

    public RowHolder(View v, int viewtype, SelectedCtategoryAdapter.onRowListener onRowListener) {
        super(v);
        productPhoto = v.findViewById(R.id.product_photo_1);
        productName = v.findViewById(R.id.product_name);
        productDesc = v.findViewById(R.id.product_desc);
        productRate = v.findViewById(R.id.product_rate_1);
        deliveryCost = v.findViewById(R.id.delivery_cost);
        categoryProductRow = v.findViewById(R.id.category_product_row);
        this.onRowListener = onRowListener;
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        onRowListener.onRowClick(getAdapterPosition());
    }
}

@Override
public int getItemViewType(int position) {
    if (position == 0) {
        return header_type;
    }
  else {
        return row_type;
    }
}

public interface onRowListener {
    void onRowClick(int position);
}
</code>```

}

may I have your time to check what is the issue over here ?
thank you

答:
I think change to getItemCount in adapter may help

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

Body:
I created a fragment with RecyclerView with two View Type (Header of the recycler,The rows)
and the model for the recycler so simple it is about product stuff,
finally the adapter with two holder types for the recycler.
 Now I tried to run the emulator calling the fragment but the Ui inside the recycler not showing up,
I was working with this process to create recyclerView with many View types many times and it just working fine.
but now the UI not showing up and no error appears .

the Fragment code

public class SelectedCategoryFragment extends Fragment implements SelectedCtategoryAdapter.onRowListener {
private RecyclerView productRecyclerView;
private ArrayList<SelectedCategoryModel> categoryModelArrayList = new ArrayList<>();

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

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_selected_category, container, false);
    initialize(v);
    setUpProductRecycler();

    return v;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void setUpProductRecycler() {
    productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(Objects.requireNonNull(getActivity()),
            LinearLayoutManager.VERTICAL);
    dividerItemDecoration.setDrawable(getActivity().getResources().getDrawable(R.drawable.slide_menu_divider));

    productRecyclerView.addItemDecoration(dividerItemDecoration);

    SelectedCtategoryAdapter selectedCtategoryAdapter = new SelectedCtategoryAdapter(productList(), this);

    productRecyclerView.setAdapter(selectedCtategoryAdapter);
}

private ArrayList<SelectedCategoryModel> productList() {

    SelectedCategoryModel p1 = new SelectedCategoryModel("category Name", "", "", "", R.drawable.sweets);
    categoryModelArrayList.add(p1);

    SelectedCategoryModel p2 = new SelectedCategoryModel("sweets", "sweets1", "30", "3", R.drawable.logo);
    categoryModelArrayList.add(p2);

    SelectedCategoryModel p3 = new SelectedCategoryModel("category Name", "sweets2", "44", "", R.drawable.sweets);
    categoryModelArrayList.add(p3);

    SelectedCategoryModel p4 = new SelectedCategoryModel("category Name", "sweets3", "88", "", R.drawable.sweets);
    categoryModelArrayList.add(p4);

    SelectedCategoryModel p5 = new SelectedCategoryModel("category Name", "sweets4", "101", "", R.drawable.sweets);
    categoryModelArrayList.add(p5);

    SelectedCategoryModel p6 = new SelectedCategoryModel("category Name", "sweets5", "45", "", R.drawable.sweets);
    categoryModelArrayList.add(p6);

    SelectedCategoryModel p7 = new SelectedCategoryModel("category Name", "sweets6", "90", "", R.drawable.sweets);
    categoryModelArrayList.add(p7);

    return categoryModelArrayList;
}

private void initialize(View v) {
    productRecyclerView = v.findViewById(R.id.product_recyclerview);
}

@Override
public void onRowClick(int position) {

}
}

**the model**

public class SelectedCategoryModel {

private String productName,productDesc,productRate,deliveryCost;
private int productPhoto;

public SelectedCategoryModel(String productName, String productDesc, String productRate, String deliveryCost, int productPhoto) {
    this.productName = productName;
    this.productDesc = productDesc;
    this.productRate = productRate;
    this.deliveryCost = deliveryCost;
    this.productPhoto = productPhoto;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public String getProductDesc() {
    return productDesc;
}

public void setProductDesc(String productDesc) {
    this.productDesc = productDesc;
}

public String getProductRate() {
    return productRate;
}

public void setProductRate(String productRate) {
    this.productRate = productRate;
}

public String getDeliveryCost() {
    return deliveryCost;
}

public void setDeliveryCost(String deliveryCost) {
    this.deliveryCost = deliveryCost;
}

public int getProductPhoto() {
    return productPhoto;
}

public void setProductPhoto(int productPhoto) {
    this.productPhoto = productPhoto;
}
}

adapter

public class SelectedCtategoryAdapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private static final int header_type = 0;
    private static final int row_type = 1;
    private ArrayList<SelectedCategoryModel>arrayList=new ArrayList<>();
    public int index = -1;
    public SelectedCtategoryAdapter.onRowListener onRowListener;

    public SelectedCtategoryAdapter() {
    }

public SelectedCtategoryAdapter(ArrayList<SelectedCategoryModel> arrayList, SelectedCtategoryAdapter.onRowListener onRowListener) {
    this.arrayList = arrayList;
    this.onRowListener = onRowListener;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view;
    RecyclerView.ViewHolder recyclerViewHolder;
    if (viewType == header_type) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
        recyclerViewHolder = new HeaderHolder(view, viewType, onRowListener);
        return recyclerViewHolder;

    } else if (viewType == row_type) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items, parent, false);
        recyclerViewHolder = new RowHolder(view, viewType, onRowListener);
        return recyclerViewHolder;

    }
    return null;
}

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

    if (holder instanceof SelectedCtategoryAdapter.HeaderHolder) {
        SelectedCtategoryAdapter.HeaderHolder headerHolder = (SelectedCtategoryAdapter.HeaderHolder) holder;
        headerHolder.header.setBackgroundResource(arrayList.get(position).getProductPhoto());

    } else if (holder instanceof SelectedCtategoryAdapter.RowHolder) {
        SelectedCtategoryAdapter.RowHolder rowHolder = (SelectedCtategoryAdapter.RowHolder) holder;
        Log.i("position>>", position + "");
        rowHolder.productName.setText(arrayList.get(position).getProductName());
        rowHolder.productDesc.setText(arrayList.get(position).getProductDesc());
        rowHolder.productRate.setText(arrayList.get(position).getProductRate());
        rowHolder.deliveryCost.setText(arrayList.get(position).getDeliveryCost());
        rowHolder.productPhoto.setImageResource(arrayList.get(position).getProductPhoto());
        rowHolder.categoryProductRow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                onRowListener.onRowClick(position);
                index = position;
                notifyDataSetChanged();

            }
        });
        if (index == position) {
            rowHolder.categoryProductRow.setBackgroundColor(Color.parseColor("#A4CD39"));
        } else {
            rowHolder.categoryProductRow.setBackgroundColor(Color.parseColor("#90a3a3a3"));

        }
    }

}

@Override
public int getItemCount() {
    return 0;
}

public class HeaderHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    SelectedCtategoryAdapter.onRowListener onRowListener;
    TextView headerTitle;
    LinearLayout header;
    public HeaderHolder(View v, int viewtype, SelectedCtategoryAdapter.onRowListener onRowListener) {
        super(v);
        headerTitle = v.findViewById(R.id.category_Header_title);
        header = v.findViewById(R.id.category_Header);
        this.onRowListener = onRowListener;
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        onRowListener.onRowClick(getAdapterPosition());
    }
}

public class RowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    ImageView productPhoto;
    TextView productName,productDesc,productRate,deliveryCost;
    SelectedCtategoryAdapter.onRowListener onRowListener;
    LinearLayout categoryProductRow;

    public RowHolder(View v, int viewtype, SelectedCtategoryAdapter.onRowListener onRowListener) {
        super(v);
        productPhoto = v.findViewById(R.id.product_photo_1);
        productName = v.findViewById(R.id.product_name);
        productDesc = v.findViewById(R.id.product_desc);
        productRate = v.findViewById(R.id.product_rate_1);
        deliveryCost = v.findViewById(R.id.delivery_cost);
        categoryProductRow = v.findViewById(R.id.category_product_row);
        this.onRowListener = onRowListener;
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        onRowListener.onRowClick(getAdapterPosition());
    }
}

@Override
public int getItemViewType(int position) {
    if (position == 0) {
        return header_type;
    }
  else {
        return row_type;
    }
}

public interface onRowListener {
    void onRowClick(int position);
}

}

may I have your time to check what is the issue over here ?
thank you

Body:
I think change to getItemCount in adapter may help

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


问:
Get the current fragment object
In my main.xml I have

```<code>  <FrameLayout
        android:id="@+id/frameTitle"
        android:padding="5dp"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="@drawable/title_bg">
            <fragment
              android:name="com.fragment.TitleFragment"
              android:id="@+id/fragmentTag"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" />

  </FrameLayout>
</code>```

And I'm setting fragment object like this

```<code>FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");

// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
</code>```

It is setting different types of Fragment objects (FragmentType2,FragmentType3,...) at different time. Now at some point of time I need to identify which object is currently there.

In short I need to do something like this:

```<code>Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle
</code>```

I tried the following

```<code>TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);
</code>```

and

```<code>    TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");
</code>```

But both the objects (titleFragmentById and titleFragmentByTag  ) are null

Did I miss something?

I'm using Compatibility Package, r3 and developing for API level 7.

findFragmentById() and findFragmentByTag() will work if we have set fragment using fragmentTransaction.replace or fragmentTransaction.add, but will return null if we have set the object at xml (like what I have done in my main.xml). I think I'm missing something in my XML files.

答:
This will give you the current fragment class name -->    </p>

```<code>String fr_name = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
</code>```

Title: Get the current fragment object

Body:
In my main.xml I have

  <FrameLayout
        android:id="@+id/frameTitle"
        android:padding="5dp"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="@drawable/title_bg">
            <fragment
              android:name="com.fragment.TitleFragment"
              android:id="@+id/fragmentTag"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" />

  </FrameLayout>

And I'm setting fragment object like this

FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");

// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

It is setting different types of Fragment objects (FragmentType2,FragmentType3,...) at different time. Now at some point of time I need to identify which object is currently there.

In short I need to do something like this:

Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle

I tried the following

TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);

and

    TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");

But both the objects (titleFragmentById and titleFragmentByTag  ) are null

Did I miss something?

I'm using Compatibility Package, r3 and developing for API level 7.

findFragmentById() and findFragmentByTag() will work if we have set fragment using fragmentTransaction.replace or fragmentTransaction.add, but will return null if we have set the object at xml (like what I have done in my main.xml). I think I'm missing something in my XML files.

Body:
This will give you the current fragment class name -->

String fr_name = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();


问:
Cannot pass data from JSONResult back to handler using ajax
I would like to have the following workflow:

Ajax call to page model handler to trigger database and creation of some viewmodels and return the result as JSONResult

Pass back the result of step 1 to another handler in order to reload a partial view

Between step 1 and 2 there is some data handling using JS. But this is out of scope, since the data is only read and not changed.

Step 1 is working fine. But step 2 does not. Here is a short code example:

Step 1:
Ajax:

```<code>            var searchArea = parseFloat(document.getElementById('txtSearchArea').value);
            var latitude = parseFloat(document.getElementById('hiddenLat').value);
            var longitude = parseFloat(document.getElementById('hiddenLong').value);

            var requestData = JSON.stringify({'latitude': latitude, 'longitude': longitude, 'searchArea': searchArea});

            $.ajax({
                type: "POST",
                url: '@Request.Scheme://@Request.Host@Request.Path?handler=GetCompaniesWithinSearchArea',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: requestData
            }).fail(function (x) {
                alert('Error fetching companies in search area.');
            }).done(function (result) {
                reloadSearchResultPartialView(result);
            });
</code>```

C#:

```<code>        public async Task<JsonResult> OnPostGetCompaniesWithinSearchAreaAsync([FromBody] LatitudeLongitudeSearchArea latitudeLongitudeSearchArea)
        {
            var latitude = latitudeLongitudeSearchArea.Latitude;
            var longitude = latitudeLongitudeSearchArea.Longitude;
            var searchArea = latitudeLongitudeSearchArea.SearchArea;

            var idsOfcompaniesInArea = await _companiesService.GetIdsOfCompaniesWithinSearchAreaAsync(latitude, longitude, searchArea));

            var companyInSearchAreaVMs = await _companiesInSearchAreaViewModelFactory.Create(idsOfcompaniesInArea);

            return new JsonResult(companyInSearchAreaVMs);
        }
</code>```

with _companiesInSearchAreaViewModelFactory.Create returning List<CompanyInSearchAreaViewModel>.

Step 2:
Normally I use the javascript load(...) method to invoke reloading of a partial view.
So I was trying to use this approach again.

JS:

```<code>function reloadSearchResultPartialView(searchResult) {
$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
}
</code>```

where searchResult is the response result of step 1. Data have not been changed between step 1 and 2.

C# - this is the handler for reloading the partial view.

```<code>        public PartialViewResult OnGetReloadCompaniesInAreaList(List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
        {
            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, companyInSearchAreaViewModels)
            };

            return result;
        }
</code>```

The handler for reloading the partial view is called, but the list of viewmodels is always an empty list.

Hopefully someone can point me in the right direction.

Thanks in advance!

答:
Change this:

```<code>function reloadSearchResultPartialView(searchResult) {
   $('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
}
</code>```

to

```<code>function reloadSearchResultPartialView(searchResult) {
     var arrStr = encodeURIComponent(JSON.stringify(searchResult));
     $('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels='+arrStr);
 }
</code>```

And in PageModel

```<code>public PartialViewResult OnGetReloadCompaniesInAreaList(List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
        {
            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, companyInSearchAreaViewModels)
            };

            return result;
        }
</code>```

to

```<code>public PartialViewResult OnGetReloadCompaniesInAreaList(string companyInSearchAreaViewModels)
{
            List<CompanyInSearchAreaViewModel> data = JsonConvert.DeserializeObject<List<CompanyInSearchAreaViewModel>>(companyInSearchAreaViewModels);

            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, data)
            };

            return result;
}
</code>```

Body:
I would like to have the following workflow:

Ajax call to page model handler to trigger database and creation of some viewmodels and return the result as JSONResult

Pass back the result of step 1 to another handler in order to reload a partial view

Between step 1 and 2 there is some data handling using JS. But this is out of scope, since the data is only read and not changed.

Step 1 is working fine. But step 2 does not. Here is a short code example:

Step 1:
Ajax:

            var searchArea = parseFloat(document.getElementById('txtSearchArea').value);
            var latitude = parseFloat(document.getElementById('hiddenLat').value);
            var longitude = parseFloat(document.getElementById('hiddenLong').value);

            var requestData = JSON.stringify({'latitude': latitude, 'longitude': longitude, 'searchArea': searchArea});

            $.ajax({
                type: "POST",
                url: '@Request.Scheme://@Request.Host@Request.Path?handler=GetCompaniesWithinSearchArea',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: requestData
            }).fail(function (x) {
                alert('Error fetching companies in search area.');
            }).done(function (result) {
                reloadSearchResultPartialView(result);
            });

C#:

        public async Task<JsonResult> OnPostGetCompaniesWithinSearchAreaAsync([FromBody] LatitudeLongitudeSearchArea latitudeLongitudeSearchArea)
        {
            var latitude = latitudeLongitudeSearchArea.Latitude;
            var longitude = latitudeLongitudeSearchArea.Longitude;
            var searchArea = latitudeLongitudeSearchArea.SearchArea;

            var idsOfcompaniesInArea = await _companiesService.GetIdsOfCompaniesWithinSearchAreaAsync(latitude, longitude, searchArea));

            var companyInSearchAreaVMs = await _companiesInSearchAreaViewModelFactory.Create(idsOfcompaniesInArea);

            return new JsonResult(companyInSearchAreaVMs);
        }

with _companiesInSearchAreaViewModelFactory.Create returning List<CompanyInSearchAreaViewModel>.

Step 2:
Normally I use the javascript load(...) method to invoke reloading of a partial view.
So I was trying to use this approach again.

JS:

function reloadSearchResultPartialView(searchResult) {
$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
}

where searchResult is the response result of step 1. Data have not been changed between step 1 and 2.

C# - this is the handler for reloading the partial view.

        public PartialViewResult OnGetReloadCompaniesInAreaList(List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
        {
            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, companyInSearchAreaViewModels)
            };

            return result;
        }

The handler for reloading the partial view is called, but the list of viewmodels is always an empty list.

Hopefully someone can point me in the right direction.

Thanks in advance!

Body:
Change this:

function reloadSearchResultPartialView(searchResult) {
   $('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
}

to

function reloadSearchResultPartialView(searchResult) {
     var arrStr = encodeURIComponent(JSON.stringify(searchResult));
     $('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels='+arrStr);
 }

And in PageModel

public PartialViewResult OnGetReloadCompaniesInAreaList(List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
        {
            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, companyInSearchAreaViewModels)
            };

            return result;
        }

to

public PartialViewResult OnGetReloadCompaniesInAreaList(string companyInSearchAreaViewModels)
{
            List<CompanyInSearchAreaViewModel> data = JsonConvert.DeserializeObject<List<CompanyInSearchAreaViewModel>>(companyInSearchAreaViewModels);

            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, data)
            };

            return result;
}


问:
How to reshape a numpy array into 3 dimensional for input to convolutional layer?

I have x_train array which is of 235 elements  and each element is a numpy array of rows 125 and 125 columns . I neeed this array to be in shape of (235,125,125) so as to feed to my convolutional neural network model ((((similar to case when we need to feed MNIST digit array of (6000,28,28) where we have 60000 samples each of which is 28x28 array)))

Can someone tell how to reshape the x_train array to (235,125,125) ?

P.S I initially converted x_train from pandas series to numpy array below is the snapshot

答:
You need to use Numpy's reshape command:

```<code>x_train = x_train.reshape(x_train.shape[0], 125, 125, 1)
</code>```

Have a look at this part of Keras' MNIST CNN tutorial.

Body:
You need to use Numpy's reshape command:

x_train = x_train.reshape(x_train.shape[0], 125, 125, 1)

Have a look at this part of Keras' MNIST CNN tutorial.


问:
Styling a jsx element in react
I have this line of code in my project that generates a certain percentage and shows it on the dashboard.

```<code>   <text
          className="netProfit-circle-text"
          x="50%"
          y="50%"
          dy=".2em"
          textAnchor="middle"
        >
          {`${this.state.percentage}%`}
        </text>
</code>```

What I want to do is to be able to style the "%" and change its size using CSS. How can I do this?
Thanks in advance.

Regards.

答:
You can use the tspan element to wrap the % part. The tspan element can be styled to look visually different than the rest of the text's content. Link to MDN

<tspan>%</tspan>

Title: Styling a jsx element in react

Body:
I have this line of code in my project that generates a certain percentage and shows it on the dashboard.

   <text
          className="netProfit-circle-text"
          x="50%"
          y="50%"
          dy=".2em"
          textAnchor="middle"
        >
          {`${this.state.percentage}%`}
        </text>

What I want to do is to be able to style the "%" and change its size using CSS. How can I do this?
Thanks in advance.

Regards.


问:
Synchronous mongoose request
Is it possible to process a db.model.find() query inside of function context and retrieve a result without using callbacks and promises with mongoose library?

I need to get assured, if some user exists in process of running controller, so, I can't minimize current scope to callback due to large amount of same operations (for example, communication with database). Also I'm trying to realize MVC model in my project, so, I want to keep the helper libs (modules) in separated files. That's why I don't want to use any callbacks or promises - they will much times complicate everything even more then things already do.

For example, how should I rewrite the following code to be executed successfully (if it's actually possible) (you can ignore login model and controller - they are written to represent complicacy if to rewrite that code using callbacks):

user.js lib

```<code>var db = require('./lib/db');

class User{
    constructor(id){ //get user by id
        var result = db.models.user.findOne({_id: id}); //unsupported syntax in real :(
        if(!result || result._id != _id)
            return false;
        else{
            this.userInfo = result;

            return result;
        }

    }
}

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

login model

```<code>var user = require('./lib/user')
var model = {};

model.checkUserLogged(function(req){
    if(!req.user.id || req.user.id == undefined)
        return false;

    if(!(this.user = new user(req.user.id)))
        return false;
    else
        return true;
});

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

login controller

```<code>var proxy = require('express').router();

proxy.all('/login', function(req, res){

    var model = require('./models/login');

    if(!model.checkUserLogged()){
        console.log('User is not logged in!');
        res.render('unlogged', model);
    }else{
        console.log('User exists in database!');
        res.render('logged_in', model);
    }

});
</code>```

Generator functions/yields, async/await (es2017), and everything et cetera can be used just to solve the problem without nesting.

Thx in advance.

答:
Old question, but I want to share a method for handling this that I didn't see in my first couple searches.

I want to get data from a model, run some logic and return the results from that logic. I need a promise wrapper around my call to the model.

Below is a slightly abstracted function that takes a model to run a mongoose/mongo query on, and a couple params to help it do some logic. It then returns the value that is expected in the promise or rejects.

```<code>export function promiseFunction(aField: string, aValue, model: Model<ADocument, {}>): Promise<aType> {
    return new Promise<string>((resolve, reject) => {
      model.findOne({[aField]: aValue}, (err, theDocument) => {
        if(err){
          reject(err.toString());
        } else {
          if(theDocument.someCheck === true){
            return(theDocument.matchingTypeField)
          } else {
            reject("there was an error of some type")
          }
        }
      });
    })
}

</code>```

Title: Synchronous mongoose request

Body:
Is it possible to process a db.model.find() query inside of function context and retrieve a result without using callbacks and promises with mongoose library?

I need to get assured, if some user exists in process of running controller, so, I can't minimize current scope to callback due to large amount of same operations (for example, communication with database). Also I'm trying to realize MVC model in my project, so, I want to keep the helper libs (modules) in separated files. That's why I don't want to use any callbacks or promises - they will much times complicate everything even more then things already do.

For example, how should I rewrite the following code to be executed successfully (if it's actually possible) (you can ignore login model and controller - they are written to represent complicacy if to rewrite that code using callbacks):

user.js lib

var db = require('./lib/db');

class User{
    constructor(id){ //get user by id
        var result = db.models.user.findOne({_id: id}); //unsupported syntax in real :(
        if(!result || result._id != _id)
            return false;
        else{
            this.userInfo = result;

            return result;
        }

    }
}

module.exports = User;

login model

var user = require('./lib/user')
var model = {};

model.checkUserLogged(function(req){
    if(!req.user.id || req.user.id == undefined)
        return false;

    if(!(this.user = new user(req.user.id)))
        return false;
    else
        return true;
});

module.exports = model;

login controller

var proxy = require('express').router();

proxy.all('/login', function(req, res){

    var model = require('./models/login');

    if(!model.checkUserLogged()){
        console.log('User is not logged in!');
        res.render('unlogged', model);
    }else{
        console.log('User exists in database!');
        res.render('logged_in', model);
    }

});

Generator functions/yields, async/await (es2017), and everything et cetera can be used just to solve the problem without nesting.

Thx in advance.

Body:
Old question, but I want to share a method for handling this that I didn't see in my first couple searches.

I want to get data from a model, run some logic and return the results from that logic. I need a promise wrapper around my call to the model.

Below is a slightly abstracted function that takes a model to run a mongoose/mongo query on, and a couple params to help it do some logic. It then returns the value that is expected in the promise or rejects.

export function promiseFunction(aField: string, aValue, model: Model<ADocument, {}>): Promise<aType> {
    return new Promise<string>((resolve, reject) => {
      model.findOne({[aField]: aValue}, (err, theDocument) => {
        if(err){
          reject(err.toString());
        } else {
          if(theDocument.someCheck === true){
            return(theDocument.matchingTypeField)
          } else {
            reject("there was an error of some type")
          }
        }
      });
    })
}


问:
How to make follower-following system with django model
I'm a student studying django rest framework

I'm making a simple sns with django rest framework

I need follower-following system. So, I tried to make it but there is some trouble

First this is my user model with AbstractBaseUser and PermissionsMixin

```<code>class User(AbstractBaseUser, PermissionsMixin):
    user_id = models.CharField(max_length=100, unique=True, primary_key=True)
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    is_staff = models.BooleanField(default=False)
    followers = models.ManyToManyField('self', related_name='follower',blank=True)
    following = models.ManyToManyField('self', related_name='following',blank=True)
    profile_image = models.ImageField(blank=True)
</code>```

the field followers is people who follows me and following is whom i follow

When i add following with this APIView class

```<code>class AddFollower(APIView):
    permission_classes = [IsAuthenticated, ]
    def post(self, requset, format=None):
        user = User.objects.get(user_id=self.request.data.get('user_id'))
        follow = User.objects.get(user_id=self.request.data.get('follow'))
        user.following.add(follow)
        user.save()
        follow.followers.add(user)
        follow.save()
        print(str(user) + ", " + str(follow))
        return JsonResponse({'status':status.HTTP_200_OK, 'data':"", 'message':"follow"+str(follow.user_id)})
</code>```

The user_id is me and the follow is whom i want to follow

I want to add follow to user_id's following field and add user_id to follow's followers field

But it does not work

What i want for result is like this (with user information api)

```<code>{
        "followers": [],
        "following": [
            "some user"
        ],
}
</code>```

some user's user info

```<code>{
        "followers": [
            "user above"
        ],
        "following": [
        ],
}
</code>```

But real result is like this

```<code>{
        "followers": [
            "some user"
        ],
        "following": [
            "some user"
        ],
}
</code>```

some user's user info

```<code>{
        "followers": [
            "user above"
        ],
        "following": [
            "user above"
        ],
}
</code>```

this is not what i want

I have no idea with this problem i need some help

Thank you

答:
The above solutions are fine and optimal, but I would like to supply a detailed solution for anyone who wants to implement such functionality.

The intermediary Model

```<code>from django.contrib.auth import get_user_model
UserModel = get_user_model()

class UserFollowing(models.Model):

    user_id = models.ForeignKey(UserModel, related_name="following", on_delete=models.CASCADE)
    following_user_id = models.ForeignKey(UserModel, related_name="followers", on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user_id','following_user_id'],  name="unique_followers")
        ]

        ordering = ["-created"]

    def __str__(self):
        f"{self.user_id} follows {self.following_user_id}"

</code>```

THE SERIALIZER for follow and unfollow

Your View for follow and unfollow

```<code>class UserFollowingViewSet(viewsets.ModelViewSet):

    permission_classes = (IsAuthenticatedOrReadOnly,)
    serializer_class = UserFollowingSerializer
    queryset = models.UserFollowing.objects.all()
</code>```

Custom FollowersSerializer and FollowingSerializer

```<code>class FollowingSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserFollowing
        fields = ("id", "following_user_id", "created")
</code>```
```<code>class FollowersSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserFollowing
        fields = ("id", "user_id", "created")
</code>```

Your UserSerializer

```<code>from django.contrib.auth import get_user_model

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):

    following = serializers.SerializerMethodField()
    followers = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            "id",
            "email",
            "username",
            "following",
            "followers",
        )
        extra_kwargs = {"password": {"write_only": True}}

    def get_following(self, obj):
        return FollowingSerializer(obj.following.all(), many=True).data

    def get_followers(self, obj):
        return FollowersSerializer(obj.followers.all(), many=True).data
</code>```

Body:
I'm a student studying django rest framework

I'm making a simple sns with django rest framework

I need follower-following system. So, I tried to make it but there is some trouble

First this is my user model with AbstractBaseUser and PermissionsMixin

class User(AbstractBaseUser, PermissionsMixin):
    user_id = models.CharField(max_length=100, unique=True, primary_key=True)
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    is_staff = models.BooleanField(default=False)
    followers = models.ManyToManyField('self', related_name='follower',blank=True)
    following = models.ManyToManyField('self', related_name='following',blank=True)
    profile_image = models.ImageField(blank=True)

the field followers is people who follows me and following is whom i follow

When i add following with this APIView class

class AddFollower(APIView):
    permission_classes = [IsAuthenticated, ]
    def post(self, requset, format=None):
        user = User.objects.get(user_id=self.request.data.get('user_id'))
        follow = User.objects.get(user_id=self.request.data.get('follow'))
        user.following.add(follow)
        user.save()
        follow.followers.add(user)
        follow.save()
        print(str(user) + ", " + str(follow))
        return JsonResponse({'status':status.HTTP_200_OK, 'data':"", 'message':"follow"+str(follow.user_id)})

The user_id is me and the follow is whom i want to follow

I want to add follow to user_id's following field and add user_id to follow's followers field

But it does not work

What i want for result is like this (with user information api)

{
        "followers": [],
        "following": [
            "some user"
        ],
}

some user's user info

{
        "followers": [
            "user above"
        ],
        "following": [
        ],
}

But real result is like this

{
        "followers": [
            "some user"
        ],
        "following": [
            "some user"
        ],
}

some user's user info

{
        "followers": [
            "user above"
        ],
        "following": [
            "user above"
        ],
}

this is not what i want

I have no idea with this problem i need some help

Thank you

Body:
The above solutions are fine and optimal, but I would like to supply a detailed solution for anyone who wants to implement such functionality.

The intermediary Model

from django.contrib.auth import get_user_model
UserModel = get_user_model()

class UserFollowing(models.Model):

    user_id = models.ForeignKey(UserModel, related_name="following", on_delete=models.CASCADE)
    following_user_id = models.ForeignKey(UserModel, related_name="followers", on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user_id','following_user_id'],  name="unique_followers")
        ]

        ordering = ["-created"]

    def __str__(self):
        f"{self.user_id} follows {self.following_user_id}"

THE SERIALIZER for follow and unfollow

Your View for follow and unfollow

class UserFollowingViewSet(viewsets.ModelViewSet):

    permission_classes = (IsAuthenticatedOrReadOnly,)
    serializer_class = UserFollowingSerializer
    queryset = models.UserFollowing.objects.all()

Custom FollowersSerializer and FollowingSerializer

class FollowingSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserFollowing
        fields = ("id", "following_user_id", "created")

class FollowersSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserFollowing
        fields = ("id", "user_id", "created")

Your UserSerializer

from django.contrib.auth import get_user_model

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):

    following = serializers.SerializerMethodField()
    followers = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            "id",
            "email",
            "username",
            "following",
            "followers",
        )
        extra_kwargs = {"password": {"write_only": True}}

    def get_following(self, obj):
        return FollowingSerializer(obj.following.all(), many=True).data

    def get_followers(self, obj):
        return FollowersSerializer(obj.followers.all(), many=True).data


问:
Side Menu matching full screen
CSS

```<code>.sidenav {
    height: 100%;
    position: relative;
    overflow-y: scroll;
    background: #000000;
    width: 15%;
}
</code>```

Setting the height to 100% makes the menu to cover the full screen properly, but if the content in my page is more and i need to scroll down, the side menu looks awkward as its height is the same as the screen size of my computer.

I want the height of the scrollbar to take up the whole screens height even when i scroll down. How can i achieve that

答:
```<code>height: 100%
max-height: 100%
overflow-y: scroll
</code>```

Can you try that?

Title: Side Menu matching full screen

Body:
CSS

.sidenav {
    height: 100%;
    position: relative;
    overflow-y: scroll;
    background: #000000;
    width: 15%;
}

Setting the height to 100% makes the menu to cover the full screen properly, but if the content in my page is more and i need to scroll down, the side menu looks awkward as its height is the same as the screen size of my computer.

I want the height of the scrollbar to take up the whole screens height even when i scroll down. How can i achieve that

Body:
height: 100%
max-height: 100%
overflow-y: scroll

Can you try that?


Title: Adding a upper level index to a MultiIndex pandas df

Body:
If I have a df:

   VLA
0   40
1  200

and then a multi-index that looks like this:

                stuff1                         ...  stuff2
                   p1            p1       p2  ...       p3       p4       p4
dates                                          ...
2019-12-01  596.973988  1268.966237  0.969522  ...  2.344248  1.365735  2.903094
2019-12-02    1.100081     2.338402  1.249667  ...  2.815914  1.387209  2.948740

How would I create a dataframe that takes VLA as an upper index on the second dataframe so it would look like this:

VLA                             40            ...              200
                stuff1                         ...  stuff2
                   p1            p1       p2  ...       p3       p4       p4
dates                                          ...
2019-12-01       596            1268 0.969522  ...  2.344248  1.365735  2.903094
2019-12-02    1.100081     2.338402  1.249667  ...  2.815914  1.387209  2.948740

print (df.columns.levels[0])

Index(['stuff1', 'stuff2', 'stuff3', 'stuff4', 'stuff5', 'stuff6', 'stuff7'], dtype='object')

print (lvl0.map(d)

Float64Index([ 43.0,  43.0,  43.0,  43.0,  43.0,  43.0,  43.0,  43.0, 210.0,
              210.0, 210.0, 210.0, 210.0, 210.0, 210.0, 210.0,   nan,   nan,
                nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,
                nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,
                nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,
                nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,   nan,
                nan,   nan],
             dtype='float64')

Body:
Use Index.get_level_values:

mux = pd.MultiIndex.from_tuples([('hh1', '43'),
('hh2', '43'),
('hh3', '43'),
('hh4', '43'),
('hh1', '210'),
('hh2', '210'),
('hh3', '210'),
('hh4', '210')],
)
final2 = pd.DataFrame(columns=mux)

mux = pd.MultiIndex.from_product([final2.columns.get_level_values(0).unique(), ['43', '210']])
print (mux)
MultiIndex([('hh1',  '43'),
            ('hh1', '210'),
            ('hh2',  '43'),
            ('hh2', '210'),
            ('hh3',  '43'),
            ('hh3', '210'),
            ('hh4',  '43'),
            ('hh4', '210')],
           )