问:
How do i write unit test for function with void return type
I am new to writing Unit tests. I saw few examples of jUnit , but they all were for functions returning a value. </p>

<p>I have to write unit test for following method. Also we are using objects and methods in this method not belonging to this class like ConfigParser and ParseConfig. How do i go about writing Unit tests for such menthods? </p>

```<code>    @RequestMapping(value = "/generate-json" , consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@PageType(pageType = "PlaceHolderPageType")
public void execute(@RequestBody String payload) throws JSONException {
    JSONObject json = new JSONObject(payload);
    JSONObject configJSON = generateJSONSchema(json.toString());
    String capabilityName = (String) configJSON.get(JSONConfigurationConstants.CAPABILITY_NAME);
    String fileLocation = FormInputFieldConstants.JSON_PATH + capabilityName + JSONConfigurationConstants.FILE_EXTENSION;
    //Write JSON file
    try (OutputStreamWriter file  = new OutputStreamWriter(new FileOutputStream(fileLocation), StandardCharsets.UTF_8)) {
        file.write(configJSON.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    URI uriSchemaLocation = new File(fileLocation).toURI();
    ConfigParser configParser = new ConfigParser(uriSchemaLocation);
    configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation));
}
</code>```

答:
This is the method that you intend to test, correct? I am surprised to see that it contains test code (configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation));)...

What exactly do you want to test?

You could for example verify the content of the file that gets written by loading that file. However, that accounts only for a part of the method logic.

I don't see any @Override annotation and therefore assume that you are not overriding a method. You could change the method signature to return the parsed config and check it with assertions.

There might be other ways to retrieve the configuration; this depends on the logic of configParser.parseConfig(...).

You could also consider extracting the last tree lines to another method and test that method.

To sum up, you can either change the method to return a result, or extract chunks to own methods and test these, or retrieve the result from another source (in case something like configParser.getParsedConfig() exists).

Body:
I am new to writing Unit tests. I saw few examples of jUnit , but they all were for functions returning a value.

