问:
Failed to load the native TensorFlow runtime - TensorFlow 2.1
I have a desktop computer and a notebook, when I tried to install tensorflow on a notebook just by using pip install tensorflow it worked ok, then I tried the same on my desktop computer and when I tried to run the simplest possible code:

import tensorflow as tf

from tensorflow.keras import Sequential

print("done")
```

<p>I got this quite complex error message:</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242,
in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342,
in load_dynamic
    return _load(spec)
ImportError: DLL load failed: Uvedený modul nebyl nalezen.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\Users\Mechatrnk\.vscode\extensions\ms-python.python-2020.1.57204\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\__main__.py", line 45, in <module>
    cli.main()
  File "c:\Users\Mechatrnk\.vscode\extensions\ms-python.python-2020.1.57204\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd/..\ptvsd\server\cli.py", line 362, in main
    run()
  File "c:\Users\Mechatrnk\.vscode\extensions\ms-python.python-2020.1.57204\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd/..\ptvsd\server\cli.py", line 204, in run_file
    runpy.run_path(options.target, run_name="__main__")
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\OneDrive\VŠ\DP - Design of Autonomous Vehicle Simulator\Programming\Q-Learning\DeepQLearningSentdex.py", line 1, in <module>
    from tensorflow.keras import Sequential
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 101, in <module>
    from tensorflow_core import *
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242,
in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342,
in load_dynamic
    return _load(spec)
ImportError: DLL load failed: Module not found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
PS C:\Users\Mechatrnk>
</code>```

How can I fix this error?

If it helps, my GPU is msi GeForce GTX 1060

答: On Windows 10, I managed to solve this issue by downloading and installing the latest Microsoft Visual C++ redistributable from here.</p>

Body:
I have a desktop computer and a notebook, when I tried to install tensorflow on a notebook just by using pip install tensorflow it worked ok, then I tried the same on my desktop computer and when I tried to run the simplest possible code:

import tensorflow as tf

from tensorflow.keras import Sequential

print("done")

I got this quite complex error message:

Traceback (most recent call last):
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242,
in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342,
in load_dynamic
    return _load(spec)
ImportError: DLL load failed: Uvedený modul nebyl nalezen.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\Users\Mechatrnk\.vscode\extensions\ms-python.python-2020.1.57204\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd\__main__.py", line 45, in <module>
    cli.main()
  File "c:\Users\Mechatrnk\.vscode\extensions\ms-python.python-2020.1.57204\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd/..\ptvsd\server\cli.py", line 362, in main
    run()
  File "c:\Users\Mechatrnk\.vscode\extensions\ms-python.python-2020.1.57204\pythonFiles\lib\python\new_ptvsd\wheels\ptvsd/..\ptvsd\server\cli.py", line 204, in run_file
    runpy.run_path(options.target, run_name="__main__")
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\OneDrive\VŠ\DP - Design of Autonomous Vehicle Simulator\Programming\Q-Learning\DeepQLearningSentdex.py", line 1, in <module>
    from tensorflow.keras import Sequential
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 101, in <module>
    from tensorflow_core import *
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242,
in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Mechatrnk\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342,
in load_dynamic
    return _load(spec)
ImportError: DLL load failed: Module not found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
PS C:\Users\Mechatrnk>

How can I fix this error?

If it helps, my GPU is msi GeForce GTX 1060


来源: stackexchange

问:
Image with hyperlink stretches across viewport
I've tried resizing the div. After that I gave up on the div as the problem seems not to be there, but in the hyperlink itself. When I remove the hyperlink it seems to fit in. I need to preserve the hyperlink, size the border to fit the image (because I need two images in the same line) and keep the zoom inside the div.

Here's the fiddle: https://jsfiddle.net/Zvonimir1308/5p2y16w7/26/

a[href $= ".jpg"] {
  margin: 20px;
  border: 1px solid black;
  overflow: hidden;
}

a[href $= ".jpg"] img {
  transition: transform .4s;
}

a[href $= ".jpg"]:hover img {
  transform: scale(1.3);
  transform-origin: 50% 50%;
}

a[href $= ".jpg"] {
  display: flex;
  columns: 2;
  margin: 0 0;
  border-radius: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="#container">
  <img src="https://as.ftcdn.net/r/v1/pics/7b11b8176a3611dbfb25406156a6ef50cd3a5009/home/discover_collections/optimized/image-2019-10-11-11-36-27-681.jpg">
</div></code>```

答:
First: your div id should be set as
, there is no need to insert the # in there.

The div default display is set to block. So, after fixing the div id, just add display: inline-block to the div:

```<code>#container {
  display: inline-block;
}
</code>```

Why changing from block to inline-block? According to w3school

Compared to display: block, the major difference is that display: inline-block does not add a line-break after the element, so the element can sit next to other elements.

Also, if you have questions about inline vs inline-block vs block, I recommend you to read this answer.

Final result:

a[href $= ".jpg"] {
  margin: 20px;
  border: 1px solid black;
  overflow: hidden;
}

a[href $= ".jpg"] img {
  transition: transform .4s;
}

a[href $= ".jpg"]:hover img {
  transform: scale(1.3);
  transform-origin: 50% 50%;
}

a[href $= ".jpg"] {
  display: flex;
  columns: 2;
  margin: 0 0;
  border-radius: 5px;
}

#container {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <img src="https://as.ftcdn.net/r/v1/pics/7b11b8176a3611dbfb25406156a6ef50cd3a5009/home/discover_collections/optimized/image-2019-10-11-11-36-27-681.jpg">
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
First: your div id should be set as <div id="container">, there is no need to insert the # in there.

The div default display is set to block. So, after fixing the div id, just add display: inline-block to the div:

#container {
  display: inline-block;
}

Why changing from block to inline-block? According to w3school

Compared to display: block, the major difference is that display: inline-block does not add a line-break after the element, so the element can sit next to other elements.

Also, if you have questions about inline vs inline-block vs block, I recommend you to read this answer.

Final result:

a[href $= ".jpg"] {
  margin: 20px;
  border: 1px solid black;
  overflow: hidden;
}

a[href $= ".jpg"] img {
  transition: transform .4s;
}

a[href $= ".jpg"]:hover img {
  transform: scale(1.3);
  transform-origin: 50% 50%;
}

a[href $= ".jpg"] {
  display: flex;
  columns: 2;
  margin: 0 0;
  border-radius: 5px;
}

#container {
  display: inline-block;
}

<div id="container">
  <a href="https://as.ftcdn.net/r/v1/pics/7b11b8176a3611dbfb25406156a6ef50cd3a5009/home/discover_collections/optimized/image-2019-10-11-11-36-27-681.jpg"><img src="https://as.ftcdn.net/r/v1/pics/7b11b8176a3611dbfb25406156a6ef50cd3a5009/home/discover_collections/optimized/image-2019-10-11-11-36-27-681.jpg"></a>
</div>


问:
Creating a hooks-based setState that has a callback
I made the following example, when a setState occurs using the hooks, the possibility of being able to receive a callback is given when the operation was successful returning the changed state.

Kind of like it did:

```<code>this.setState({a: 1}, () => {
   console.log("Ok.");
});
</code>```

I wanted to know your opinion about it what do you think?

Could there be problems?

Can it be improved?

Link: codesandbox

App:

```<code>import React from "react";
import { useStateCallback } from "./useStateCallback";