I have to write unit test for following method. Also we are using objects and methods in this method not belonging to this class like ConfigParser and ParseConfig. How do i go about writing Unit tests for such menthods?

    @RequestMapping(value = "/generate-json" , consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@PageType(pageType = "PlaceHolderPageType")
public void execute(@RequestBody String payload) throws JSONException {
    JSONObject json = new JSONObject(payload);
    JSONObject configJSON = generateJSONSchema(json.toString());
    String capabilityName = (String) configJSON.get(JSONConfigurationConstants.CAPABILITY_NAME);
    String fileLocation = FormInputFieldConstants.JSON_PATH + capabilityName + JSONConfigurationConstants.FILE_EXTENSION;
    //Write JSON file
    try (OutputStreamWriter file  = new OutputStreamWriter(new FileOutputStream(fileLocation), StandardCharsets.UTF_8)) {
        file.write(configJSON.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    URI uriSchemaLocation = new File(fileLocation).toURI();
    ConfigParser configParser = new ConfigParser(uriSchemaLocation);
    configParser.parseConfig(TestHelper.getMockedJSONObject(fileLocation));
}


来源: stackexchange

问:
replaceFirst() fails when replacing with "$"
I don't understand why the "$" is special.

```<code>String str = "bla aa";
String tag = "$";
str = str.replaceFirst("aa", tag);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
</code>```

If I change the tag = "\\$", then it works fine.  But why does it need to be escaped?  thanks in advance.

答: Replace first takes regular expression. According to Pattern javadoc $ matches The end of a line.

ContentLicense: CC BY-SA 3.0

Body:
I don't understand why the "$" is special.

String str = "bla aa";
String tag = "$";
str = str.replaceFirst("aa", tag);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

If I change the tag = "\\$", then it works fine.  But why does it need to be escaped?  thanks in advance.


问:
onclick show div and hide other div doesn't work
Could you please help me?

My code doens't work, the section doesnt appear after clicking the bottom section.

```<code><script>
$("#img1").on('click', function() {
   $("#div1").fadeIn();
   $("#div2,#div3,#div4").fadeOut();
});
$("#img2").on('click', function() {
   $("#div2").fadeIn();
   $("#div1,#div3,#div4").fadeOut();
});
$("#img3").on('click', function() {
   $("#div3").fadeIn();
   $("#div1,#div2,#div4").fadeOut();
});
$("#img4").on('click', function() {
   $("#div4").fadeIn();
   $("#div1,#div2,#div3").fadeOut();
});
</script>
</code>```

http://bookshark.phlexon.com/home-2/

Thanks so much!

答:
Try this.

Your jQuery library is initiated but $ is not part of it.

```<code><script>
jQuery("#img1").on('click', function() {
   jQuery("#div1").fadeIn();
   jQuery("#div2,#div3,#div4").fadeOut();
});
jQuery("#img2").on('click', function() {
   jQuery("#div2").fadeIn();
   jQuery("#div1,#div3,#div4").fadeOut();
});
jQuery("#img3").on('click', function() {
   jQuery("#div3").fadeIn();
   jQuery("#div1,#div2,#div4").fadeOut();
});
jQuery("#img4").on('click', function() {
   jQuery("#div4").fadeIn();
   jQuery("#div1,#div2,#div3").fadeOut();
});
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Could you please help me?

My code doens't work, the section doesnt appear after clicking the bottom section.

http://bookshark.phlexon.com/home-2/

Thanks so much!

Body:
Try this.

Your jQuery library is initiated but $ is not part of it.

<script>
jQuery("#img1").on('click', function() {
   jQuery("#div1").fadeIn();
   jQuery("#div2,#div3,#div4").fadeOut();
});
jQuery("#img2").on('click', function() {
   jQuery("#div2").fadeIn();
   jQuery("#div1,#div3,#div4").fadeOut();
});
jQuery("#img3").on('click', function() {
   jQuery("#div3").fadeIn();
   jQuery("#div1,#div2,#div4").fadeOut();
});
jQuery("#img4").on('click', function() {
   jQuery("#div4").fadeIn();
   jQuery("#div1,#div2,#div3").fadeOut();
});
</script>


问:
Python - Threading, Timing, or function use?
I am having an issue formulating an idea on how to work this problem. Please help.

My project consists of an N x N grid with a series of blocks that are supposed to move in a random direction and random velocity within this grid (every .1 seconds, the location of the block is updated with the velocity). I have three "special" blocks that are expected to have individual movement functions. I will have other blocks (many of them) doing nothing but updating their location, and making sure they remain in the grid.

Now these three blocks have functions beyond movement, but each of these runs individually, waiting for the other block's special function to finish (block 2 will wait on block 1, Block 3 will wait on 2 and set it back to block 1, etc.) This queue of sorts will be running while the motion is happening. I want the motion to never stop. After each block's non-movement function runs n times, the code finishes.

My question is this: should I use threads to start and stop the non-movement functions, or is there a way to just set a time and set booleans that could use a class function after .1 seconds to continuously move the objects (and obviously loop over and over), and then use counts to end the program all together? If so, how would you write main function for this in Python? For all of this happening, does anyone think that Java would be significantly faster than Python in running this, especially if writing the data to a .txt file?

答:
Your best bet is probably to handle all of them at once in a single update function rather than attempting to use Threads.  This is primarily because the Global Interpreter Lock will prevent multiple threads from processing concurrently anyway.  What you're after then is something like this:

```<code>def tick():
  for box in randomBoxes:
    box.relocate()

  specialBlock1.relocate()

  specialBlock2.relocate()

  specialBlock3.relocate()
</code>```

Then we define a second function that will run our first function indefinitely:

```<code>def worker():
  while True:
    tick()

    sleep(0.1)
</code>```

Now that we have an interval or sorts, we'll launch a Thread that runs in the background and handles our display updates.

```<code>from threading import Thread

t = Thread(target = worker, name = "Grid Worker")

t.daemon = True # Useful when this thread is not the main thread.

t.start()
</code>```

In our tick() function we've worked in the requirements that specialBlocks 1, 2, and 3 are working in a set order.  The other boxes each take their actions regardless of what the others do.

Body:
Your best bet is probably to handle all of them at once in a single update function rather than attempting to use Threads.  This is primarily because the Global Interpreter Lock will prevent multiple threads from processing concurrently anyway.  What you're after then is something like this:

def tick():
  for box in randomBoxes:
    box.relocate()

  specialBlock1.relocate()

  specialBlock2.relocate()

  specialBlock3.relocate()

Then we define a second function that will run our first function indefinitely:

def worker():
  while True:
    tick()

    sleep(0.1)

Now that we have an interval or sorts, we'll launch a Thread that runs in the background and handles our display updates.

from threading import Thread

t = Thread(target = worker, name = "Grid Worker")

t.daemon = True # Useful when this thread is not the main thread.

t.start()

In our tick() function we've worked in the requirements that specialBlocks 1, 2, and 3 are working in a set order.  The other boxes each take their actions regardless of what the others do.


问:
Having trouble removing first and last character from urls in csv
I am getting the following error when using requests requests.exceptions.InvalidSchema: No connection adapters were found for'['https://www.example.com/contact/find..']' . So there are these two braces at the start and at the end of the links which I am reading from a csv file. These braces end up there because of this statement links_total.append('https://www.example.com'+cell_link['href']) . I am trying to slice the row before requests .Is not working. I used row = row[1:-1] which gives the following error requests.exceptions.InvalidURL: Failed to parse: []. I'd like to remove these braces.

```<code>try:
    with open('rt.csv', 'r') as read_obj:
      csv_reader = reader(read_obj)
      for row in csv_reader:
        row = row[1:-1]
        page2 = requests.get(row)
</code>```

This line is from a program I used to scrape these links to the csv file. links_total.append('https://www.example.com'+cell_link['href'])

答: Try using re module, check the re module documentation

Body:
I am getting the following error when using requests requests.exceptions.InvalidSchema: No connection adapters were found for'['https://www.example.com/contact/find..']' . So there are these two braces at the start and at the end of the links which I am reading from a csv file. These braces end up there because of this statement links_total.append('https://www.example.com'+cell_link['href']) . I am trying to slice the row before requests .Is not working. I used row = row[1:-1] which gives the following error requests.exceptions.InvalidURL: Failed to parse: []. I'd like to remove these braces.

try:
    with open('rt.csv', 'r') as read_obj:
      csv_reader = reader(read_obj)
      for row in csv_reader:
        row = row[1:-1]
        page2 = requests.get(row)

This line is from a program I used to scrape these links to the csv file. links_total.append('https://www.example.com'+cell_link['href'])


问:
Python to an exe File
I am trying to convert my python file which uses transformers, spacy, and torch as packages, into an .exe file. I have tried both cx_freeze and pyinstaller but every time I try to run my generated exe I face the following errors respectively.

For Pyinstaller:

```<code>    C:\Users\aishv\output>qa.exe
To use data.metrics please install scikit-learn. See https://scikit-learn.org/stable/index.html
Traceback (most recent call last):
  File "main.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\transformers\__init__.py", line 42, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\transformers\tokenization_auto.py", line 28, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\transformers\tokenization_xlm.py", line 27, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\sacremoses\__init__.py", line 2, in <module>
    """This directory is meant for IPython extensions."""
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\sacremoses\tokenize.py", line 16, in <module>
  File "site-packages\sacremoses\tokenize.py", line 23, in MosesTokenizer
  File "site-packages\sacremoses\corpus.py", line 63, in chars
  File "pkgutil.py", line 637, in get_data
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 471, in get_data
    with open(path, 'rb') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\aishv\\AppData\\Local\\Temp\\_MEI228322\\sacremoses\\data\\perluniprops\\IsN.txt'
[23284] Failed to execute script main
</code>```

For cx_freeze:

```<code>Traceback (most recent call last):
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 40, in run
    module.run()
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\cx_Freeze\initscripts\Console.py", line 37, in run
    exec(code, {'__name__': '__main__'})
  File "main.py", line 1, in <module>
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\transformers\__init__.py", line 20, in <module>
    from .file_utils import (TRANSFORMERS_CACHE, PYTORCH_TRANSFORMERS_CACHE, PYTORCH_PRETRAINED_BERT_CACHE,
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\transformers\file_utils.py", line 20, in <module>
    import boto3
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\boto3\__init__.py", line 16, in <module>
    from boto3.session import Session
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\boto3\session.py", line 17, in <module>
    import botocore.session
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\session.py", line 30, in <module>
    import botocore.client
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\client.py", line 16, in <module>
    from botocore import waiter, xform_name
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\waiter.py", line 18, in <module>
    from botocore.docs.docstring import WaiterDocstring
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\__init__.py", line 15, in <module>
    from botocore.docs.service import ServiceDocumenter
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\service.py", line 18, in <module>
    from botocore.docs.bcdoc.restdoc import DocumentStructure
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\bcdoc\restdoc.py", line 16, in <module>
    from botocore.docs.bcdoc.docstringparser import DocStringParser
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\bcdoc\docstringparser.py", line 16, in <module>
    class DocStringParser(six.moves.html_parser.HTMLParser):
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\vendored\six.py", line 92, in __get__
    result = self._resolve()
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\vendored\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\vendored\six.py", line 82, in _import_module
    __import__(name)
ModuleNotFoundError: No module named 'html.parser'
</code>```

Please help me in this situation.
Here is my setup file for Cx_freeze:

```<code>from cx_Freeze import setup, Executable
setup(name='Qa',
        version='0.1',
        description='Application',
        executables = [Executable("main.py")])
</code>```

答:
For windows use this, also the error is because of the missing dependencies.

```<code>import sys
base = 'Win32GUI' if sys.platform=='win32' else None

executables = [
    Executable('main.py', base=base)
]

setup(name='editor',
      version = '1.0',
      description = '',
      options = dict(build_exe = buildOptions),
      executables = executables)
</code>```

Try to create a virtual env, satisfy all dependencies in it then create exe file.

Title: Python to an exe File

Body:
I am trying to convert my python file which uses transformers, spacy, and torch as packages, into an .exe file. I have tried both cx_freeze and pyinstaller but every time I try to run my generated exe I face the following errors respectively.

For Pyinstaller:

    C:\Users\aishv\output>qa.exe
To use data.metrics please install scikit-learn. See https://scikit-learn.org/stable/index.html
Traceback (most recent call last):
  File "main.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\transformers\__init__.py", line 42, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\transformers\tokenization_auto.py", line 28, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\transformers\tokenization_xlm.py", line 27, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\sacremoses\__init__.py", line 2, in <module>
    """This directory is meant for IPython extensions."""
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\sacremoses\tokenize.py", line 16, in <module>
  File "site-packages\sacremoses\tokenize.py", line 23, in MosesTokenizer
  File "site-packages\sacremoses\corpus.py", line 63, in chars
  File "pkgutil.py", line 637, in get_data
  File "c:\users\aishv\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 471, in get_data
    with open(path, 'rb') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\aishv\\AppData\\Local\\Temp\\_MEI228322\\sacremoses\\data\\perluniprops\\IsN.txt'
[23284] Failed to execute script main

For cx_freeze:

Traceback (most recent call last):
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 40, in run
    module.run()
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\cx_Freeze\initscripts\Console.py", line 37, in run
    exec(code, {'__name__': '__main__'})
  File "main.py", line 1, in <module>
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\transformers\__init__.py", line 20, in <module>
    from .file_utils import (TRANSFORMERS_CACHE, PYTORCH_TRANSFORMERS_CACHE, PYTORCH_PRETRAINED_BERT_CACHE,
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\transformers\file_utils.py", line 20, in <module>
    import boto3
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\boto3\__init__.py", line 16, in <module>
    from boto3.session import Session
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\boto3\session.py", line 17, in <module>
    import botocore.session
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\session.py", line 30, in <module>
    import botocore.client
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\client.py", line 16, in <module>
    from botocore import waiter, xform_name
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\waiter.py", line 18, in <module>
    from botocore.docs.docstring import WaiterDocstring
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\__init__.py", line 15, in <module>
    from botocore.docs.service import ServiceDocumenter
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\service.py", line 18, in <module>
    from botocore.docs.bcdoc.restdoc import DocumentStructure
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\bcdoc\restdoc.py", line 16, in <module>
    from botocore.docs.bcdoc.docstringparser import DocStringParser
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\docs\bcdoc\docstringparser.py", line 16, in <module>
    class DocStringParser(six.moves.html_parser.HTMLParser):
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\vendored\six.py", line 92, in __get__
    result = self._resolve()
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\vendored\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\Users\aishv\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\vendored\six.py", line 82, in _import_module
    __import__(name)
ModuleNotFoundError: No module named 'html.parser'

Please help me in this situation.
Here is my setup file for Cx_freeze:

from cx_Freeze import setup, Executable
setup(name='Qa',
        version='0.1',
        description='Application',
        executables = [Executable("main.py")])

Body:
For windows use this, also the error is because of the missing dependencies.

import sys
base = 'Win32GUI' if sys.platform=='win32' else None

executables = [
    Executable('main.py', base=base)
]

setup(name='editor',
      version = '1.0',
      description = '',
      options = dict(build_exe = buildOptions),
      executables = executables)

Try to create a virtual env, satisfy all dependencies in it then create exe file.


问:
Programattically set barbutton " System Item"
I want to set share button on rightbarbuttonitem of navigation controller.
I don't want to add custom images , I want use share button image provided by Xcode.This is how I do in storyboard.
I set Style , and set System_Item as Action.

Now the question is how do I set System_Item programatically, if I create barbuttonitem programatically ?

```<code>let shareButton = UIBarButtonItem(title: "",
                                  style: .plain,
                                  target: self,
                                  action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor

    navigationItem.rightBarButtonItem = shareButton
</code>```

答:
you need to use UIBarButtonSystemItemAction option to get share action directly </p>

```<code>   let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor
    navigationItem.rightBarButtonItem = share
</code>```

<p>and handle the action as like </p>

```<code>@objc func shareAction(sender: UIBarButtonItem) {

}
</code>```

Body:
I want to set share button on rightbarbuttonitem of navigation controller.
I don't want to add custom images , I want use share button image provided by Xcode.This is how I do in storyboard.
I set Style , and set System_Item as Action.

Now the question is how do I set System_Item programatically, if I create barbuttonitem programatically ?

let shareButton = UIBarButtonItem(title: "",
                                  style: .plain,
                                  target: self,
                                  action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor

    navigationItem.rightBarButtonItem = shareButton

Body:
you need to use UIBarButtonSystemItemAction option to get share action directly

   let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor
    navigationItem.rightBarButtonItem = share

and handle the action as like

@objc func shareAction(sender: UIBarButtonItem) {

}


问:
Helm, create env var with image tag value
I'm fairly new to helm as I use charts created by other ppl for our applications and I'm trying to do something that I suppose is kinda easy but couldn't manage to find how to. Basically I want to pass application version to my react app. Based on the few information I found, here is what I came up with

```<code>image:
    tag: 0.2.6
extraEnv:
  - name: REACT_APP_APP_VERSION
    value: {image.tag}
</code>```

thx in advance

答:
From Documentation

The tpl function allows developers to evaluate strings as templates inside a template. This is useful to pass a template string as a value to a chart or render external configuration files. Syntax: {{ tpl TEMPLATE_STRING VALUES }}

You will have something similar to

values.yaml

```<code>image:
  repository: k8s.gcr.io/busybox
  tag: "latest"

extraEnv: "{{ .Values.image.tag }}"
</code>```

pod.yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
  - name: test
    image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
    env:
    - name: REACT_APP_APP_VERSION
      value: {{ tpl .Values.extraEnv . }}
</code>```

helm template output for pod.yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
  - name: test
    image: "k8s.gcr.io/busybox:latest"
    env:
    - name: REACT_APP_APP_VERSION
      value: latest
</code>```

Body:
I'm fairly new to helm as I use charts created by other ppl for our applications and I'm trying to do something that I suppose is kinda easy but couldn't manage to find how to. Basically I want to pass application version to my react app. Based on the few information I found, here is what I came up with

image:
    tag: 0.2.6
extraEnv:
  - name: REACT_APP_APP_VERSION
    value: {image.tag}

thx in advance

Body:
From Documentation

The tpl function allows developers to evaluate strings as templates inside a template. This is useful to pass a template string as a value to a chart or render external configuration files. Syntax: {{ tpl TEMPLATE_STRING VALUES }}

You will have something similar to

values.yaml

image:
  repository: k8s.gcr.io/busybox
  tag: "latest"

extraEnv: "{{ .Values.image.tag }}"

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
  - name: test
    image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
    env:
    - name: REACT_APP_APP_VERSION
      value: {{ tpl .Values.extraEnv . }}

helm template output for pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
  - name: test
    image: "k8s.gcr.io/busybox:latest"
    env:
    - name: REACT_APP_APP_VERSION
      value: latest


问:
Finding Recently Edited File in Bash
I am having some problem writing a script that gets two file names from the user and then comparing those two files of which one is edited more recently.

BASH FILE:

```<code>#!/bin/bash

    echo "Please Enter The File Names:"
    read filename1 filename2

    if [ $(filename1) -nt $(filename2) ]; then
        echo "$filename1 has been updated more recently"

    else
        echo " $filename2 has been updated more recently"
    fi
</code>```

CURRENT OUTPUT:

```<code>Please Enter The File Names:
testFile1.c testFile2.c
./newerthanQuestion.sh: line 6: filename1: command not found
./newerthanQuestion.sh: line 6: filename2: command not found
testFile1.c has been updated more recently
</code>```

I am not quite sure why it is showing command not found. Can someone point me in the right direction. Thank you.

答:
replace this

```<code> if [ $(filename1) -nt $(filename2) ]; then
</code>```

with this:

```<code> if [ $filename1 -nt $filename2 ]; then
</code>```

$(command) is called command substitution, and it is used if you want to replace $(command) with the result of command

Title: Finding Recently Edited File in Bash

Body:
I am having some problem writing a script that gets two file names from the user and then comparing those two files of which one is edited more recently.

BASH FILE:

#!/bin/bash

    echo "Please Enter The File Names:"
    read filename1 filename2

    if [ $(filename1) -nt $(filename2) ]; then
        echo "$filename1 has been updated more recently"

    else
        echo " $filename2 has been updated more recently"
    fi

CURRENT OUTPUT:

Please Enter The File Names:
testFile1.c testFile2.c
./newerthanQuestion.sh: line 6: filename1: command not found
./newerthanQuestion.sh: line 6: filename2: command not found
testFile1.c has been updated more recently

I am not quite sure why it is showing command not found. Can someone point me in the right direction. Thank you.

Body:
replace this

 if [ $(filename1) -nt $(filename2) ]; then

with this:

 if [ $filename1 -nt $filename2 ]; then

$(command) is called command substitution, and it is used if you want to replace $(command) with the result of command


问:
ec2 instance skip terminated instances
The script seen, it works but I noticed another issue which I would appreciate a hint how to fix.   when it comes across an instance that is terminated it barffs, it seems to complete but at the very end it barffs. not sure if that will always be the results. I am wondering if a try/except will work here of I just need to skip. here is my code, but once it hits a terminated instance I this error. I think we have a few instances that rebuild themselves on a constant bases. I assume it is barffing because it can't find the vpc and or subnet.

I am thinking I need to pass them or ignore them but im kind of lost here..

```<code>EC2 State is: terminated
Traceback (most recent call last):
  File "./list_ec2_instance.py.3", line 57, in <module>
    main()
  File "./list_ec2_instance.py.3", line 53, in main
    list_instance()
  File "./list_ec2_instance.py.3", line 37, in list_instance
    print("VPC Id is: {}".format(instance_id['VpcId']))
KeyError: 'VpcId'
</code>```

my code is:

```<code>for item in response['Reservations']:
    #pprint(item['Instances'])
        print("AWS Account ID: {}".format(item['OwnerId']))
        for instance_id in item['Instances']:
            #print(instance_id)
            Tags = instance_id['Tags']
            tag_name_value = ""
            for tag in Tags:
                if tag['Key'] == "Name":
                    tag_name_value = tag["Value"]
                    break
            #Tags = instance_id['Tags']['Value']
            State = instance_id['State']['Name']
            #print("EC2 Name: {}".format(Tags))
            print("EC2 Name: {}".format(tag_name_value))
            print("Instance Id is: {}\nInstance Type is: {}".format(instance_id['InstanceId'],instance_id['InstanceType']))
            print("EC2 State is: {}".format(State))
            print("VPC Id is: {}".format(instance_id['VpcId']))
            print("Subnet Id is: {}".format(instance_id['SubnetId']))
</code>```

答:
You can change this:

```<code>print("VPC Id is: {}".format(instance_id['VpcId']))
</code>```

into

```<code>if 'VpcId' in instance_id:
    print("VPC Id is: {}".format(instance_id['VpcId']))
</code>```

Title: ec2 instance skip terminated instances

Body:
The script seen, it works but I noticed another issue which I would appreciate a hint how to fix.   when it comes across an instance that is terminated it barffs, it seems to complete but at the very end it barffs. not sure if that will always be the results. I am wondering if a try/except will work here of I just need to skip. here is my code, but once it hits a terminated instance I this error. I think we have a few instances that rebuild themselves on a constant bases. I assume it is barffing because it can't find the vpc and or subnet.

I am thinking I need to pass them or ignore them but im kind of lost here..

EC2 State is: terminated
Traceback (most recent call last):
  File "./list_ec2_instance.py.3", line 57, in <module>
    main()
  File "./list_ec2_instance.py.3", line 53, in main
    list_instance()
  File "./list_ec2_instance.py.3", line 37, in list_instance
    print("VPC Id is: {}".format(instance_id['VpcId']))
KeyError: 'VpcId'

my code is:

for item in response['Reservations']:
    #pprint(item['Instances'])
        print("AWS Account ID: {}".format(item['OwnerId']))
        for instance_id in item['Instances']:
            #print(instance_id)
            Tags = instance_id['Tags']
            tag_name_value = ""
            for tag in Tags:
                if tag['Key'] == "Name":
                    tag_name_value = tag["Value"]
                    break
            #Tags = instance_id['Tags']['Value']
            State = instance_id['State']['Name']
            #print("EC2 Name: {}".format(Tags))
            print("EC2 Name: {}".format(tag_name_value))
            print("Instance Id is: {}\nInstance Type is: {}".format(instance_id['InstanceId'],instance_id['InstanceType']))
            print("EC2 State is: {}".format(State))
            print("VPC Id is: {}".format(instance_id['VpcId']))
            print("Subnet Id is: {}".format(instance_id['SubnetId']))

Body:
You can change this:

print("VPC Id is: {}".format(instance_id['VpcId']))

into

if 'VpcId' in instance_id:
    print("VPC Id is: {}".format(instance_id['VpcId']))


问:
Unable to create a new module (module already exists) Intellij
I am trying to create a new module in my project. As soon as I specify the name of the module, Intellij throws "That this module already exists". After I exit the wizard it creates a directory with same module name but doesn't make it a module. I delete the directory and I perform "Invalidate Caches and Restart" but still the error persists.

答:
If you are using Gradle and this is a multi-project layout, which is looks like it is, you shouldn't create modules directly in IntelliJ.

Rather, create the directory manually if it doesn't already exists, create a gradle.build[.kts] file in it if needed, and then add an import statement for it in settings.gradle[.kts]. Then just refresh the Gradle configuration in IntelliJ ("Reimport All Gradle Projects").


问:
How to generate libpjsua2.so for x86 abi in jnilibs
I want to test the app with android 10 in emulator.So for that I only have "armeabi", "armeabi-v7a","arm64-v8a" in jnilibs. But running app with android 10 device(Emulator), requires x86 abi. So for that first I have downloaded ndk for x86.And the second thing is I want to generate libpjsua2.so for x86 abi.
I am using pjsip library.
I have referred to https://trac.pjsip.org/repos/wiki/Getting-Started/Android. What I have tried is,
1) Downloaded latest pjsip version and extracted in folder.
2) Followed the steps given in pjsip website as below,

```<code>$ cd /path/to/your/pjsip/dir
$ export ANDROID_NDK_ROOT=/path_to_android_ndk_dir
$ ./configure-android
$ make dep && make clean && make
</code>```

```<code>$ cd /path/to/your/pjsip/dir
$ make clean

# cleanup pjsua sample app
$ cd pjsip-apps/src/pjsua/android/jni
$ make clean

# also cleanup pjsua2 sample app (SWIG)
$ cd /path/to/your/pjsip/dir
$ cd pjsip-apps/src/swig
$ make clean
</code>```

```<code>$ cd pjsip-apps/src/swig
$ make clean
</code>```

```<code>TARGET_ABI=x86 ./configure-android --use-ndk-cflags
</code>```

Got error when reached above code,

```<code>LDFLAGS =  --sysroot= -L/libs/x86/
 LIBS = -lgnustl_static  -lc -lgcc -ldl
 AR = /home/Android/android-ndk-r21b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++
 RANLIB = /home/Android/android-ndk-r21b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++
 TARGET_HOST = llvm-linux-android
 TARGET_ABI = x86
checking build system type... x86_64-unknown-linux-gnu
checking host system type... Invalid configuration `llvm-linux-android': machine `llvm' not recognized
aconfigure: error: /bin/sh ./config.sub llvm-linux-android failed
</code>```

In my pjsip2.7 folder I found a folder named llvm but that is a empty folder. I doesn't know What is that. I am using cent os 7. Why I am getting this error? What do I need to do to overcome this.

答:
Try compile with this builder

replace in ./config.cong you are using 2.10

```<code># PJSIP Version to download
PJSIP_VERSION=2.10
</code>```

```<code>./prepare-build-system
</code>```

and then

```<code>./build
</code>```

Body:
I want to test the app with android 10 in emulator.So for that I only have "armeabi", "armeabi-v7a","arm64-v8a" in jnilibs. But running app with android 10 device(Emulator), requires x86 abi. So for that first I have downloaded ndk for x86.And the second thing is I want to generate libpjsua2.so for x86 abi.
I am using pjsip library.
I have referred to https://trac.pjsip.org/repos/wiki/Getting-Started/Android. What I have tried is,
1) Downloaded latest pjsip version and extracted in folder.
2) Followed the steps given in pjsip website as below,

$ cd /path/to/your/pjsip/dir
$ export ANDROID_NDK_ROOT=/path_to_android_ndk_dir
$ ./configure-android
$ make dep && make clean && make

$ cd /path/to/your/pjsip/dir
$ make clean

# cleanup pjsua sample app
$ cd pjsip-apps/src/pjsua/android/jni
$ make clean

# also cleanup pjsua2 sample app (SWIG)
$ cd /path/to/your/pjsip/dir
$ cd pjsip-apps/src/swig
$ make clean

$ cd pjsip-apps/src/swig
$ make clean

TARGET_ABI=x86 ./configure-android --use-ndk-cflags

Got error when reached above code,

LDFLAGS =  --sysroot= -L/libs/x86/
 LIBS = -lgnustl_static  -lc -lgcc -ldl
 AR = /home/Android/android-ndk-r21b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++
 RANLIB = /home/Android/android-ndk-r21b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++
 TARGET_HOST = llvm-linux-android
 TARGET_ABI = x86
checking build system type... x86_64-unknown-linux-gnu
checking host system type... Invalid configuration `llvm-linux-android': machine `llvm' not recognized
aconfigure: error: /bin/sh ./config.sub llvm-linux-android failed

In my pjsip2.7 folder I found a folder named llvm but that is a empty folder. I doesn't know What is that. I am using cent os 7. Why I am getting this error? What do I need to do to overcome this.

Body:
Try compile with this builder

replace in ./config.cong you are using 2.10

# PJSIP Version to download
PJSIP_VERSION=2.10

./prepare-build-system

and then

./build


问:
jQuery get img width after src change and before fadeIn
I've got quite the problem with jQuery and a custom photo gallery I am building.  I've searched high and low and tried endlessly different solutions but nothing is working perfectly.  So let me present the information:

This photo gallery has thumbnails on the left side and a big image in the center.  Every thumbnail can be clicked which calls a function passing in its' ID.  What I want it to do is, AJAX POST to server to get image comment and image name.  Fadeout the current big picture div, switch the src in the img tag, get the new image's width, set the width of an overlaying comment div, fadeIn the big picture div.

The problem is that I can't get the width of the new image after it has loaded (even using the a form of .load() to wait for the image to finish loading).  Now I can get it to work when I fadeIn the new image and then get the width but that isn't what I need.  I need to get the width and set the div's width before I fadeIn.

Any ideas or corrections would be great, hopefully I have provided enough information.

Here is the code I am wrestling with:

```<code>function thumbClick(val) {
    $.post('ajax.php', {
        photo_in: val
    }, function (data) {
        $('div#picture').fadeOut('slow', function () {

            //$('img#big-picture').load(function(){
            $('img#big-picture').one('load', function () {

                //alert($('img#big-picture').width());
                //will alert 0
                $('div#picture').fadeIn('slow', function () {
                    $('div#comment-box').width($('img#big-picture').width());
                    //set comment to what I want
                    $('p#comment').html("");
                    //alert($('img#big-picture').width());
                    //will alert new image width after FadeIN
                    $('p#comment').html(data.comment);
                });

            }); //end of one(load)
            $('img#big-picture').attr("src", data.newImage);

        }); //end of fadeout
    }, "json"); //end of post
}
</code>```

答: You should be able to set the CSS property visibility to hidden and then get the width, as visibility doesn't take it out of the document flow (like display: none), but simply makes it invisible.  Just make sure you set the visibility property back to visible when you fade in.

Body:
I've got quite the problem with jQuery and a custom photo gallery I am building.  I've searched high and low and tried endlessly different solutions but nothing is working perfectly.  So let me present the information:

This photo gallery has thumbnails on the left side and a big image in the center.  Every thumbnail can be clicked which calls a function passing in its' ID.  What I want it to do is, AJAX POST to server to get image comment and image name.  Fadeout the current big picture div, switch the src in the img tag, get the new image's width, set the width of an overlaying comment div, fadeIn the big picture div.

The problem is that I can't get the width of the new image after it has loaded (even using the a form of .load() to wait for the image to finish loading).  Now I can get it to work when I fadeIn the new image and then get the width but that isn't what I need.  I need to get the width and set the div's width before I fadeIn.

Any ideas or corrections would be great, hopefully I have provided enough information.

Here is the code I am wrestling with:

function thumbClick(val) {
    $.post('ajax.php', {
        photo_in: val
    }, function (data) {
        $('div#picture').fadeOut('slow', function () {

            //$('img#big-picture').load(function(){
            $('img#big-picture').one('load', function () {

                //alert($('img#big-picture').width());
                //will alert 0
                $('div#picture').fadeIn('slow', function () {
                    $('div#comment-box').width($('img#big-picture').width());
                    //set comment to what I want
                    $('p#comment').html("");
                    //alert($('img#big-picture').width());
                    //will alert new image width after FadeIN
                    $('p#comment').html(data.comment);
                });

            }); //end of one(load)
            $('img#big-picture').attr("src", data.newImage);

        }); //end of fadeout
    }, "json"); //end of post
}


问:
Deserialize json with auto-trimming strings
I use Newtonsoft.Json library

Is there a way to trim spaces from any string data during deserialization?

```<code>class Program
{
    class Person
    {
        [JsonProperty("name")]
        public string Name;
    }
    static void Main(string[] args)
    {
        var p = JsonConvert.DeserializeObject<Person>(@"{ name: "" John "" }");
        Console.WriteLine("Name is: \"{0}\"", p.Name);
    }
}
</code>```

Added:

Finally, I've got solution with custom converter. Not nice, but better then property with Trim().

If anyone has any ideas how to do it in more natural way, please welcome.

```<code>class Program
{
    sealed class TrimAttribute : Attribute
    { }

    class TrimConverter<T> : JsonConverter where T : new()
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
            var obj = new T();
            serializer.Populate(jObject.CreateReader(), obj);

            var props = objectType.GetFields(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => p.FieldType == typeof(string))
                .Where(p => Attribute.GetCustomAttributes(p).Any(u => (Type) u.TypeId == typeof(TrimAttribute)))
                ;

            foreach (var fieldInfo in props)
            {
                var val = (string) fieldInfo.GetValue(obj);
                fieldInfo.SetValue(obj, val.Trim());
            }

            return obj;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsAssignableFrom(typeof (T));
        }
    }

    [JsonConverter(typeof(TrimConverter<Person>))]
    class Person
    {
        [JsonProperty("name")]
        [Trim]
        public string Name;

        [JsonProperty("surname")]
        public string Surname;
    }
    static void Main(string[] args)
    {
        var p = JsonConvert.DeserializeObject<Person>(@"{ name: "" John "", surname: "" Smith "" }");
        Console.WriteLine("Name is: \"{0}\", \"{1}\"", p.Name, p.Surname);
    }
}
</code>```

答:
In .NET Core 3.1 you can use System.Text.Json to achieve this.

```<code>/// <summary>
/// Trim leading and trailing whitespace.
/// </summary>
public class TrimmingConverter : JsonConverter<string>
{
    /// <summary>
    /// Trim the input string
    /// </summary>
    /// <param name="reader">reader</param>
    /// <param name="typeToConvert">Object type</param>
    /// <param name="options">Existing Value</param>
    /// <returns></returns>
    public override string Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) => reader.GetString()?.Trim();

    /// <summary>
    /// Trim the output string
    /// </summary>
    /// <param name="writer">Writer</param>
    /// <param name="value">value</param>
    /// <param name="options">serializer</param>
    public override void Write(
        Utf8JsonWriter writer,
        string value,
        JsonSerializerOptions options) => writer.WriteStringValue(value?.Trim());
}
</code>```

Body:
I use Newtonsoft.Json library

Is there a way to trim spaces from any string data during deserialization?

class Program
{
    class Person
    {
        [JsonProperty("name")]
        public string Name;
    }
    static void Main(string[] args)
    {
        var p = JsonConvert.DeserializeObject<Person>(@"{ name: "" John "" }");
        Console.WriteLine("Name is: \"{0}\"", p.Name);
    }
}

Added:

Finally, I've got solution with custom converter. Not nice, but better then property with Trim().

If anyone has any ideas how to do it in more natural way, please welcome.

class Program
{
    sealed class TrimAttribute : Attribute
    { }

    class TrimConverter<T> : JsonConverter where T : new()
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
            var obj = new T();
            serializer.Populate(jObject.CreateReader(), obj);

            var props = objectType.GetFields(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => p.FieldType == typeof(string))
                .Where(p => Attribute.GetCustomAttributes(p).Any(u => (Type) u.TypeId == typeof(TrimAttribute)))
                ;

            foreach (var fieldInfo in props)
            {
                var val = (string) fieldInfo.GetValue(obj);
                fieldInfo.SetValue(obj, val.Trim());
            }

            return obj;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsAssignableFrom(typeof (T));
        }
    }

    [JsonConverter(typeof(TrimConverter<Person>))]
    class Person
    {
        [JsonProperty("name")]
        [Trim]
        public string Name;

        [JsonProperty("surname")]
        public string Surname;
    }
    static void Main(string[] args)
    {
        var p = JsonConvert.DeserializeObject<Person>(@"{ name: "" John "", surname: "" Smith "" }");
        Console.WriteLine("Name is: \"{0}\", \"{1}\"", p.Name, p.Surname);
    }
}

Body:
In .NET Core 3.1 you can use System.Text.Json to achieve this.

/// <summary>
/// Trim leading and trailing whitespace.
/// </summary>
public class TrimmingConverter : JsonConverter<string>
{
    /// <summary>
    /// Trim the input string
    /// </summary>
    /// <param name="reader">reader</param>
    /// <param name="typeToConvert">Object type</param>
    /// <param name="options">Existing Value</param>
    /// <returns></returns>
    public override string Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) => reader.GetString()?.Trim();

    /// <summary>
    /// Trim the output string
    /// </summary>
    /// <param name="writer">Writer</param>
    /// <param name="value">value</param>
    /// <param name="options">serializer</param>
    public override void Write(
        Utf8JsonWriter writer,
        string value,
        JsonSerializerOptions options) => writer.WriteStringValue(value?.Trim());
}


问:
not able to understand scope of variable in this code
In this code vid is initialized inside the function, so how can it be used outside the function
( i.e how could vid.play() know that vid is initialised using vid = document.querySelector("#myPlayer")).

```<code>window.onload = init;

let vid;
function init() {
  console.log('page loaded, DOM is ready');
  vid = document.querySelector('#myPlayer');
  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();
}

function playVideo() {
  vid.play();
}
</code>```

答:
You should distinguish between variable declarations and variable affectations (or initialization to use your words). Sometimes both actions are made at the same time (let vid = 'value';) but that's not mandatory.

In Javascript a variable can be used as long as it has been declared. Its value will then be undefined.

For the scope of your variable, it can be seen by both of your functions because it is declared ouside of it, look at the second snippet, if it would have been declared inside init function, it would only be accessible by it, and not visible outside of it.

let vid;

function test(){
    console.log(vid); //declared and not initialized
}

function test2(){
    console.log(vid2); //not declared (and not initialized)
}

test(); //undefined value (no error)
test2(); //error: not declared```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function init(){
    let vid;
}
function test3(){
    init();
    console.log(vid); //declared in another scope
}

test3(); //error: not declared</code>```

Body:
In this code vid is initialized inside the function, so how can it be used outside the function
( i.e how could vid.play() know that vid is initialised using vid = document.querySelector("#myPlayer")).

window.onload = init;

let vid;
function init() {
  console.log('page loaded, DOM is ready');
  vid = document.querySelector('#myPlayer');
  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();
}

function playVideo() {
  vid.play();
}

Body:
You should distinguish between variable declarations and variable affectations (or initialization to use your words). Sometimes both actions are made at the same time (let vid = 'value';) but that's not mandatory.

In Javascript a variable can be used as long as it has been declared. Its value will then be undefined.

For the scope of your variable, it can be seen by both of your functions because it is declared ouside of it, look at the second snippet, if it would have been declared inside init function, it would only be accessible by it, and not visible outside of it.

let vid;

function test(){
    console.log(vid); //declared and not initialized
}

function test2(){
    console.log(vid2); //not declared (and not initialized)
}

test(); //undefined value (no error)
test2(); //error: not declared

function init(){
    let vid;
}
function test3(){
    init();
    console.log(vid); //declared in another scope
}

test3(); //error: not declared


问:
<ng-select> select not working correct
I am using angular2 and  for drop downs. Whenever a do a search in the drop down and listed items matching criteria highlights the text searched for and on click of which it does not get selected item in the drop down. When you select any other text apart from searched text in the item listed, it gets selected. What causes this behaviour?

Code is as mentioned:

```<code><ng-select [items]="tests"
           (data)="updateSelected($event')"
           [active]="selectChannel"
           id="channelList{{tabId}}"
           style="float: left; width: 70%;">
</ng-select>
</code>```

答:
Try this:

```<code><ng-select
           [items]="tests"
            [(ngModel)]='selected'
           (change)="updateSelected(selected)"
           [active]="selectChannel"
           id="channelList{{tabId}}"
           style="float: left; width: 70%;">
</ng-select>
</code>```

Here, selected is a variable you have to declare in the .ts file.

Title: <ng-select> select not working correct

Body:
I am using angular2 and  for drop downs. Whenever a do a search in the drop down and listed items matching criteria highlights the text searched for and on click of which it does not get selected item in the drop down. When you select any other text apart from searched text in the item listed, it gets selected. What causes this behaviour?

Code is as mentioned:

<ng-select [items]="tests"
           (data)="updateSelected($event')"
           [active]="selectChannel"
           id="channelList{{tabId}}"
           style="float: left; width: 70%;">
</ng-select>

Body:
Try this:

<ng-select
           [items]="tests"
            [(ngModel)]='selected'
           (change)="updateSelected(selected)"
           [active]="selectChannel"
           id="channelList{{tabId}}"
           style="float: left; width: 70%;">
</ng-select>

Here, selected is a variable you have to declare in the .ts file.


问:
How to debug kubernetes deployed service using Eclipse
I have a micro service written using Java EE + Openliberty. I have deployed this into kubernetes in my Docker-Desktop. I want to know, is there any way to debug this deployed service? I am using Eclipse. Please let me know how can I debug deployed service. Thank you!

答:
If you want to debug your application, you can do it using either squash or telepresence. Here is great article comparing these two solutions

Article also mentions that squash doesn't support eclipse, but notice that is was written in 2018 and since then squash added support for eclipse IDE.


问:
Javascript - Counting array elements by reduce method until specific value occurs doesn't give a correct output
```<code>const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total)=>(num==0 ? total : total+num), 0)
console.log(sum(arr, 0))
</code>```

<p>Please check how can I make it work. Did some mistake but don't know what exactly. Output is a function instead of a result. </p>

答:
call it as follows:</p>

```<code>console.log(sum(arr, 0)());
</code>```

Body:
const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total)=>(num==0 ? total : total+num), 0)
console.log(sum(arr, 0))

Please check how can I make it work. Did some mistake but don't know what exactly. Output is a function instead of a result.

Body:
call it as follows:

console.log(sum(arr, 0)());


问:
Should the FQDN for ADFS and ADFS servers be the same?
I have two ADFS 2.0 Proxy servers with the name auth.somedomain.no and two ADFS 2.0 servers with the name adfs.somedomain.no.

However, the https://auth.somedomain.no/FederationMetadata/2007-06/FederationMetadata.xml does not expose the https://adfs.somedomain.no/FederationMetadata/2007-06/FederationMetadata.xml

Must the official name of both ADFS and ADFS proxy be equal?

答: The answer is yes. I did the change so that all adfs servers and proxy use the same federation name like sso. The MS documentation is not very precise in this regard.</p>


问:
Spark-SQL using with
I am trying to load up a Parquet file with columns storyId1 and publisher1. I want to find all pairs of publishers that publish articles about the same stories. For each publisher pair need to report the number of co-published stories. Where a co-published story in a story published by both publishers. Report the pairs in decreasing order of frequency. The solution must conform to the following rules:
1.  There should not be any replicated entries like:
NASDAQ, NASDAQ, 1000
2.  Should not have the same pair occurring twice in opposite order. Only one of the following should occur:
NASDAQ, Reuters, 1000
Reuters, NASDAQ, 1000
(i.e. it is incorrect to have both of the above two lines in your result)