export default function App() {
  const [stateString, setStateString] = useStateCallback("James");
  const [stateObj, setStateObj] = useStateCallback({
    name: "James",
    surname: "Bond",
    number: 7
  });

  const { name, surname, number } = stateObj;

  React.useEffect(() => {
    setStateString("Bond");
    setStateString("Arthur", res => {
      console.log("State:", res);
    });
    setStateObj({
      ...stateObj,
      number: 1
    });
    setStateObj(
      {
        ...stateObj,
        name: "Arthur",
        surname: "Conan",
        number: 21
      },
      res => {
        console.log("State:", res);
      }
    );
  }, []);

  return (
    <div>
      State: {stateString}
      <br />
      <br />
      Name: {name}
      <br />
      Surname: {surname}
      <br />
      Number: {number}
      <br />
    </div>
  );
}
</code>```

useStateCallback:

```<code>import { useState } from "react";
const useStateCallback = initialState => {
  const [state, setState] = useState(initialState);
  return [
    state,
    (state, callback) => {
      setState(state);
      return callback && callback(state);
    }
  ];
};
export { useStateCallback };
</code>```

答:
Two problems I see with this implementation:

You need to check if callback is a function or you opening a room for a runtime error:

```<code>setStateString('Arthur', { hello: 'hello' });
</code>```

On every render, the custom hook returns a new instance of the setter function, which is not an expected behavior that can lead to rerunning useEffects:

```<code>export default function App() {
  const [stateString, setStateString] = useStateCallback('James');
  const [, setCounter] = useState(0);

  React.useEffect(() => {
    setStateString('Arthur', res => {
      console.log('State:', res);
    });
  }, [setStateString]);

  return (
    <div>
      State: {stateString}
      <button onClick={() => setCounter(p => p + 1)}>Render</button>
    </div>
  );
}
</code>```

To fix those issues, check the type of callback and memoize the setter:

```<code>export const useStateCallback = initialState => {
  const [state, setState] = useState(initialState);
  const setter = useCallback((state, callback) => {
    setState(state);
    return typeof callback === 'function' && callback(state);
  }, []);
  return [state, setter];
};
</code>```

Side note, you may notice that this hook is exactly what useEffect does.

Body:
I made the following example, when a setState occurs using the hooks, the possibility of being able to receive a callback is given when the operation was successful returning the changed state.

Kind of like it did:

this.setState({a: 1}, () => {
   console.log("Ok.");
});

I wanted to know your opinion about it what do you think?

Could there be problems?

Can it be improved?

Link: codesandbox

App:

import React from "react";
import { useStateCallback } from "./useStateCallback";

export default function App() {
  const [stateString, setStateString] = useStateCallback("James");
  const [stateObj, setStateObj] = useStateCallback({
    name: "James",
    surname: "Bond",
    number: 7
  });

  const { name, surname, number } = stateObj;

  React.useEffect(() => {
    setStateString("Bond");
    setStateString("Arthur", res => {
      console.log("State:", res);
    });
    setStateObj({
      ...stateObj,
      number: 1
    });
    setStateObj(
      {
        ...stateObj,
        name: "Arthur",
        surname: "Conan",
        number: 21
      },
      res => {
        console.log("State:", res);
      }
    );
  }, []);

  return (

      State: {stateString}

      Name: {name}

      Surname: {surname}

      Number: {number}

  );
}

useStateCallback:

import { useState } from "react";
const useStateCallback = initialState => {
  const [state, setState] = useState(initialState);
  return [
    state,
    (state, callback) => {
      setState(state);
      return callback && callback(state);
    }
  ];
};
export { useStateCallback };

Body:
Two problems I see with this implementation:

You need to check if callback is a function or you opening a room for a runtime error:

setStateString('Arthur', { hello: 'hello' });

On every render, the custom hook returns a new instance of the setter function, which is not an expected behavior that can lead to rerunning useEffects:

export default function App() {
  const [stateString, setStateString] = useStateCallback('James');
  const [, setCounter] = useState(0);

  React.useEffect(() => {
    setStateString('Arthur', res => {
      console.log('State:', res);
    });
  }, [setStateString]);

  return (
    <div>
      State: {stateString}
      <button onClick={() => setCounter(p => p + 1)}>Render</button>
    </div>
  );
}

To fix those issues, check the type of callback and memoize the setter:

export const useStateCallback = initialState => {
  const [state, setState] = useState(initialState);
  const setter = useCallback((state, callback) => {
    setState(state);
    return typeof callback === 'function' && callback(state);
  }, []);
  return [state, setter];
};

Side note, you may notice that this hook is exactly what useEffect does.


问:
Mapping child collections
I'm using auto mapper to map from a view model to dto. Below are some test examples.

public class Vehicle
{
    public Vehicle()
    {
        AboutYou = new AboutYou();
        TestModels = new List<TestModel>();
    }

    public AboutYou AboutYou { get; set; }

    public List<TestModel> TestModels { get; set; }
}

public class AboutYou
{
    [DisplayName("What is your title")]
    public int Title { get; set; }
}

public class TestModel
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}
```

<p>And Dto.</p>

<pre class="lang-cs prettyprint-override"><code>public class TestModel
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

public class VehicleDto
{
    public VehicleDto()
    {
        TestDtos = new List<TestDto>();
    }

    public int AboutYouTitle { get; set; }

    public List<TestDto> TestDtos { get; set; }
}

public class TestDto
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}
</code>```

And this is my profile.

public class VehicleMapping : Profile
{
    public VehicleMapping()
    {
        CreateMap<Vehicle, VehicleDto>().ReverseMap();
        CreateMap<TestModel, TestDto>().ReverseMap();

    }
}
```

The problem I'm having is that I need to have the reversemap in place so it flattens and unflattens the AboutYou class. However, the TestModels collection is not being mapped to the TestDtos collection. I can apply a AfterMap but then I have to manually unflatten the AboutYou object. Any ideas how I can set it up so that the AboutYou is flattened and unflattened and the collections are mapped as well?

答:
Specifying how to map members explicitly did the trick for me

public class VehicleMapping : Profile
{
    public VehicleMapping()
    {
        CreateMap<Vehicle, VehicleDto>()
            .ForMember(x => x.TestDtos, opt => opt.MapFrom(src => src.TestModels))
            .ReverseMap();
        CreateMap<TestModel, TestDto>().ReverseMap();

    }
}
```

Title: Mapping child collections

Body:
I'm using auto mapper to map from a view model to dto. Below are some test examples.

public class Vehicle
{
    public Vehicle()
    {
        AboutYou = new AboutYou();
        TestModels = new List<TestModel>();
    }

    public AboutYou AboutYou { get; set; }

    public List<TestModel> TestModels { get; set; }
}

public class AboutYou
{
    [DisplayName("What is your title")]
    public int Title { get; set; }
}

public class TestModel
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

And Dto.

public class TestModel
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

public class VehicleDto
{
    public VehicleDto()
    {
        TestDtos = new List<TestDto>();
    }

    public int AboutYouTitle { get; set; }

    public List<TestDto> TestDtos { get; set; }
}

public class TestDto
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

And this is my profile.

public class VehicleMapping : Profile
{
    public VehicleMapping()
    {
        CreateMap<Vehicle, VehicleDto>().ReverseMap();
        CreateMap<TestModel, TestDto>().ReverseMap();

    }
}

The problem I'm having is that I need to have the reversemap in place so it flattens and unflattens the AboutYou class. However, the TestModels collection is not being mapped to the TestDtos collection. I can apply a AfterMap but then I have to manually unflatten the AboutYou object. Any ideas how I can set it up so that the AboutYou is flattened and unflattened and the collections are mapped as well?


问:
Replace() with Split()
I need to enter a "0" in case there's only one digit after the comma, how does replace() work in this situation?

var a = "2x 250,5";

console.log(a.replace(a.split(",")[1], a.split(",")[1] + 0));

//expected result
// 2x 250,50

//Output
//2x 2500,5```

答:
try

```<code>a.replace(/,\d$/, x => x+'0');
</code>```

var tests = [
  '2x 250,0',
  '2x 200,03',
  '2x 511,0',
  '2x 413,3'
]
function addZero(str){
  return str.replace(/,\d$/, x => x+'0');
}
tests.forEach(str => console.log(addZero(str)));```

Title: Replace() with Split()

Body:
try

a.replace(/,\d$/, x => x+'0');

var tests = [
  '2x 250,0',
  '2x 200,03',
  '2x 511,0',
  '2x 413,3'
]
function addZero(str){
  return str.replace(/,\d$/, x => x+'0');
}
tests.forEach(str => console.log(addZero(str)));


问:
How to generate nuget package with specific file organization using cpack/cmake?
I generate two nuget package with cpack and cmake. My problem is to organize files in my package. I would like to put some files in specific folder.

Actually i have in my first package:

```<code>/_rels
/package
toto.nuspec
toto.dll
</code>```

But i want to have toto.dll in /lib folder :

```<code>/_rels
/package
/lib/toto.dll
toto.nuspec
</code>```

I tried to use:

```<code>set(CPACK_PACKAGING_INSTALL_PREFIX "/lib")
</code>```

but i want different file organization for other packages.

Do you have an idea to do this for one specific package ?

答:
Set the desired destination in the install(TARGET...) command instead. E.g.,

```<code>install(
    TARGET toto DESTINATION lib
    # Some other args may follow here, like `COMPONENT`...
  )
</code>```

Body:
I generate two nuget package with cpack and cmake. My problem is to organize files in my package. I would like to put some files in specific folder.

Actually i have in my first package:

/_rels
/package
toto.nuspec
toto.dll

But i want to have toto.dll in /lib folder :

/_rels
/package
/lib/toto.dll
toto.nuspec

I tried to use:

set(CPACK_PACKAGING_INSTALL_PREFIX "/lib")

but i want different file organization for other packages.

Do you have an idea to do this for one specific package ?

Body:
Set the desired destination in the install(TARGET...) command instead. E.g.,

install(
    TARGET toto DESTINATION lib
    # Some other args may follow here, like `COMPONENT`...
  )


问:
Can a CSS overflow scrollbar be controlled in Javascript?
I have a div with a class overflow: auto;  Is there a way to control this scrollbar when it appears?

I have a ajax photo gallery (no page refresh) where some caption text is in a div, but the content is of varying length.  If you scroll down in this div and then advance to the next slide, the scrollbar does not go back to the top.  So, I was wondering if there was a way to control this scrollbar.  Thanks.

答:
You can change the value of the property scrollTop of the
 element.

See element.scrollTop on MDC docs

See element.scrollTop on MSDN

While scrollTop is not part of any standard, it is supported by all major browsers.

ContentLicense: CC BY-SA 3.0

Body:
You can change the value of the property scrollTop of the <div> element.

See element.scrollTop on MDC docs

See element.scrollTop on MSDN

While scrollTop is not part of any standard, it is supported by all major browsers.


问:
How to add variable in Django model
I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint.

this is what i found in the web, but the problem is the variable is not rerun to user

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)
   full_name = ''
```

How to rerun the full_name to user when he call the api ?

答:
If this is using Django Rest Framework, I don't know how your code is set up, but you'll need to extend your serializer:

add a new field to the serializer: full_name = serializers.SerializerMethodField()

add a method to the serializer:

```<code>def get_full_name(self, obj):
    return "{} {}".format(obj.first_name, obj.last_name)
</code>```

NOTE:
there are LOTS of different ways of joining those strings together, using @property in your model, fstrings, etc - up to you to choose the most appropriate for your needs (without seeing the rest of your code()

Title: How to add variable in Django model

Body:
I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint.

this is what i found in the web, but the problem is the variable is not rerun to user

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)
   full_name = ''

How to rerun the full_name to user when he call the api ?

Body:
If this is using Django Rest Framework, I don't know how your code is set up, but you'll need to extend your serializer:

add a new field to the serializer: full_name = serializers.SerializerMethodField()

add a method to the serializer:

def get_full_name(self, obj):
    return "{} {}".format(obj.first_name, obj.last_name)

NOTE:
there are LOTS of different ways of joining those strings together, using @property in your model, fstrings, etc - up to you to choose the most appropriate for your needs (without seeing the rest of your code()


问:
Connecting Strapi to NextJS/Apollo Client GraphQL -- Variable "$input" of required type 'XXX' was not provided
Forgive me, this is very basic, but I haven't worked with GraphQL in a year or so and I'm missing the obvious.  I'm trying to connect a Strapi backend to a NextJS/Apollo Client front-end using GraphQL and the basic syntax is eluding me.  (This is a 'proof of concept' for a project we're working on, just to see if we can use Strapi, NextJS, and a rich text editor for our use-case)

Strapi has provided me with the createPost endpoint

To which, as far as I can tell, I need to send an object with a field data which contains my text.  I'm using TinyMCE's editor to edit the text and using apollo hooks to get the mutation

```<code>const TheEditor = () => {
    const [addPost, {data}] = useMutation(ADD_POST);
    const [theText, setText] = useState('')

    const handleEditorChange = (content, editor) => {
        console.log('Content was updated:', content);
        setText(content)
    }

    return <>
        <Editor apiKey='4564654765476547654'
                initialValue="<p>This is the initial content of the editor</p>"
                init={{
                    height: 500,
                    menubar: false,
                    plugins: [
                        'advlist autolink lists link image charmap print preview anchor',
                        'searchreplace visualblocks code fullscreen',
                        'insertdatetimse media table paste code help wordcount'
                    ],
                    toolbar:
                        'undo redo | formatselect | bold italic backcolor | \
                        alignleft aligncenter alignright alignjustify | \
                        bullist numlist outdent indent | removeformat | help'
                }}
                onEditorChange={handleEditorChange}
        />
        <button onClick={async e => {
            e.preventDefault();
            await addPost({variables: {data:theText}});
        }}>ENTER
        </button>

    </>
}

export default withApollo(TheEditor);
</code>```

My mutation is

```<code>const ADD_POST = gql`
      mutation ADD_POST($input: createPostInput!) {
        createPost(input: $input) {
          post {
          text
          }
        }
      }
`;
</code>```

But I get the error

Clearly the issue is I need to go back and learn the basics of GraphQL syntax again.  In the meantime I'm hoping someone can point out the (egregious) errors of my ways.  I have been following along with the Apollo tutorial here, but I can't seem to make the leap from their code to mine.  Any help much appreciated.

答:
you variable name is input not data</p>

```<code><button onClick={async e => {
                e.preventDefault();
                await addPost({variables: { input:theText }});
            }}>ENTER
</button>
</code>```

Body:
Forgive me, this is very basic, but I haven't worked with GraphQL in a year or so and I'm missing the obvious.  I'm trying to connect a Strapi backend to a NextJS/Apollo Client front-end using GraphQL and the basic syntax is eluding me.  (This is a 'proof of concept' for a project we're working on, just to see if we can use Strapi, NextJS, and a rich text editor for our use-case)

Strapi has provided me with the createPost endpoint

To which, as far as I can tell, I need to send an object with a field data which contains my text.  I'm using TinyMCE's editor to edit the text and using apollo hooks to get the mutation

const TheEditor = () => {
    const [addPost, {data}] = useMutation(ADD_POST);
    const [theText, setText] = useState('')

    const handleEditorChange = (content, editor) => {
        console.log('Content was updated:', content);
        setText(content)
    }

    return <>
        <Editor apiKey='4564654765476547654'
                initialValue="
This is the initial content of the editor
"
                init={{
                    height: 500,
                    menubar: false,
                    plugins: [
                        'advlist autolink lists link image charmap print preview anchor',
                        'searchreplace visualblocks code fullscreen',
                        'insertdatetimse media table paste code help wordcount'
                    ],
                    toolbar:
                        'undo redo | formatselect | bold italic backcolor | \
                        alignleft aligncenter alignright alignjustify | \
                        bullist numlist outdent indent | removeformat | help'
                }}
                onEditorChange={handleEditorChange}
        />
        <button onClick={async e => {
            e.preventDefault();
            await addPost({variables: {data:theText}});
        }}>ENTER
        </button>

    </>
}

export default withApollo(TheEditor);

My mutation is

const ADD_POST = gql`
      mutation ADD_POST($input: createPostInput!) {
        createPost(input: $input) {
          post {
          text
          }
        }
      }
`;

But I get the error

Clearly the issue is I need to go back and learn the basics of GraphQL syntax again.  In the meantime I'm hoping someone can point out the (egregious) errors of my ways.  I have been following along with the Apollo tutorial here, but I can't seem to make the leap from their code to mine.  Any help much appreciated.

Body:
you variable name is input not data

<button onClick={async e => {
                e.preventDefault();
                await addPost({variables: { input:theText }});
            }}>ENTER
</button>


问:
Set python interpreter for project in VSCode
Chances are high that this question already exists, but I could find any useful answers until now:/ The issue is that I have created a new github repository for a new small python project. I would like to work in VS-Code and create an environment with miniconda. All this is no problem. But is there any way to make sure, that always when I open VSCode it automatically switches to this interpreter?</p>