Now it have tried following code:

```<code>> import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions._
import spark.implicits._

val worddocDF = spark.read.parquet("file:///home/user204943816622/t4_story_publishers.parquet")
val worddocDF1 = spark.read.parquet("file:///home/user204943816622/t4_story_publishers.parquet")
worddocDF.cache()
val joinDF = worddocDF.join(worddocDF1, "storyId1").withColumnRenamed("worddocDF.publisher1", "publisher2")
joinDF.filter($"publisher1" !== $"publisher2")
</code>```

Input format:

```<code>[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Livemint]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Moneynews]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, NASDAQ]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Los Angeles Times]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, NASDAQ]
</code>```

Required output:

```<code>[

NASDAQ,IFA Magazine,2]

[Moneynews,Livemint,1]

[Moneynews,IFA Magazine,1]

[NASDAQ,Livemint,1]

[NASDAQ,Los Angeles Times,1]

[Moneynews,Los Angeles Times,1]

[Los Angeles Times,IFA Magazine,1]

[Livemint,IFA Magazine,1]

[NASDAQ,Moneynews,1]

[Los Angeles Times,Livemint,1]
</code>```

答:
```<code>import spark.implicits._

    wordDocDf.as("a")
    .join(
      wordDocDf.as("b"),
      $"a.storyId1" === $"b.storyId1" && $"a.publisher1" =!= $"b.publisher1",
      "inner"
    )
    .select(
      $"a.storyId1".as("storyId"),
      $"a.publisher1".as("publisher1"),
      $"b.publisher1".as("publisher2")
    )
</code>```