答:
Under .vscode folder, create a file named settings.json and add this:

```<code>{
    "python.pythonPath": "env/bin/python3.7"
}
</code>```

Body:
Under .vscode folder, create a file named settings.json and add this:

{
    "python.pythonPath": "env/bin/python3.7"
}


问:
Returning multiple case statements on one row in T-SQL
I'm using the following T-SQL statement to return some values:

```<code>CASE WHEN month(m.pcp_startdate) = 1 THEN m.pcp_value ELSE NULL END AS January,
CASE WHEN month(m.pcp_startdate) = 2 THEN m.pcp_value ELSE NULL END AS Febuary,
CASE WHEN month(m.pcp_startdate) = 3 THEN m.pcp_value ELSE NULL END AS March,
CASE WHEN month(m.pcp_startdate) = 4 THEN m.pcp_value ELSE NULL END AS April,
CASE WHEN month(m.pcp_startdate) = 5 THEN m.pcp_value ELSE NULL END AS May,
CASE WHEN month(m.pcp_startdate) = 6 THEN m.pcp_valuen ELSE NULL END AS June,
CASE WHEN month(m.pcp_startdate) = 7 THEN m.pcp_value ELSE NULL END AS July,
CASE WHEN month(m.pcp_startdate) = 8 THEN m.pcp_value ELSE NULL END AS August,
CASE WHEN month(m.pcp_startdate) = 9 THEN m.pcp_value ELSE NULL END AS September,
CASE WHEN month(m.pcp_startdate) = 10 THEN m.pcp_value ELSE NULL END AS October,
CASE WHEN month(m.pcp_startdate) = 11 THEN m.pcp_value ELSE NULL END AS November,
CASE WHEN month(m.pcp_startdate) = 12 THEN m.pcp_value ELSE NULL END AS December
</code>```

However this is returning all of these values on different rows

```<code>NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
</code>```

Is there any way to make them appear on the same row? Thanks!

答:
Looks like you want aggregation:

```<code>MAX(CASE WHEN month(m.pcp_startdate) = 1 THEN m.pcp_value END) AS January,
MAX(CASE WHEN month(m.pcp_startdate) = 2 THEN m.pcp_value END) AS February,
</code>```

You may have to adjust the GROUP BY in your query as well, but you don't show that in your question.

Body:
I'm using the following T-SQL statement to return some values:

CASE WHEN month(m.pcp_startdate) = 1 THEN m.pcp_value ELSE NULL END AS January,
CASE WHEN month(m.pcp_startdate) = 2 THEN m.pcp_value ELSE NULL END AS Febuary,
CASE WHEN month(m.pcp_startdate) = 3 THEN m.pcp_value ELSE NULL END AS March,
CASE WHEN month(m.pcp_startdate) = 4 THEN m.pcp_value ELSE NULL END AS April,
CASE WHEN month(m.pcp_startdate) = 5 THEN m.pcp_value ELSE NULL END AS May,
CASE WHEN month(m.pcp_startdate) = 6 THEN m.pcp_valuen ELSE NULL END AS June,
CASE WHEN month(m.pcp_startdate) = 7 THEN m.pcp_value ELSE NULL END AS July,
CASE WHEN month(m.pcp_startdate) = 8 THEN m.pcp_value ELSE NULL END AS August,
CASE WHEN month(m.pcp_startdate) = 9 THEN m.pcp_value ELSE NULL END AS September,
CASE WHEN month(m.pcp_startdate) = 10 THEN m.pcp_value ELSE NULL END AS October,
CASE WHEN month(m.pcp_startdate) = 11 THEN m.pcp_value ELSE NULL END AS November,
CASE WHEN month(m.pcp_startdate) = 12 THEN m.pcp_value ELSE NULL END AS December

However this is returning all of these values on different rows

NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

Is there any way to make them appear on the same row? Thanks!

Body:
Looks like you want aggregation:

MAX(CASE WHEN month(m.pcp_startdate) = 1 THEN m.pcp_value END) AS January,
MAX(CASE WHEN month(m.pcp_startdate) = 2 THEN m.pcp_value END) AS February,

You may have to adjust the GROUP BY in your query as well, but you don't show that in your question.


问:
RecyleView showing all items duplicates
I am trying to display posts from a server in listView. So I used recycle-view to achieve that. Everything is working fine except that ll items are displaying twice.

I counted the total fetched items from server, and the count is 5, but adapter.getItemCount is showing 10.

After searching hours on the internet, I tried following :

```<code>@Override
public long getItemId(int position) {
    return position;
}
@Override
public int getItemViewType(int position) {
    return position;
}
</code>```

and

homeFragmentAdapter.setHasStableIds(true);

Below is my fragment...