Title: Spark-SQL using with

Body:
I am trying to load up a Parquet file with columns storyId1 and publisher1. I want to find all pairs of publishers that publish articles about the same stories. For each publisher pair need to report the number of co-published stories. Where a co-published story in a story published by both publishers. Report the pairs in decreasing order of frequency. The solution must conform to the following rules:
1.  There should not be any replicated entries like:
NASDAQ, NASDAQ, 1000
2.  Should not have the same pair occurring twice in opposite order. Only one of the following should occur:
NASDAQ, Reuters, 1000
Reuters, NASDAQ, 1000
(i.e. it is incorrect to have both of the above two lines in your result)

Now it have tried following code:

> import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions._
import spark.implicits._

val worddocDF = spark.read.parquet("file:///home/user204943816622/t4_story_publishers.parquet")
val worddocDF1 = spark.read.parquet("file:///home/user204943816622/t4_story_publishers.parquet")
worddocDF.cache()
val joinDF = worddocDF.join(worddocDF1, "storyId1").withColumnRenamed("worddocDF.publisher1", "publisher2")
joinDF.filter($"publisher1" !== $"publisher2")

Input format:

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Livemint]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Moneynews]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, NASDAQ]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Los Angeles Times]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, NASDAQ]

Required output:

[

NASDAQ,IFA Magazine,2]

[Moneynews,Livemint,1]

[Moneynews,IFA Magazine,1]

[NASDAQ,Livemint,1]

[NASDAQ,Los Angeles Times,1]

[Moneynews,Los Angeles Times,1]

[Los Angeles Times,IFA Magazine,1]

[Livemint,IFA Magazine,1]

[NASDAQ,Moneynews,1]

[Los Angeles Times,Livemint,1]


问:
VSTO AssemblyResolve issue
We develop a VSTO plugin for Word and we have the problem that the earliest entry point of the addin is the AddIn_Startup handler. The issue is that this handler is called too late for the AssemblyResolve handler we implemented to find the needed assemblies.

I sovled the problem by assigning the handler to the AppDomain.CurrentDomain.AssemblyResolve event in the Addins.Designer.cs class, but as you all know, this code is autogenerated.

Is there a way to assign the AssemblyResolve Handler sooner as in the AddIn_Startup handler and in a not autogenerated file?

答:
I have just had this problem, landed here from searching and then had a look around the  VSTO Microsoft.Tools AddinBase Class (I hope this is the right link).  In any case I am Overriding the Begininit and setting AppDomain.CurrentDomain.AssemblyResolve there.  For my case this is early enough to load my reference.

However, please note that the addin can still try to load your assembly (and fail) if it needs it and this can happen even before Begininit. For example if you refer to an Enum or Const from your Assembly in the ThisAddin class.

Title: VSTO AssemblyResolve issue


问:
React TypeError: Cannot read property 'map' of undefined
Updated

I am learning react so using omdbapi api want to fetch data but getting TypeError: Cannot read property 'map' of undefined

Kindly help how to solve this issue

```<code>class App extends React.Component {
  constructor(){
    super()
    this.state={
      data:[],
    }
  }
  componentDidMount(){
    fetch('http://www.omdbapi.com/?i=tt3896198&apikey=key123')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
     this.setState({
       data:findresponse.movie
     })
      })
  }
  render() {
  return (
    <div>
      {this.state.data.map((dynamicData)=>
      <div>
        <img src={dynamicData.Poster} alt=""/>
        <p>{dynamicData.title} </p>
        <p>{dynamicData.Released} </p>
      </div>
      )}
    </div>
  )
}
}
</code>```

After below answer i have updated the source code now in html output is blank but in console.log showing the output

I want to loop 20 movies

```<code>componentDidMount(){
    fetch('http://www.omdbapi.com/?apikey=mykey&s=batman')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
      console.log(findresponse)
     this.setState({
      data:[findresponse]
     })
      })
  }
  render() {
  return (
    <div>
      {this.state.data && this.state.data.map((dynamicData , key)=>
      <div key={key}>
        <img src={dynamicData.Poster} alt=""/>
        <p>{dynamicData.Title} </p>
        <p>{dynamicData.Released} </p>
      </div>
      )}
    </div>
  )
}
}
</code>```

答:
Issue :

As per the api, it returns only one movie object, and it dosen't have movie key either, so you can't map through the json object it should be array.

```<code>// response is taken from http://www.omdbapi.com/?i=tt3896198

{
    "Title": "Guardians of the Galaxy Vol. 2",
    "Year": "2017",
    "Rated": "PG-13",
    "Released": "05 May 2017",
    "Runtime": "136 min",
    "Genre": "Action, Adventure, Comedy, Sci-Fi",
    "Director": "James Gunn",
    "Writer": "James Gunn, Dan Abnett (based on the Marvel comics by), Andy Lanning (based on the Marvel comics by), Steve Englehart (Star-Lord created by), Steve Gan (Star-Lord created by), Jim Starlin (Gamora and Drax created by), Stan Lee (Groot created by), Larry Lieber (Groot created by), Jack Kirby (Groot created by), Bill Mantlo (Rocket Raccoon created by), Keith Giffen (Rocket Raccoon created by), Steve Gerber (Howard the Duck created by), Val Mayerik (Howard the Duck created by)",
    "Actors": "Chris Pratt, Zoe Saldana, Dave Bautista, Vin Diesel",
    "Plot": "The Guardians struggle to keep together as a team while dealing with their personal family issues, notably Star-Lord's encounter with his father the ambitious celestial being Ego.",
    "Language": "English",
    "Country": "USA",
    "Awards": "Nominated for 1 Oscar. Another 15 wins & 56 nominations.",
    "Poster": "https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg",
    "Ratings": [
        {
            "Source": "Internet Movie Database",
            "Value": "7.6/10"
        },
        {
            "Source": "Rotten Tomatoes",
            "Value": "85%"
        },
        {
            "Source": "Metacritic",
            "Value": "67/100"
        }
    ],
    "Metascore": "67",
    "imdbRating": "7.6",
    "imdbVotes": "537,920",
    "imdbID": "tt3896198",
    "Type": "movie",
    "DVD": "22 Aug 2017",
    "BoxOffice": "$389,804,217",
    "Production": "Walt Disney Pictures",
    "Website": "N/A",
    "Response": "True"
}
</code>```