```<code>package com.example.projectName;

import static android.content.Context.MODE_PRIVATE;
import static android.webkit.ConsoleMessage.MessageLevel.LOG;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class HomeFollowersFragment extends Fragment implements InfiniteScrollListener.OnLoadMoreListener, RecyclerViewItemListener {

    private static final String TAG = "HomeFollowersFragment";
    private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
    private RecyclerView recyclerView;
    private ProgressBar postLoader;
    FFmpeg ffmpeg;
//    private List<Movie> movieList;
//    private HomeAdapter mAdapter;

    private List<PostList> postListGlobal = new ArrayList<>();
    List<VerticalDataModal> verticalDataModals;
    List<HorizontalDataModal> horizontalDataModals;
    private SwipeRefreshLayout swipeMore;
    private InfiniteScrollListener infiniteScrollListener;
    private HomeFragmentAdapter homeFragmentAdapter;

    SharedPreferences sharedPreferences;
    private Boolean isLoggedIn = false;
    private String email = "";
    private String token = "";
    private String userId = "";

    private Dialog customLoader;
    SkeletonScreen skeletonScreen;

    private int pastVisiblesItems, visibleItemCount, totalItemCount;
    private boolean loading = false;
    private EndlessScrollListener scrollListener;

    SharedPreferences sp;
    SharedPreferences.Editor Ed;

    public HomeFollowersFragment() {
        //super();
    }
    /**
     * @return A new instance of fragment HomeFollowersFragment.
     */
    public static HomeFollowersFragment newInstance() {
        return new HomeFollowersFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
//        ((AppCompatActivity) getActivity()).getSupportActionBar().show();

        try{
            sharedPreferences = getActivity().getSharedPreferences("Login", MODE_PRIVATE);
            email = sharedPreferences.getString("email", null);
            token = sharedPreferences.getString("token", null);
            isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
            userId = sharedPreferences.getString("id", null);
        }catch (Exception e){
            e.printStackTrace();
            Log.d("StackError", "StackError: "+e);
        }
        sp = getActivity().getSharedPreferences("Posts", MODE_PRIVATE);
        if(!isLoggedIn || token == null || userId == null){
            Intent intent = new Intent(getActivity(), RegisterActivity.class);
            intent.putExtra("loginFrom", "profile");
            startActivity(intent);
        }

        recyclerView = view.findViewById(R.id.recycler_view);
        postLoader = view.findViewById(R.id.post_loader);
        swipeMore = view.findViewById(R.id.swipe_layout);

        homeFragmentAdapter = new HomeFragmentAdapter(postListGlobal, this, "home");

        if(sp.contains("postListGlobal"))
            skeletonScreen = Skeleton.bind(recyclerView)
                    .adapter(homeFragmentAdapter)
                    .shimmer(true)
                    .angle(20)
                    .frozen(false)
                    .duration(1200)
                    .count(10)
                    .load(R.layout.item_skelton_home_page)
                    .show(); //default count is 10
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        StaggeredGridLayoutManager sLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(sLayoutManager);
        homeFragmentAdapter.setHasStableIds(true);
        recyclerView.setAdapter(homeFragmentAdapter);
        recyclerView.setNestedScrollingEnabled(false);

        customLoader = new Dialog(getActivity(), R.style.crystal_range_seek_bar);
        customLoader.setCancelable(false);
        View loaderView = getLayoutInflater().inflate(R.layout.custom_loading_layout, null);
        customLoader.getWindow().getAttributes().windowAnimations = R.style.crystal_range_seek_bar;
        customLoader.getWindow().setBackgroundDrawableResource(R.color.translucent_black);

        ImageView imageLoader = loaderView.findViewById(R.id.logo_loader);
        Glide.with(this).load(R.drawable.logo_loader).into(imageLoader);
        customLoader.setContentView(loaderView);

        if(homeFragmentAdapter.getItemCount() == 0 && !loading){
            // server fetchdata
            Log.d(TAG, "no item available..");
            postLoader.setVisibility(View.VISIBLE);
            loading = true;
            fetchStoreItems();
        }else{
            postLoader.setVisibility(View.GONE);
        }
        swipeMore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d(TAG, "on refresh...");
                fetchStoreItems();
            }
        });
        return view;
    }
    @Override
    public void onItemClicked(int position) {
        Log.d(TAG, "click position: "+position);
        Toast.makeText(getActivity(),postListGlobal.get(position).getTitle(),Toast.LENGTH_SHORT).show();
//        Toast.makeText(getActivity(),""+position, Toast.LENGTH_SHORT).show();

    }
    public int getLastVisibleItem(int[] lastVisibleItemPositions) {
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) {
            if (i == 0) {
                maxSize = lastVisibleItemPositions[i];
            }
            else if (lastVisibleItemPositions[i] > maxSize) {
                maxSize = lastVisibleItemPositions[i];
            }
        }
        return maxSize;
    }
    @Override
    public void onLoadMore() {
        homeFragmentAdapter.addNullData();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                homeFragmentAdapter.removeNull();
                Toast.makeText(getContext(), "load more here...", Toast.LENGTH_LONG).show();
//                fetchStoreItems();
                swipeMore.setRefreshing(false);
            }
        }, 2000);
    }
    private void fetchStoreItems() {
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        Log.d(TAG, "Post Data Followers: "+Constant.FETCH_POSTS_API);
        CacheRequest cacheRequest = new CacheRequest(0, Constant.FETCH_POSTS_API, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {
                try {
                    final String jsonString = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers));
                    if (response == null) {
                        Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
                        loading = false;
                        return;
                    }
                    JSONObject postObj = new JSONObject(jsonString);
                    System.out.println("post full data... : " + postObj);
                    if (postObj.getBoolean("Status")) {
                        try {
                            postLoader.setVisibility(View.GONE);
                            JSONArray arrayResponse = postObj.optJSONArray("Data");
                            int dataArrLength = arrayResponse.length();
                            if(dataArrLength == 0){
                                Toast.makeText(getActivity(), "No posts available at this time, you can create yout own post by clicking on mic button", Toast.LENGTH_SHORT).show();
                            }
                            postListGlobal.clear();
                            Log.d(TAG, "Total Posts count: "+dataArrLength);
                            for(int i=0; i<dataArrLength; i++) {
                                try {
                                    JSONObject dataListObj = arrayResponse.optJSONObject(i);
                                    System.out.println("post full data... : " + dataListObj);

                                    JSONObject postDetailObj = dataListObj.optJSONObject("post_detail");
                                    JSONObject followDtatusObj = dataListObj.optJSONObject("follow_status");
                                    JSONArray postFilesArr = dataListObj.optJSONArray("post_files");
                                    JSONObject userDatasObj = postDetailObj.optJSONObject("user");

                                    String userId = userDatasObj.optString("id");
                                    String userName = userDatasObj.optString("email");
                                    String userImage = userDatasObj.optString("email");

                                    boolean followStatus = followDtatusObj.optBoolean("follow");

                                    String postId = postDetailObj.optString("id");
                                    String postTitle = postDetailObj.optString("post_title");
                                    String postDescription = postDetailObj.optString("post_description");
                                    String postCoverUrl = postDetailObj.optString("post_coverurl", "1");
                                    String postViewType = postDetailObj.optString("view_type", "1");
                                    String postAllowComment = postDetailObj.optString("allow_comments", "1");
                                    String postAllowDownload = postDetailObj.optString("allow_download", "1");
                                    String postTotalPost = postDetailObj.optString("total_post", "1");
                                    String postPostSection = postDetailObj.optString("post_section", "image");
                                    String postActiveStatus = postDetailObj.optString("is_active", "1");

                                    String postTotalViews = postDetailObj.optString("total_watched","0");
                                    String postTotalShare = postDetailObj.optString("total_share","0");
                                    String postTotalDownload = postDetailObj.optString("total_download","0");
                                    String postTotalReaction = postDetailObj.optString("total_reaction","0");

                                    String postTotalLike = postDetailObj.optString("total_like","0");
                                    String postTotalSmile = postDetailObj.optString("smile_reaction","0");
                                    String postTotalLaugh = postDetailObj.optString("laugh_reaction","0");
                                    String postTotalSad = postDetailObj.optString("sad_reaction","0");
                                    String postTotalLove = postDetailObj.optString("love_reaction","0");
                                    String postTotalShock = postDetailObj.optString("shock_reaction","0");

                                    int totalPostFiles = Integer.parseInt(postTotalPost);
                                    int postArrLength = postFilesArr.length();
                                    String postImageUrl = null;
                                    String postMusicUrl = null;

                                    String commonUrl = "http://serverName.com/";
                                    if(postArrLength >= 1){
                                        JSONObject dataFilesListObj = postFilesArr.optJSONObject(0);
//                                        System.out.println("post files full data... : " + dataFilesListObj);
                                        String postFileId = dataFilesListObj.optString("id");
                                        postImageUrl = dataFilesListObj.optString("image_file_path");
                                        postMusicUrl = dataFilesListObj.optString("music_file_path");
                                        System.out.println("post files full data... : " + dataFilesListObj);
                                    }
                                    System.out.println("post files full data... : " + commonUrl+postMusicUrl);
                                    System.out.println("post files full data... : " + commonUrl+postImageUrl);
                                    PostList postList = new PostList();
                                    postList.setId(postId);
                                    postList.setTitle(postTitle);
                                    postList.setTotalPost(""+dataArrLength);
                                    postList.setTotalView(postTotalViews);
                                    postList.setTotalReaction(postTotalReaction);
                                    postList.setMusicPath(commonUrl+postMusicUrl);

                                    postList.setImagePath(commonUrl+postImageUrl);
                                    if(postImageUrl == null){
                                        postList.setImagePath("https://amazonBucket.s3.location.amazonaws.com/images/pic1.jpg");
                                    }
                                    postList.setUserId(userId);
                                    postList.setUserName(userName);
                                    postList.setPostDataObject(arrayResponse);
                                    postListGlobal.add(postList);

                                    Log.d(TAG, "Total Posts: "+dataListObj);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.d(TAG, "Post Data Error1: "+e);
                                    Toast.makeText(getActivity(), "File now found", Toast.LENGTH_LONG).show();
                                    loading = false;
                                }

                            }

                        } catch (Exception e){
                            e.printStackTrace();
                            Log.d(TAG, "Post Data Error2: "+e);
                            Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
                            loading = false;
                        }
                    }else{
                        try {
                            Toast.makeText(getActivity(), new JSONObject(jsonString).getString("Message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException ex) {
                            ex.printStackTrace();
                            Log.d(TAG, "Post Data Error3: "+ex);
                            Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_SHORT).show();
                        }
                        loading = false;
                    }

                    // refreshing recycler view
                    homeFragmentAdapter.removeNull();
                    homeFragmentAdapter.addData(postListGlobal);
                    homeFragmentAdapter.notifyDataSetChanged();
//                    save in local memory
//                    saveArrayList(postListGlobal, "postListGlobal");

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, "Post Data Error4: "+e);
                }
                loading = true;
                homeFragmentAdapter.notifyDataSetChanged();
                swipeMore.setRefreshing(false);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "onErrorResponse: "+ error, Toast.LENGTH_SHORT).show();
                swipeMore.setRefreshing(false);
                loading = true;
                homeFragmentAdapter.notifyDataSetChanged();
                postLoader.setVisibility(View.VISIBLE);
                loading = false;
                Log.d(TAG, "Post Data Error5: "+error);
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
                String finalToken = "Bearer  "+token;
                params.put("Authorization", finalToken);
                params.put("Content-Type", "application/json");

                return params;
            }
        };
        // Add the request to the RequestQueue.
        queue.add(cacheRequest);

    }
    private class CacheRequest extends Request<NetworkResponse> {
        private final Response.Listener<NetworkResponse> mListener;
        private final Response.ErrorListener mErrorListener;

        public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
            super(method, url, errorListener);
            this.mListener = listener;
            this.mErrorListener = errorListener;
        }
        @Override
        protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
            Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
            if (cacheEntry == null) {
                cacheEntry = new Cache.Entry();
            }
            final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
            final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
            long now = System.currentTimeMillis();
            final long softExpire = now + cacheHitButRefreshed;
            final long ttl = now + cacheExpired;
            cacheEntry.data = response.data;
            cacheEntry.softTtl = softExpire;
            cacheEntry.ttl = ttl;
            String headerValue;
            headerValue = response.headers.get("Date");
            if (headerValue != null) {
                cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            headerValue = response.headers.get("Last-Modified");
            if (headerValue != null) {
                cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            cacheEntry.responseHeaders = response.headers;
            return Response.success(response, cacheEntry);
        }
        @Override
        protected void deliverResponse(NetworkResponse response) {
            mListener.onResponse(response);
        }
        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            Log.d(TAG, "Post Data volleyError: "+volleyError);
            return super.parseNetworkError(volleyError);
        }
        @Override
        public void deliverError(VolleyError error) {
            mErrorListener.onErrorResponse(error);
        }
    }
}
</code>```