Solution :

For : from http://www.omdbapi.com/?i=tt3896198

```<code>// as there is no `movie` key change `findresponse.movie` to `findresponse`

// if you want to use it as array for only one object
this.setState({
    data:[findresponse]
    // OR
    data : [...this.state.data , findresponse] // <--- If you want pushing result with previous
})

// suggested
this.setState({
    data : findresponse
})
</code>```

For : http://www.omdbapi.com/?apikey=YOUR_KEY&s=Batman , you can use the below one

```<code>this.setState({
    data : findresponse.Search
})
</code>```

Body:
Updated

I am learning react so using omdbapi api want to fetch data but getting TypeError: Cannot read property 'map' of undefined

Kindly help how to solve this issue

class App extends React.Component {
  constructor(){
    super()
    this.state={
      data:[],
    }
  }
  componentDidMount(){
    fetch('http://www.omdbapi.com/?i=tt3896198&apikey=key123')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
     this.setState({
       data:findresponse.movie
     })
      })
  }
  render() {
  return (

      {this.state.data.map((dynamicData)=>

{dynamicData.title}

{dynamicData.Released}

      )}

  )
}
}

After below answer i have updated the source code now in html output is blank but in console.log showing the output

I want to loop 20 movies

componentDidMount(){
    fetch('http://www.omdbapi.com/?apikey=mykey&s=batman')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
      console.log(findresponse)
     this.setState({
      data:[findresponse]
     })
      })
  }
  render() {
  return (

      {this.state.data && this.state.data.map((dynamicData , key)=>

{dynamicData.Title}

{dynamicData.Released}

      )}

  )
}
}

Body:
Issue :

As per the api, it returns only one movie object, and it dosen't have movie key either, so you can't map through the json object it should be array.

// response is taken from http://www.omdbapi.com/?i=tt3896198

{
    "Title": "Guardians of the Galaxy Vol. 2",
    "Year": "2017",
    "Rated": "PG-13",
    "Released": "05 May 2017",
    "Runtime": "136 min",
    "Genre": "Action, Adventure, Comedy, Sci-Fi",
    "Director": "James Gunn",
    "Writer": "James Gunn, Dan Abnett (based on the Marvel comics by), Andy Lanning (based on the Marvel comics by), Steve Englehart (Star-Lord created by), Steve Gan (Star-Lord created by), Jim Starlin (Gamora and Drax created by), Stan Lee (Groot created by), Larry Lieber (Groot created by), Jack Kirby (Groot created by), Bill Mantlo (Rocket Raccoon created by), Keith Giffen (Rocket Raccoon created by), Steve Gerber (Howard the Duck created by), Val Mayerik (Howard the Duck created by)",
    "Actors": "Chris Pratt, Zoe Saldana, Dave Bautista, Vin Diesel",
    "Plot": "The Guardians struggle to keep together as a team while dealing with their personal family issues, notably Star-Lord's encounter with his father the ambitious celestial being Ego.",
    "Language": "English",
    "Country": "USA",
    "Awards": "Nominated for 1 Oscar. Another 15 wins & 56 nominations.",
    "Poster": "https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg",
    "Ratings": [
        {
            "Source": "Internet Movie Database",
            "Value": "7.6/10"
        },
        {
            "Source": "Rotten Tomatoes",
            "Value": "85%"
        },
        {
            "Source": "Metacritic",
            "Value": "67/100"
        }
    ],
    "Metascore": "67",
    "imdbRating": "7.6",
    "imdbVotes": "537,920",
    "imdbID": "tt3896198",
    "Type": "movie",
    "DVD": "22 Aug 2017",
    "BoxOffice": "$389,804,217",
    "Production": "Walt Disney Pictures",
    "Website": "N/A",
    "Response": "True"
}

Solution :

For : from http://www.omdbapi.com/?i=tt3896198

// as there is no `movie` key change `findresponse.movie` to `findresponse`

// if you want to use it as array for only one object
this.setState({
    data:[findresponse]
    // OR
    data : [...this.state.data , findresponse] // <--- If you want pushing result with previous
})

// suggested
this.setState({
    data : findresponse
})

For : http://www.omdbapi.com/?apikey=YOUR_KEY&s=Batman , you can use the below one

this.setState({
    data : findresponse.Search
})


问:
?: ?? Operators Instead Of IF|ELSE
```<code>public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
</code>```

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

```<code>if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
</code>```

[ 2 ]

```<code>if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}
</code>```

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

答: The ternary operator (?:) is not designed for control flow, it's only designed for conditional assignment.  If you need to control the flow of your program, use a control structure, such as if/else.

Title: ?: ?? Operators Instead Of IF|ELSE

Body:
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[ 2 ]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?


问:
Attempted to load class "Mpdf" from namespace "Mpdf"
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
 So I've done the following :

```<code>use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;

class DevisGenerator
{
public function runDevis()
    {
       $spreadsheet = $this->loadexcelTemplate();
       $uuid = $this->uniqidReal();
       $filename = $this->writeName($spreadsheet, $uuid);
       $this->convertPdf($spreadsheet, $filename);

    }

    public function writeName($spreadsheet, $uuid)
    {
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getCell('B2')->setValue('Toto');

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filename = $uuid;
            $writer->save($filename.'.xlsx');
        }catch (Exception $e)
        {
            //TODO gestion erreur
        }
        return $filename;

    }

public function convertPdf($spreadsheet, $filename)
    {
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer->save($filename.'.pdf');

    }

</code>```

But whan I run the code the following error appear :

Attempted to load class "Mpdf" from namespace "Mpdf".
  Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?

I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

答:
After use statement before class, you should use only:</p>

```<code>public function convertPdf($spreadsheet, $filename)
{
    $writer = new Mpdf($spreadsheet);
    $writer->save($filename.'.pdf');
}
</code>```

Body:
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
 So I've done the following :

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;

class DevisGenerator
{
public function runDevis()
    {
       $spreadsheet = $this->loadexcelTemplate();
       $uuid = $this->uniqidReal();
       $filename = $this->writeName($spreadsheet, $uuid);
       $this->convertPdf($spreadsheet, $filename);

    }

    public function writeName($spreadsheet, $uuid)
    {
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getCell('B2')->setValue('Toto');

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filename = $uuid;
            $writer->save($filename.'.xlsx');
        }catch (Exception $e)
        {
            //TODO gestion erreur
        }
        return $filename;

    }

public function convertPdf($spreadsheet, $filename)
    {
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer->save($filename.'.pdf');

    }

But whan I run the code the following error appear :

Attempted to load class "Mpdf" from namespace "Mpdf".
  Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?

I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

Body:
After use statement before class, you should use only:

public function convertPdf($spreadsheet, $filename)
{
    $writer = new Mpdf($spreadsheet);
    $writer->save($filename.'.pdf');
}


答:
You need parenthesis to execute the function ()

```<code>sum(arr, 0)
</code>```

Without parenthesis you store a reference to the function in the variable

Title: Javascript - Counting array elements by reduce method until specific value occurs doesn't give a correct output

Body:
You need parenthesis to execute the function ()

sum(arr, 0)

Without parenthesis you store a reference to the function in the variable


问:
How to convert JSON Object into key value pair in JS?
```<code>{"1":"val1","2":"val2","3":"val3"}
</code>```

i want it to converted like this:

```<code>{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
</code>```

little Help Please would be much appricated

答:
```<code> const obj = {"1":"val1","2":"val2","3":"val3"}

  const newObject = Object.keys(obj).map(e => {
 return {ID: e , value : obj[e] }
   });

  console.log(newObject); // [ { ID: '1', value: 'val1' },
                                { ID: '2', value: 'val2' },
                              { ID: '3', value: 'val3' } ]
</code>```

it will give u an array of object,  later u need to convert it to object and flat the object:

How do I convert array of Objects into one Object in JavaScript?

how to convert this nested object into a flat object?

Body:
{"1":"val1","2":"val2","3":"val3"}

i want it to converted like this:

{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}

little Help Please would be much appricated

Body:
 const obj = {"1":"val1","2":"val2","3":"val3"}

  const newObject = Object.keys(obj).map(e => {
 return {ID: e , value : obj[e] }
   });

  console.log(newObject); // [ { ID: '1', value: 'val1' },
                                { ID: '2', value: 'val2' },
                              { ID: '3', value: 'val3' } ]

it will give u an array of object,  later u need to convert it to object and flat the object:

How do I convert array of Objects into one Object in JavaScript?

how to convert this nested object into a flat object?


问:
Understanding View.drawableStateChanged
Can anyone explain when exactly View.drawableStateChanged is called? I want to use it in conjunction with ViewGroup.setAddStatesFromChildren to make a complete ViewGroup "optically" focused, meaning e.g. change background color when e.g. an EditText of this ViewGroup gets focus.

When I implement View.drawableStateChanged it's called very often, how do I know that the current call is the one I care about? What's the advantage over settings focus listeners on the child Views?

答:
You can learn more about it here.

View.drawableStateChanged() is called whenever the state of the view changes in such
a way that it impacts the state of drawables being shown.

If you create drawable like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#ffff0000"/>
    <item android:state_focused="true"
          android:color="#ff0000ff"/>
    <item android:state_enabled="true"
          android:color="#ff00ffff"/>
    <item android:color="#ff000000"/>
</selector>
</code>```

This drawable has mainly different states(like state_pressed, state_focused, state_enabled). If you have set drawable to a particular view and that view is clickable then when you click on of that view, this state generally changes.

You can use setOnFocusChangeListener to check about focus changes and setOnTouchListener touch events.
Also, you can check to enable/disable the state onClick() event of that view.

Update: This method is deprecated, please follow this link for more.

Title: Understanding View.drawableStateChanged

Body:
You can learn more about it here.

View.drawableStateChanged() is called whenever the state of the view changes in such
a way that it impacts the state of drawables being shown.

If you create drawable like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#ffff0000"/>
    <item android:state_focused="true"
          android:color="#ff0000ff"/>
    <item android:state_enabled="true"
          android:color="#ff00ffff"/>
    <item android:color="#ff000000"/>
</selector>

This drawable has mainly different states(like state_pressed, state_focused, state_enabled). If you have set drawable to a particular view and that view is clickable then when you click on of that view, this state generally changes.

You can use setOnFocusChangeListener to check about focus changes and setOnTouchListener touch events.
Also, you can check to enable/disable the state onClick() event of that view.

Update: This method is deprecated, please follow this link for more.


问:
Update text in Angular Toastr
I would like to change the toastr text already displayed.

I am using the following code to create and trying to update the existing text.

```<code>  if (this.toastr.currentlyActive > 0) {
    this.toastr.toasts.find(toast => toast.toastId == 1).message = "Tempo em Atendimento: " + tempoAtendimento;
  } else {
    this.toastr.info("Tempo em Atendimento: " + tempoAtendimento, "", { timeOut: 0, extendedTimeOut: 0 });
  }
</code>```

I do not receive error message, however, the text is not changed! Any tips?

I am using:
https://github.com/scttcper/ngx-toastr/
Versão:
10.1.0

答:
As an addition to @Minato his answer...

When you create a toastr message, an instance of the ActiveToast is returned. If you store that in a variable you won't have to search for it by id.

```<code>const toast: ActiveToast = this.toastrService.success('My toastr message');
const componentInstance: Toast = toast.toastRef.componentInstance;
setTimeout(
  () => toastComponent.message = 'My changed message', 3000
);
</code>```

Title: Update text in Angular Toastr

Body:
I would like to change the toastr text already displayed.

I am using the following code to create and trying to update the existing text.

  if (this.toastr.currentlyActive > 0) {
    this.toastr.toasts.find(toast => toast.toastId == 1).message = "Tempo em Atendimento: " + tempoAtendimento;
  } else {
    this.toastr.info("Tempo em Atendimento: " + tempoAtendimento, "", { timeOut: 0, extendedTimeOut: 0 });
  }

I do not receive error message, however, the text is not changed! Any tips?

I am using:
https://github.com/scttcper/ngx-toastr/
Versão:
10.1.0

Body:
As an addition to @Minato his answer...

When you create a toastr message, an instance of the ActiveToast is returned. If you store that in a variable you won't have to search for it by id.

const toast: ActiveToast = this.toastrService.success('My toastr message');
const componentInstance: Toast = toast.toastRef.componentInstance;
setTimeout(
  () => toastComponent.message = 'My changed message', 3000
);


问:
Select two tables between dates?
I get this error:

Incorrect syntax near '2020-05-29'.

How to fix this?

```<code>SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate BETWEEN '2020-05-28' AND BorrowerDetails.DueDate '2020-05-29'
</code>```

答:
Between doesn't seem to support two fields.

You may use:

```<code>SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate >= '2020-05-28' AND BorrowerDetails.DueDate <='2020-05-29'
</code>```

Title: Select two tables between dates?

Body:
I get this error:

Incorrect syntax near '2020-05-29'.

How to fix this?

SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate BETWEEN '2020-05-28' AND BorrowerDetails.DueDate '2020-05-29'

Body:
Between doesn't seem to support two fields.

You may use:

SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate >= '2020-05-28' AND BorrowerDetails.DueDate <='2020-05-29'


问:
Why can AppEngine Not Find Mailgun Pakage
I have my Golang App Engine project. I'm no expert of Go and so the package manager is a bit of a mystery to me. I haven't had any issues until now. When I try to use the MailGun Api, it is saying it can't resolve the dependency. I import mailgun like this:
import "github.com/mailgun/mailgun-go".

However when I try to run: gcloud app deploy I get the following error:

```<code> GO111MODULE=auto, but no go.mod found, so building with dependencies from GOPATH
main-package: MyPackage
2020/05/28 08:44:25 Staging second-gen Standard app (GOPATH mode): failed analyzing C:\Users\myUserName\go\src\MyPackage: cannot f
ind package "github.com/mailgun/mailgun-go/v4/events" in any of:
        ($GOROOT not set)
        C:\Users\MyUserName\go\src\github.com\mailgun\mailgun-go\v4\events (from $GOPATH)
GOPATH: C:\Users\MyUserName\go
</code>```

When I navigate to C:\Users\MyUserName\go\src\github.com\mailgun\mailgun-go exists but there is no folders v4 and events... Not sure what the issue is and where it is getting the events folder. Thanks for an help!

答:
The /vX convention is used by Go modules to distinguish between different major versions. This means you need to be using Go modules to consume such a package.

To do this, you'll need to run go mod init within your project's root directory.

Further, if you're using an older version of Go (1.11 or 1.12), you'll need to set GO111MODULE=on to ensure that your code is treated as a Go module.

Body:
I have my Golang App Engine project. I'm no expert of Go and so the package manager is a bit of a mystery to me. I haven't had any issues until now. When I try to use the MailGun Api, it is saying it can't resolve the dependency. I import mailgun like this:
import "github.com/mailgun/mailgun-go".

However when I try to run: gcloud app deploy I get the following error:

 GO111MODULE=auto, but no go.mod found, so building with dependencies from GOPATH
main-package: MyPackage
2020/05/28 08:44:25 Staging second-gen Standard app (GOPATH mode): failed analyzing C:\Users\myUserName\go\src\MyPackage: cannot f
ind package "github.com/mailgun/mailgun-go/v4/events" in any of:
        ($GOROOT not set)
        C:\Users\MyUserName\go\src\github.com\mailgun\mailgun-go\v4\events (from $GOPATH)
GOPATH: C:\Users\MyUserName\go

When I navigate to C:\Users\MyUserName\go\src\github.com\mailgun\mailgun-go exists but there is no folders v4 and events... Not sure what the issue is and where it is getting the events folder. Thanks for an help!


问:
Jest allow multi types for object structure match
I am trying to create a test with jest which has to check if an object key is a string or a number.

Simple like this, but I cannot find anything in the documentation.

Test Example:

```<code>test('Assets structure is right', () => {
    const assetExpectedStructure = {
      id: expect.any(String),
      source_type: expect.any(String),
      media_types: expect.any(Array),
      source_id: expect.any(String)   // <------------ HERE  String or Number
    }

    for (const asset of assets) {
        expect(asset).toMatchObject(assetExpectedStructure)
    }
 }
</code>```

I could do expect.anything(), but this gets also other types  (Boolean, Objects etc.) which I don't want.

Does someone have an idea how to do this?

答:
I'm not super familiar with the library, but from the documentation, you can add your own matches:</p>

```<code>expect.extend({
  toBeOneOf(received, constructors = [String, Number]) {
    const pass = !!constructors.find(c => received.constructor === c);
    if (pass) {
      return {
        message: () => `looks good`,
        pass: true,
      };
    } else {
      return {
        message: () => `no so good....`,
        pass: false,
      };
    }
  },
});
</code>```

Body:
I am trying to create a test with jest which has to check if an object key is a string or a number.

Simple like this, but I cannot find anything in the documentation.

Test Example:

test('Assets structure is right', () => {
    const assetExpectedStructure = {
      id: expect.any(String),
      source_type: expect.any(String),
      media_types: expect.any(Array),
      source_id: expect.any(String)   // <------------ HERE  String or Number
    }

    for (const asset of assets) {
        expect(asset).toMatchObject(assetExpectedStructure)
    }
 }

I could do expect.anything(), but this gets also other types  (Boolean, Objects etc.) which I don't want.

Does someone have an idea how to do this?

Body:
I'm not super familiar with the library, but from the documentation, you can add your own matches:

expect.extend({
  toBeOneOf(received, constructors = [String, Number]) {
    const pass = !!constructors.find(c => received.constructor === c);
    if (pass) {
      return {
        message: () => `looks good`,
        pass: true,
      };
    } else {
      return {
        message: () => `no so good....`,
        pass: false,
      };
    }
  },
});