and Adapter Class

```<code>package com.example.ProjectName;

public class HomeFragmentAdapter extends RecyclerView.Adapter <HomeFragmentAdapter.HomeViewHolder>{

    //    private ArrayList<Integer> dataList;
    private List<PostList> postListGlobal;
    int VIEW_TYPE_LOADING;
    int VIEW_TYPE_ITEM;
    Context context;
    private RecyclerViewItemListener callback;
    FFmpeg ffmpeg;
    String callingPage;

    public HomeFragmentAdapter(List<PostList> postListGlobal, RecyclerViewItemListener callback, String callingPage) {
        this.postListGlobal = postListGlobal;
        this.callback = callback;
        this.callingPage = callingPage;
//        setHasStableIds(true);
    }

    @NonNull
    @Override
    public HomeFragmentAdapter.HomeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = null;
        context = parent.getContext();
        root = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_tile_list, parent, false);
        return new DataViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull HomeFragmentAdapter.HomeViewHolder holder, int position) {
        if (holder instanceof DataViewHolder) {
            final PostList postList = postListGlobal.get(position);
            holder.postTitle.setText(postList.getTitle());
            holder.postWatch.setText(postList.getTotalView());
            holder.postReaction.setText(postList.getTotalReaction());

            String imageUrl = postList.getImagePath();
//            String imageUrl = Constant.SERVER_URL+"/"+postList.getImagePath();
            String musicUrl = postList.getMusicPath();
//            String musicUrl = Constant.SERVER_URL+"/"+postList.getMusicPath();
            Log.d(TAG, "Post url: "+imageUrl+" -- "+musicUrl);
//            int totalMusicTime = getDurationVal(musicUrl, "second");
            holder.postTime.setText(postList.getTotalPost());

            holder.thumbnail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callback.onItemClicked(position);
                    Log.d("homeView", "screenName : "+callingPage);
                    if(callingPage.equals("home")){
                        Log.d("homeView", "screenName : "+position);
                        Intent intent = new Intent(context, MainViewActivity.class);
                        intent.putExtra("loginFrom", "homeView");
                        intent.putExtra("postDataObj", postList.getPostDataObject().toString());
                        intent.putExtra("postPosition", ""+position);
                        intent.putExtra("tabId", "1");
                        context.startActivity(intent);
                    }
                }
            });

            Drawable mDefaultBackground = context.getResources().getDrawable(R.drawable.influencers);
            CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(context);
            circularProgressDrawable.setStrokeWidth(5f);
            Glide.with(context)
                    .load(imageUrl)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
//                            progressBar.setVisibility(View.GONE);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                            progressBar.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .error(mDefaultBackground)
                    .into(holder.thumbnail);
        }else{
            //Do whatever you want. Or nothing !!
        }
    }

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

    class DataViewHolder extends HomeViewHolder {
        public DataViewHolder(View itemView) {
            super(itemView);
        }

    }

    class ProgressViewHolder extends HomeViewHolder {
        public ProgressViewHolder(View itemView) {
            super(itemView);
        }
    }

    class HomeViewHolder extends RecyclerView.ViewHolder {
        public TextView postTitle, postTime, postWatch, postReaction;
        public ImageView thumbnail;
        public HomeViewHolder(View itemView) {
            super(itemView);
            postTitle = itemView.findViewById(R.id.post_title);
            postTime = itemView.findViewById(R.id.total_time);
            postWatch = itemView.findViewById(R.id.total_watch);
            postReaction = itemView.findViewById(R.id.total_reaction);
            thumbnail = itemView.findViewById(R.id.thumbnail);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public int getItemViewType(int position) {
        return position;
    }
    public void addNullData() {
    }
    public void removeNull() {
        notifyItemRemoved(postListGlobal.size());
    }
    public void addData(List<PostList> postLists) {
        postListGlobal.addAll(postLists);
        notifyDataSetChanged();
    }
}
</code>```

After trying everything, I was still not able to resolve the issue. Any help/suggestions are welcome. Let me know If I left out any needed code--if so I can update it here.

答: postListGlobal.clear();  just clear tha arraylist before add .</p>

Title: RecyleView showing all items duplicates

Body:
I am trying to display posts from a server in listView. So I used recycle-view to achieve that. Everything is working fine except that ll items are displaying twice.

I counted the total fetched items from server, and the count is 5, but adapter.getItemCount is showing 10.

After searching hours on the internet, I tried following :

@Override
public long getItemId(int position) {
    return position;
}
@Override
public int getItemViewType(int position) {
    return position;
}

and

homeFragmentAdapter.setHasStableIds(true);

Below is my fragment...

package com.example.projectName;

import static android.content.Context.MODE_PRIVATE;
import static android.webkit.ConsoleMessage.MessageLevel.LOG;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class HomeFollowersFragment extends Fragment implements InfiniteScrollListener.OnLoadMoreListener, RecyclerViewItemListener {

    private static final String TAG = "HomeFollowersFragment";
    private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
    private RecyclerView recyclerView;
    private ProgressBar postLoader;
    FFmpeg ffmpeg;
//    private List<Movie> movieList;
//    private HomeAdapter mAdapter;

    private List<PostList> postListGlobal = new ArrayList<>();
    List<VerticalDataModal> verticalDataModals;
    List<HorizontalDataModal> horizontalDataModals;
    private SwipeRefreshLayout swipeMore;
    private InfiniteScrollListener infiniteScrollListener;
    private HomeFragmentAdapter homeFragmentAdapter;

    SharedPreferences sharedPreferences;
    private Boolean isLoggedIn = false;
    private String email = "";
    private String token = "";
    private String userId = "";

    private Dialog customLoader;
    SkeletonScreen skeletonScreen;

    private int pastVisiblesItems, visibleItemCount, totalItemCount;
    private boolean loading = false;
    private EndlessScrollListener scrollListener;

    SharedPreferences sp;
    SharedPreferences.Editor Ed;

    public HomeFollowersFragment() {
        //super();
    }
    /**
     * @return A new instance of fragment HomeFollowersFragment.
     */
    public static HomeFollowersFragment newInstance() {
        return new HomeFollowersFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
//        ((AppCompatActivity) getActivity()).getSupportActionBar().show();

        try{
            sharedPreferences = getActivity().getSharedPreferences("Login", MODE_PRIVATE);
            email = sharedPreferences.getString("email", null);
            token = sharedPreferences.getString("token", null);
            isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
            userId = sharedPreferences.getString("id", null);
        }catch (Exception e){
            e.printStackTrace();
            Log.d("StackError", "StackError: "+e);
        }
        sp = getActivity().getSharedPreferences("Posts", MODE_PRIVATE);
        if(!isLoggedIn || token == null || userId == null){
            Intent intent = new Intent(getActivity(), RegisterActivity.class);
            intent.putExtra("loginFrom", "profile");
            startActivity(intent);
        }

        recyclerView = view.findViewById(R.id.recycler_view);
        postLoader = view.findViewById(R.id.post_loader);
        swipeMore = view.findViewById(R.id.swipe_layout);

        homeFragmentAdapter = new HomeFragmentAdapter(postListGlobal, this, "home");

        if(sp.contains("postListGlobal"))
            skeletonScreen = Skeleton.bind(recyclerView)
                    .adapter(homeFragmentAdapter)
                    .shimmer(true)
                    .angle(20)
                    .frozen(false)
                    .duration(1200)
                    .count(10)
                    .load(R.layout.item_skelton_home_page)
                    .show(); //default count is 10
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        StaggeredGridLayoutManager sLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(sLayoutManager);
        homeFragmentAdapter.setHasStableIds(true);
        recyclerView.setAdapter(homeFragmentAdapter);
        recyclerView.setNestedScrollingEnabled(false);

        customLoader = new Dialog(getActivity(), R.style.crystal_range_seek_bar);
        customLoader.setCancelable(false);
        View loaderView = getLayoutInflater().inflate(R.layout.custom_loading_layout, null);
        customLoader.getWindow().getAttributes().windowAnimations = R.style.crystal_range_seek_bar;
        customLoader.getWindow().setBackgroundDrawableResource(R.color.translucent_black);

        ImageView imageLoader = loaderView.findViewById(R.id.logo_loader);
        Glide.with(this).load(R.drawable.logo_loader).into(imageLoader);
        customLoader.setContentView(loaderView);

        if(homeFragmentAdapter.getItemCount() == 0 && !loading){
            // server fetchdata
            Log.d(TAG, "no item available..");
            postLoader.setVisibility(View.VISIBLE);
            loading = true;
            fetchStoreItems();
        }else{
            postLoader.setVisibility(View.GONE);
        }
        swipeMore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d(TAG, "on refresh...");
                fetchStoreItems();
            }
        });
        return view;
    }
    @Override
    public void onItemClicked(int position) {
        Log.d(TAG, "click position: "+position);
        Toast.makeText(getActivity(),postListGlobal.get(position).getTitle(),Toast.LENGTH_SHORT).show();
//        Toast.makeText(getActivity(),""+position, Toast.LENGTH_SHORT).show();

    }
    public int getLastVisibleItem(int[] lastVisibleItemPositions) {
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) {
            if (i == 0) {
                maxSize = lastVisibleItemPositions[i];
            }
            else if (lastVisibleItemPositions[i] > maxSize) {
                maxSize = lastVisibleItemPositions[i];
            }
        }
        return maxSize;
    }
    @Override
    public void onLoadMore() {
        homeFragmentAdapter.addNullData();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                homeFragmentAdapter.removeNull();
                Toast.makeText(getContext(), "load more here...", Toast.LENGTH_LONG).show();
//                fetchStoreItems();
                swipeMore.setRefreshing(false);
            }
        }, 2000);
    }
    private void fetchStoreItems() {
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        Log.d(TAG, "Post Data Followers: "+Constant.FETCH_POSTS_API);
        CacheRequest cacheRequest = new CacheRequest(0, Constant.FETCH_POSTS_API, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {
                try {
                    final String jsonString = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers));
                    if (response == null) {
                        Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
                        loading = false;
                        return;
                    }
                    JSONObject postObj = new JSONObject(jsonString);
                    System.out.println("post full data... : " + postObj);
                    if (postObj.getBoolean("Status")) {
                        try {
                            postLoader.setVisibility(View.GONE);
                            JSONArray arrayResponse = postObj.optJSONArray("Data");
                            int dataArrLength = arrayResponse.length();
                            if(dataArrLength == 0){
                                Toast.makeText(getActivity(), "No posts available at this time, you can create yout own post by clicking on mic button", Toast.LENGTH_SHORT).show();
                            }
                            postListGlobal.clear();
                            Log.d(TAG, "Total Posts count: "+dataArrLength);
                            for(int i=0; i<dataArrLength; i++) {
                                try {
                                    JSONObject dataListObj = arrayResponse.optJSONObject(i);
                                    System.out.println("post full data... : " + dataListObj);

                                    JSONObject postDetailObj = dataListObj.optJSONObject("post_detail");
                                    JSONObject followDtatusObj = dataListObj.optJSONObject("follow_status");
                                    JSONArray postFilesArr = dataListObj.optJSONArray("post_files");
                                    JSONObject userDatasObj = postDetailObj.optJSONObject("user");

                                    String userId = userDatasObj.optString("id");
                                    String userName = userDatasObj.optString("email");
                                    String userImage = userDatasObj.optString("email");

                                    boolean followStatus = followDtatusObj.optBoolean("follow");

                                    String postId = postDetailObj.optString("id");
                                    String postTitle = postDetailObj.optString("post_title");
                                    String postDescription = postDetailObj.optString("post_description");
                                    String postCoverUrl = postDetailObj.optString("post_coverurl", "1");
                                    String postViewType = postDetailObj.optString("view_type", "1");
                                    String postAllowComment = postDetailObj.optString("allow_comments", "1");
                                    String postAllowDownload = postDetailObj.optString("allow_download", "1");
                                    String postTotalPost = postDetailObj.optString("total_post", "1");
                                    String postPostSection = postDetailObj.optString("post_section", "image");
                                    String postActiveStatus = postDetailObj.optString("is_active", "1");

                                    String postTotalViews = postDetailObj.optString("total_watched","0");
                                    String postTotalShare = postDetailObj.optString("total_share","0");
                                    String postTotalDownload = postDetailObj.optString("total_download","0");
                                    String postTotalReaction = postDetailObj.optString("total_reaction","0");

                                    String postTotalLike = postDetailObj.optString("total_like","0");
                                    String postTotalSmile = postDetailObj.optString("smile_reaction","0");
                                    String postTotalLaugh = postDetailObj.optString("laugh_reaction","0");
                                    String postTotalSad = postDetailObj.optString("sad_reaction","0");
                                    String postTotalLove = postDetailObj.optString("love_reaction","0");
                                    String postTotalShock = postDetailObj.optString("shock_reaction","0");

                                    int totalPostFiles = Integer.parseInt(postTotalPost);
                                    int postArrLength = postFilesArr.length();
                                    String postImageUrl = null;
                                    String postMusicUrl = null;

                                    String commonUrl = "http://serverName.com/";
                                    if(postArrLength >= 1){
                                        JSONObject dataFilesListObj = postFilesArr.optJSONObject(0);
//                                        System.out.println("post files full data... : " + dataFilesListObj);
                                        String postFileId = dataFilesListObj.optString("id");
                                        postImageUrl = dataFilesListObj.optString("image_file_path");
                                        postMusicUrl = dataFilesListObj.optString("music_file_path");
                                        System.out.println("post files full data... : " + dataFilesListObj);
                                    }
                                    System.out.println("post files full data... : " + commonUrl+postMusicUrl);
                                    System.out.println("post files full data... : " + commonUrl+postImageUrl);
                                    PostList postList = new PostList();
                                    postList.setId(postId);
                                    postList.setTitle(postTitle);
                                    postList.setTotalPost(""+dataArrLength);
                                    postList.setTotalView(postTotalViews);
                                    postList.setTotalReaction(postTotalReaction);
                                    postList.setMusicPath(commonUrl+postMusicUrl);

                                    postList.setImagePath(commonUrl+postImageUrl);
                                    if(postImageUrl == null){
                                        postList.setImagePath("https://amazonBucket.s3.location.amazonaws.com/images/pic1.jpg");
                                    }
                                    postList.setUserId(userId);
                                    postList.setUserName(userName);
                                    postList.setPostDataObject(arrayResponse);
                                    postListGlobal.add(postList);

                                    Log.d(TAG, "Total Posts: "+dataListObj);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.d(TAG, "Post Data Error1: "+e);
                                    Toast.makeText(getActivity(), "File now found", Toast.LENGTH_LONG).show();
                                    loading = false;
                                }

                            }

                        } catch (Exception e){
                            e.printStackTrace();
                            Log.d(TAG, "Post Data Error2: "+e);
                            Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
                            loading = false;
                        }
                    }else{
                        try {
                            Toast.makeText(getActivity(), new JSONObject(jsonString).getString("Message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException ex) {
                            ex.printStackTrace();
                            Log.d(TAG, "Post Data Error3: "+ex);
                            Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_SHORT).show();
                        }
                        loading = false;
                    }

                    // refreshing recycler view
                    homeFragmentAdapter.removeNull();
                    homeFragmentAdapter.addData(postListGlobal);
                    homeFragmentAdapter.notifyDataSetChanged();
//                    save in local memory
//                    saveArrayList(postListGlobal, "postListGlobal");

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, "Post Data Error4: "+e);
                }
                loading = true;
                homeFragmentAdapter.notifyDataSetChanged();
                swipeMore.setRefreshing(false);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "onErrorResponse: "+ error, Toast.LENGTH_SHORT).show();
                swipeMore.setRefreshing(false);
                loading = true;
                homeFragmentAdapter.notifyDataSetChanged();
                postLoader.setVisibility(View.VISIBLE);
                loading = false;
                Log.d(TAG, "Post Data Error5: "+error);
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
                String finalToken = "Bearer  "+token;
                params.put("Authorization", finalToken);
                params.put("Content-Type", "application/json");

                return params;
            }
        };
        // Add the request to the RequestQueue.
        queue.add(cacheRequest);

    }
    private class CacheRequest extends Request<NetworkResponse> {
        private final Response.Listener<NetworkResponse> mListener;
        private final Response.ErrorListener mErrorListener;

        public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
            super(method, url, errorListener);
            this.mListener = listener;
            this.mErrorListener = errorListener;
        }
        @Override
        protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
            Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
            if (cacheEntry == null) {
                cacheEntry = new Cache.Entry();
            }
            final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
            final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
            long now = System.currentTimeMillis();
            final long softExpire = now + cacheHitButRefreshed;
            final long ttl = now + cacheExpired;
            cacheEntry.data = response.data;
            cacheEntry.softTtl = softExpire;
            cacheEntry.ttl = ttl;
            String headerValue;
            headerValue = response.headers.get("Date");
            if (headerValue != null) {
                cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            headerValue = response.headers.get("Last-Modified");
            if (headerValue != null) {
                cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            cacheEntry.responseHeaders = response.headers;
            return Response.success(response, cacheEntry);
        }
        @Override
        protected void deliverResponse(NetworkResponse response) {
            mListener.onResponse(response);
        }
        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            Log.d(TAG, "Post Data volleyError: "+volleyError);
            return super.parseNetworkError(volleyError);
        }
        @Override
        public void deliverError(VolleyError error) {
            mErrorListener.onErrorResponse(error);
        }
    }
}

and Adapter Class

package com.example.ProjectName;

public class HomeFragmentAdapter extends RecyclerView.Adapter <HomeFragmentAdapter.HomeViewHolder>{

    //    private ArrayList<Integer> dataList;
    private List<PostList> postListGlobal;
    int VIEW_TYPE_LOADING;
    int VIEW_TYPE_ITEM;
    Context context;
    private RecyclerViewItemListener callback;
    FFmpeg ffmpeg;
    String callingPage;

    public HomeFragmentAdapter(List<PostList> postListGlobal, RecyclerViewItemListener callback, String callingPage) {
        this.postListGlobal = postListGlobal;
        this.callback = callback;
        this.callingPage = callingPage;
//        setHasStableIds(true);
    }

    @NonNull
    @Override
    public HomeFragmentAdapter.HomeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = null;
        context = parent.getContext();
        root = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_tile_list, parent, false);
        return new DataViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull HomeFragmentAdapter.HomeViewHolder holder, int position) {
        if (holder instanceof DataViewHolder) {
            final PostList postList = postListGlobal.get(position);
            holder.postTitle.setText(postList.getTitle());
            holder.postWatch.setText(postList.getTotalView());
            holder.postReaction.setText(postList.getTotalReaction());

            String imageUrl = postList.getImagePath();
//            String imageUrl = Constant.SERVER_URL+"/"+postList.getImagePath();
            String musicUrl = postList.getMusicPath();
//            String musicUrl = Constant.SERVER_URL+"/"+postList.getMusicPath();
            Log.d(TAG, "Post url: "+imageUrl+" -- "+musicUrl);
//            int totalMusicTime = getDurationVal(musicUrl, "second");
            holder.postTime.setText(postList.getTotalPost());

            holder.thumbnail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callback.onItemClicked(position);
                    Log.d("homeView", "screenName : "+callingPage);
                    if(callingPage.equals("home")){
                        Log.d("homeView", "screenName : "+position);
                        Intent intent = new Intent(context, MainViewActivity.class);
                        intent.putExtra("loginFrom", "homeView");
                        intent.putExtra("postDataObj", postList.getPostDataObject().toString());
                        intent.putExtra("postPosition", ""+position);
                        intent.putExtra("tabId", "1");
                        context.startActivity(intent);
                    }
                }
            });

            Drawable mDefaultBackground = context.getResources().getDrawable(R.drawable.influencers);
            CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(context);
            circularProgressDrawable.setStrokeWidth(5f);
            Glide.with(context)
                    .load(imageUrl)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
//                            progressBar.setVisibility(View.GONE);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                            progressBar.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .error(mDefaultBackground)
                    .into(holder.thumbnail);
        }else{
            //Do whatever you want. Or nothing !!
        }
    }

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

    class DataViewHolder extends HomeViewHolder {
        public DataViewHolder(View itemView) {
            super(itemView);
        }

    }

    class ProgressViewHolder extends HomeViewHolder {
        public ProgressViewHolder(View itemView) {
            super(itemView);
        }
    }

    class HomeViewHolder extends RecyclerView.ViewHolder {
        public TextView postTitle, postTime, postWatch, postReaction;
        public ImageView thumbnail;
        public HomeViewHolder(View itemView) {
            super(itemView);
            postTitle = itemView.findViewById(R.id.post_title);
            postTime = itemView.findViewById(R.id.total_time);
            postWatch = itemView.findViewById(R.id.total_watch);
            postReaction = itemView.findViewById(R.id.total_reaction);
            thumbnail = itemView.findViewById(R.id.thumbnail);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public int getItemViewType(int position) {
        return position;
    }
    public void addNullData() {
    }
    public void removeNull() {
        notifyItemRemoved(postListGlobal.size());
    }
    public void addData(List<PostList> postLists) {
        postListGlobal.addAll(postLists);
        notifyDataSetChanged();
    }
}

After trying everything, I was still not able to resolve the issue. Any help/suggestions are welcome. Let me know If I left out any needed code--if so I can update it here.


问:
Getting correct absolute path in library used by web project
I have an asp.net mvc project that uses some search methods in a seperate library.
This library needs to know the location of my lucene index files.

```<code>    private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];

    public static ColorList SearchColors(Query query) {
        return new ColorList(
            new IndexSearcher(Path.GetFullPath(lucenePath)),
            query);
    }
</code>```

This correctly reads my configured lucenePath from the web.config's application key node.
But how can I get the correct full path from this relative path? Path.GetFullPath gives me a completely incorrect path.

--Conclusion--

If you want to go full-out, tvanfosson's answer is probably for you.

I, however, kept it a little more brain dead by using the following:

```<code>Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
    ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));
</code>```

This will look in the caller's app.config for an appkey called "path" and combine its value to the caller's path. The TrimStart() makes sure that the config file can both contain a leading \ or not.

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5

Body:
I have an asp.net mvc project that uses some search methods in a seperate library.
This library needs to know the location of my lucene index files.

    private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];

    public static ColorList SearchColors(Query query) {
        return new ColorList(
            new IndexSearcher(Path.GetFullPath(lucenePath)),
            query);
    }

This correctly reads my configured lucenePath from the web.config's application key node.
But how can I get the correct full path from this relative path? Path.GetFullPath gives me a completely incorrect path.

--Conclusion--

If you want to go full-out, tvanfosson's answer is probably for you.

I, however, kept it a little more brain dead by using the following:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
    ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));

This will look in the caller's app.config for an appkey called "path" and combine its value to the caller's path. The TrimStart() makes sure that the config file can both contain a leading \ or not.

LastEditorDisplayName: boris callens

Body: Server.MapPath(string);

OwnerDisplayName: abatishchev