问:
Error when running pyinstaller (1920, 'LoadLibraryEx', 'System cannot access the file')
Im trying to compile my python script to an exe so that i can send it to friends that can use with without having to install python, but im running into an issue and cant find a solution.

i found a similar issue at Pyinstaller win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryExW', 'System cannot access the file')

but cant post there except as a answer, i tried to add permissions and unhide the 'WindowsApps' folder but nothing seems to work.

Here is what cmd is giving me when running pyinstaller

and 'Systemet kan inte komma åt filen' is swedish for 'System cannot access the file'

```<code>100 INFO: PyInstaller: 3.5
101 INFO: Python: 3.7.4
101 INFO: Platform: Windows-10-10.0.18362-SP0
103 INFO: wrote C:\Users\Jonathan\Pictures\shimbot2\gui.spec
106 INFO: UPX is not available.
109 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Jonathan\\Pictures', 'C:\\Users\\Jonathan\\Pictures\\shimbot2']
110 INFO: checking Analysis
110 INFO: Building Analysis because Analysis-00.toc is non existent
111 INFO: Initializing module dependency graph...
116 INFO: Initializing module graph hooks...
119 INFO: Analyzing base_library.zip ...
4140 INFO: running Analysis Analysis-00.toc
Traceback (most recent call last):
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\pywintypes.py", line 35, in pywin32error
    yield
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\win32api.py", line 43, in LoadLibraryEx
    return _dll._LoadLibraryEx(fileName, 0, flags)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\core\cffi\_dll.py", line 26, in _LoadLibraryEx
    function_name='LoadLibraryEx')
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\core\cffi\_util.py", line 81, in __call__
    self._raise_error(function_name)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\core\cffi\_util.py", line 92, in _raise_error
    raise exception
OSError: [WinError 1920] Systemet kan inte komma åt filen

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1264.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1264.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Jonathan\Pictures\shimbot2\pyinstaller.exe\__main__.py", line 7, in <module>
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 844, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 791, in build
    exec(code, spec_namespace)
  File "C:\Users\Jonathan\Pictures\shimbot2\gui.spec", line 17, in <module>
    noarchive=False)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 243, in __init__
    self.__postinit__()
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
    self.assemble()
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 405, in assemble
    redirects=self.binding_redirects)[1:])
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\depend\bindepend.py", line 231, in Dependencies
    for ftocnm, fn in getAssemblyFiles(pth, manifest, redirects):
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\depend\bindepend.py", line 407, in getAssemblyFiles
    for assembly in getAssemblies(pth):
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\depend\bindepend.py", line 358, in getAssemblies
    res = GetManifestResources(pth)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\utils\win32\winmanifest.py", line 1005, in GetManifestResources
    return winresource.GetResources(filename, [RT_MANIFEST], names, languages)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\utils\win32\winresource.py", line 168, in GetResources
    hsrc = win32api.LoadLibraryEx(filename, 0, LOAD_LIBRARY_AS_DATAFILE)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\win32api.py", line 43, in LoadLibraryEx
    return _dll._LoadLibraryEx(fileName, 0, flags)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1264.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\pywintypes.py", line 37, in pywin32error
    raise error(exception.winerror, exception.function, exception.strerror)
win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryEx', 'Systemet kan inte komma åt filen')
</code>```

答:
I had exactly the same '(1920, 'LoadLibraryEx', 'System cannot access the file')'  problem with Pyinstaller and after much thrashing on the problem decided to clean up my Python environment.  So I uninstalled Python 3.6 and 3.7 then uninstalled PyCharm and Anaconda.

Then installed Python 3.8 and Pip 3.8 and then Pyinstaller and IT WORKED!!!  My hunch is the problem was a conflict between 3.6 and 3.7 but that is just a hunch.  I do think PyCharm and Anaconda are great products - - I'm just going to be WAY more careful about my Python environment from here on out.

[BTW Pyinstaller worked flawlessly first time on my Linux development box.]

Body:
Im trying to compile my python script to an exe so that i can send it to friends that can use with without having to install python, but im running into an issue and cant find a solution.

i found a similar issue at Pyinstaller win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryExW', 'System cannot access the file')

but cant post there except as a answer, i tried to add permissions and unhide the 'WindowsApps' folder but nothing seems to work.

Here is what cmd is giving me when running pyinstaller

and 'Systemet kan inte komma åt filen' is swedish for 'System cannot access the file'

100 INFO: PyInstaller: 3.5
101 INFO: Python: 3.7.4
101 INFO: Platform: Windows-10-10.0.18362-SP0
103 INFO: wrote C:\Users\Jonathan\Pictures\shimbot2\gui.spec
106 INFO: UPX is not available.
109 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Jonathan\\Pictures', 'C:\\Users\\Jonathan\\Pictures\\shimbot2']
110 INFO: checking Analysis
110 INFO: Building Analysis because Analysis-00.toc is non existent
111 INFO: Initializing module dependency graph...
116 INFO: Initializing module graph hooks...
119 INFO: Analyzing base_library.zip ...
4140 INFO: running Analysis Analysis-00.toc
Traceback (most recent call last):
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\pywintypes.py", line 35, in pywin32error
    yield
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\win32api.py", line 43, in LoadLibraryEx
    return _dll._LoadLibraryEx(fileName, 0, flags)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\core\cffi\_dll.py", line 26, in _LoadLibraryEx
    function_name='LoadLibraryEx')
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\core\cffi\_util.py", line 81, in __call__
    self._raise_error(function_name)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\core\cffi\_util.py", line 92, in _raise_error
    raise exception
OSError: [WinError 1920] Systemet kan inte komma åt filen

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1264.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1264.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Jonathan\Pictures\shimbot2\pyinstaller.exe\__main__.py", line 7, in <module>
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 844, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 791, in build
    exec(code, spec_namespace)
  File "C:\Users\Jonathan\Pictures\shimbot2\gui.spec", line 17, in <module>
    noarchive=False)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 243, in __init__
    self.__postinit__()
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
    self.assemble()
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\building\build_main.py", line 405, in assemble
    redirects=self.binding_redirects)[1:])
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\depend\bindepend.py", line 231, in Dependencies
    for ftocnm, fn in getAssemblyFiles(pth, manifest, redirects):
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\depend\bindepend.py", line 407, in getAssemblyFiles
    for assembly in getAssemblies(pth):
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\depend\bindepend.py", line 358, in getAssemblies
    res = GetManifestResources(pth)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\utils\win32\winmanifest.py", line 1005, in GetManifestResources
    return winresource.GetResources(filename, [RT_MANIFEST], names, languages)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\PyInstaller\utils\win32\winresource.py", line 168, in GetResources
    hsrc = win32api.LoadLibraryEx(filename, 0, LOAD_LIBRARY_AS_DATAFILE)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\win32api.py", line 43, in LoadLibraryEx
    return _dll._LoadLibraryEx(fileName, 0, flags)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1264.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "C:\Users\Jonathan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32ctypes\pywin32\pywintypes.py", line 37, in pywin32error
    raise error(exception.winerror, exception.function, exception.strerror)
win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryEx', 'Systemet kan inte komma åt filen')


来源: stackexchange

问:
internal/modules/cjs/loader.js:800 throw err
Executed yarn install in my project folder and got below error.

```<code>internal/modules/cjs/loader.js:800
throw err;
^
Error: Cannot find module 'ts-node/register'
Require stack:
- internal/preload
?[90m    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797
:15)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:690:27)?[39m
?[90m    at Module.require (internal/modules/cjs/loader.js:852:19)?[39m
?[90m    at Module._preloadModules (internal/modules/cjs/loader.js:1147:12)?[39m
?[90m    at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)?[39m
?[90m    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3
)?[39m
?[90m    at internal/main/run_main_module.js:7:1?[39m {
code: ?[32m'MODULE_NOT_FOUND'?[39m,
requireStack: [ ?[32m'internal/preload'?[39m ]
}
</code>```

Removed node_module, yarn.lock and node-cache. But no success.

This error is not project specific. If i run yarn, node or npm anywhere in my system I'm getting above error. Is my node and yarn package corrupted?

答:
Solved Issue by checking NODE_OPTIONS

Run echo %NODE_OPTIONS% and got ts-node/register.

So, to remove ts-node/register run setx NODE_OPTIONS ""

After this node,npm and yarn are working properly.

ContentLicense: CC BY-SA 4.0

Body:
Executed yarn install in my project folder and got below error.

internal/modules/cjs/loader.js:800
throw err;
^
Error: Cannot find module 'ts-node/register'
Require stack:
- internal/preload
?[90m    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797
:15)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:690:27)?[39m
?[90m    at Module.require (internal/modules/cjs/loader.js:852:19)?[39m
?[90m    at Module._preloadModules (internal/modules/cjs/loader.js:1147:12)?[39m
?[90m    at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)?[39m
?[90m    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3
)?[39m
?[90m    at internal/main/run_main_module.js:7:1?[39m {
code: ?[32m'MODULE_NOT_FOUND'?[39m,
requireStack: [ ?[32m'internal/preload'?[39m ]
}

Removed node_module, yarn.lock and node-cache. But no success.

This error is not project specific. If i run yarn, node or npm anywhere in my system I'm getting above error. Is my node and yarn package corrupted?


问:
How to combine multiple loss and accuracy during training in Keras?
With reference to the question, during training I am getting multiple losses and accuracies. For example,

```<code>Epoch 1/100
1382/1382 [==============================] - 694s 502ms/step - loss: 0.6798 - decoder_loss: 0.3399 - decoder_accuracy: 0.5770 - decoder_accuracy_1: 0.5770 - val_loss: 0.6606 - val_decoder_loss: 0.3373 - val_decoder_accuracy: 0.5783 - val_decoder_accuracy_1: 0.5783
</code>```

It's hard to understand and what I want is only loss, accuracy, validation_loss and validation_accuracy. Is there any way to merge them.

Another thing is my log file is getting bigger and bigger as the network print the loss/accuracy after each step as:

```<code>1/1382 [..............................] - ETA: 13:59 - loss: 0.7226 - decoder_loss: 0.3613 - decoder_accuracy: 0.5536 - decoder_accuracy_1: 0.5536
2/1382 [..............................] - ETA: 10:23 - loss: 0.7204 - decoder_loss: 0.3602 - decoder_accuracy: 0.5881 - decoder_accuracy_1: 0.5881
3/1382 [..............................] - ETA: 8:57 - loss: 0.7151 - decoder_loss: 0.3576 - decoder_accuracy: 0.5821 - decoder_accuracy_1: 0.5821
</code>```

Can I reduce it to output only when the epoch ends instead of each step?

答:
i assume you use the fit funciton of keras with a verbose of 1.
E.g.

```<code>model.fit(Xtrain, Ytrain, batch_size = 32, epochs = 100, verbose=1)
</code>```

You can change the verbose to 2 then you will get only one output per epoch. Alternatively you can turn the training progress output off if you set verbose to 0.
(Source: Keras API)
E.g.

```<code>model.fit(Xtrain, Ytrain, batch_size = 32, epochs = 5, verbose=2)
</code>```

Should give you an output like:

I hope this solves your problem. If not you might want to share a little bit of your code so we can help you futher.

EDIT1:
As for your question if you can influence your monitoring metrics: Yes you can, but I can only answer your question with assumptions because I don't have your code.
If you use keras for your model you should have used the "compile" funciton of keras somewhere. E.g

```<code>model.compile(optimizer=keras.optimizers.RMSprop(),  # Optimizer
          # Loss function to minimize
          loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
          # List of metrics to monitor
          metrics=["accuracy"])
</code>```

You can influence the metrics which are shown in your console if you change the metrics values to the values you want to see. (Source:Kearas API,Keras Metrics)

If you only want to see the loss, accuracy you can use the example above. The metrics val_... will be generated accordingly if you use a validation _split or validation_datat in your fit function. E.g.

```<code>history = model.fit(x_train, y_train,
                batch_size=64,
                epochs=3,
                # We pass some validation for
                # monitoring validation loss and metrics
                # at the end of each epoch
                validation_data=(x_val, y_val))
</code>```

If build you two examples to visualize my point
 Example 1 shows accuracy, loss, val_acc and val_loss

 Example 2 shows accuracy, loss,mae, val_acc, val_loss and val_mae

For completness here the link to the colab notebook, where you can see my code:Colab for Examples

I hope this helps to solve your quesion completly. If not let me know.

Body:
With reference to the question, during training I am getting multiple losses and accuracies. For example,

Epoch 1/100
1382/1382 [==============================] - 694s 502ms/step - loss: 0.6798 - decoder_loss: 0.3399 - decoder_accuracy: 0.5770 - decoder_accuracy_1: 0.5770 - val_loss: 0.6606 - val_decoder_loss: 0.3373 - val_decoder_accuracy: 0.5783 - val_decoder_accuracy_1: 0.5783

It's hard to understand and what I want is only loss, accuracy, validation_loss and validation_accuracy. Is there any way to merge them.

Another thing is my log file is getting bigger and bigger as the network print the loss/accuracy after each step as:

1/1382 [..............................] - ETA: 13:59 - loss: 0.7226 - decoder_loss: 0.3613 - decoder_accuracy: 0.5536 - decoder_accuracy_1: 0.5536
2/1382 [..............................] - ETA: 10:23 - loss: 0.7204 - decoder_loss: 0.3602 - decoder_accuracy: 0.5881 - decoder_accuracy_1: 0.5881
3/1382 [..............................] - ETA: 8:57 - loss: 0.7151 - decoder_loss: 0.3576 - decoder_accuracy: 0.5821 - decoder_accuracy_1: 0.5821

Can I reduce it to output only when the epoch ends instead of each step?

Body:
i assume you use the fit funciton of keras with a verbose of 1.
E.g.

model.fit(Xtrain, Ytrain, batch_size = 32, epochs = 100, verbose=1)

You can change the verbose to 2 then you will get only one output per epoch. Alternatively you can turn the training progress output off if you set verbose to 0.
(Source: Keras API)
E.g.

model.fit(Xtrain, Ytrain, batch_size = 32, epochs = 5, verbose=2)

Should give you an output like:

I hope this solves your problem. If not you might want to share a little bit of your code so we can help you futher.

EDIT1:
As for your question if you can influence your monitoring metrics: Yes you can, but I can only answer your question with assumptions because I don't have your code.
If you use keras for your model you should have used the "compile" funciton of keras somewhere. E.g

model.compile(optimizer=keras.optimizers.RMSprop(),  # Optimizer
          # Loss function to minimize
          loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
          # List of metrics to monitor
          metrics=["accuracy"])

You can influence the metrics which are shown in your console if you change the metrics values to the values you want to see. (Source:Kearas API,Keras Metrics)

If you only want to see the loss, accuracy you can use the example above. The metrics val_... will be generated accordingly if you use a validation _split or validation_datat in your fit function. E.g.

history = model.fit(x_train, y_train,
                batch_size=64,
                epochs=3,
                # We pass some validation for
                # monitoring validation loss and metrics
                # at the end of each epoch
                validation_data=(x_val, y_val))

If build you two examples to visualize my point
 Example 1 shows accuracy, loss, val_acc and val_loss

 Example 2 shows accuracy, loss,mae, val_acc, val_loss and val_mae

For completness here the link to the colab notebook, where you can see my code:Colab for Examples

I hope this helps to solve your quesion completly. If not let me know.


问:
Scala Builder a object recursively
Here is the situation

```<code>val input = "a:b:c:d:e"

def getTrait(primary: SomeTrait, secondary: SomeTrait): SomeTrait {
...
}

def convertTrait(name: String): SomeTrait {
...
}
</code>```

So what I want to do is to slide input in window of 2 and build SomeTrait based on that like this

```<code>val result = getTrait(convertTrait(a),convertTrait(b))
</code>```

and then use this result to build another result like this

```<code>val resul2 = getTrait(result, convertTrait(c))
</code>```

and so onn.......

Offcourse I wanna do it in some kind of recursion/for in scala but unable to find solution

Here is where I am

```<code>val listOfList = input.split(":").grouped(2).toList

private def builder(inputList: List[List[String]], primary: SomeTrait, secondary: SomeTrait): SomeTrait = {
    for {
      xs <- inputList
      fallback = if(xs.size == 1) providerFallBackChainBuilder(convertTrait(xs(0)), "noop") else providerFallBackChainBuilder(convertTrait(xs(1)), convertTrait(xs(0)))
    } yield fallback
    FallbackConfigProvider(primary, secondary)
  }
</code>```

I  somehow need to pass this fallback back to function .. I know this is not working and not best solution but can anyone guide me on how to dit better and correctly

答:
This should what you need.</p>

```<code>"a:b:c:d:e".split(":").iterator.map(convertTrait).reduce(getTrait)
</code>```

Title: Scala Builder a object recursively

Body:
Here is the situation

val input = "a:b:c:d:e"

def getTrait(primary: SomeTrait, secondary: SomeTrait): SomeTrait {
...
}

def convertTrait(name: String): SomeTrait {
...
}

So what I want to do is to slide input in window of 2 and build SomeTrait based on that like this

val result = getTrait(convertTrait(a),convertTrait(b))

and then use this result to build another result like this

val resul2 = getTrait(result, convertTrait(c))

and so onn.......

Offcourse I wanna do it in some kind of recursion/for in scala but unable to find solution

Here is where I am

val listOfList = input.split(":").grouped(2).toList

private def builder(inputList: List[List[String]], primary: SomeTrait, secondary: SomeTrait): SomeTrait = {
    for {
      xs <- inputList
      fallback = if(xs.size == 1) providerFallBackChainBuilder(convertTrait(xs(0)), "noop") else providerFallBackChainBuilder(convertTrait(xs(1)), convertTrait(xs(0)))
    } yield fallback
    FallbackConfigProvider(primary, secondary)
  }

I  somehow need to pass this fallback back to function .. I know this is not working and not best solution but can anyone guide me on how to dit better and correctly

Body:
This should what you need.

"a:b:c:d:e".split(":").iterator.map(convertTrait).reduce(getTrait)


问:
INTELIJ terminal only showing directory instead of running a command prompt
Sorry if it is a dumb question, but i was running my code perfectly and the terminal was reacting when i ran my program.

After turning my laptop off and on I cant seem to get it to show my SOP commands in the terminal. All i get is the directory of where my program is saved in.

答:
Because Terminal shows the command prompt in which you can write your commands.

If you run your code, you'll probably have a Run button around the Terminal button. Click on Run or Debug whichever button is showing and there you will see your output.

(You can optionally do the traditional javac filename.java and java classname inside the terminal to see your output too if you can't find the Run button, which I think will be somewhere near by)


问:
System.InvalidOperationException CrossThread using worker function
I'm dealing with a thread error using a worker in my function. I already checked about bindings and 'invoke'(?) but I'm quite new to C# and WPF and I don't really understand the way I should solve this. It seems that I'm calling of function from another which is not the "owner".

```<code>void myLongLastingFunction(0)
{
    line_list.SelectedIndex = 0; //ERROR CrossThread
    blablabla..
}

private void btnClick(object sender, RoutedEventArgs e)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.WorkerReportsProgress = true;
    worker.DoWork += worker_DoConvertOne;
    worker.ProgressChanged += worker_ProgressChanged;
    worker.RunWorkerAsync();
}

private void worker_DoConvertOne(object sender, DoWorkEventArgs e)
{
    var worker = sender as BackgroundWorker;
    //Processing
    myLongLastingFunction(0);

    //The progress bas is full...
    worker.ReportProgress(100, "Done Processing.");
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("Converting finished!");
    TestProgressBar.Value = 0;
}

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    TestProgressBar.Value = e.ProgressPercentage;
}
</code>```

I was inspired by this post.

Error appears when I'm calling myLongLastingFunction() which is crashing my app :

System.InvalidOperationException: 'Calling thread can't reach this object because a other thread is the owner'

Sorry for my translation which is probably faulse but as close to the original message as possible.
Have you got any idea ?

答:
Use the dispatcher:</p>

```<code>void myLongLastingFunction(0)
{
    Dispatcher.BeginInvoke((Action)(() => {
        line_list.SelectedIndex = 0;
    }));
}
</code>```

Body:
I'm dealing with a thread error using a worker in my function. I already checked about bindings and 'invoke'(?) but I'm quite new to C# and WPF and I don't really understand the way I should solve this. It seems that I'm calling of function from another which is not the "owner".

void myLongLastingFunction(0)
{
    line_list.SelectedIndex = 0; //ERROR CrossThread
    blablabla..
}

private void btnClick(object sender, RoutedEventArgs e)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.WorkerReportsProgress = true;
    worker.DoWork += worker_DoConvertOne;
    worker.ProgressChanged += worker_ProgressChanged;
    worker.RunWorkerAsync();
}

private void worker_DoConvertOne(object sender, DoWorkEventArgs e)
{
    var worker = sender as BackgroundWorker;
    //Processing
    myLongLastingFunction(0);

    //The progress bas is full...
    worker.ReportProgress(100, "Done Processing.");
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("Converting finished!");
    TestProgressBar.Value = 0;
}

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    TestProgressBar.Value = e.ProgressPercentage;
}

I was inspired by this post.

Error appears when I'm calling myLongLastingFunction() which is crashing my app :

System.InvalidOperationException: 'Calling thread can't reach this object because a other thread is the owner'

Sorry for my translation which is probably faulse but as close to the original message as possible.
Have you got any idea ?

Body:
Use the dispatcher:

void myLongLastingFunction(0)
{
    Dispatcher.BeginInvoke((Action)(() => {
        line_list.SelectedIndex = 0;
    }));
}


问:
How to verify the status of an EC2 instance launched from a newly created AMI?
How to check if an EC2 instance is up and running/one particular service is up or down using boto3. The instance is created from a newly created AMI. </p>

答:
While you ask specifically about boto3, there is a way to ensure some service is in ready state more AWS natively.

Move creation of your instance to CloudFormation template and define CreationPolicy, like described in AWS Blog post:
https://aws.amazon.com/blogs/devops/use-a-creationpolicy-to-wait-for-on-instance-configurations/

TL;DR: when the instance is launched, it will run a script which will check if whatever service you need is working, and then signal CloudFormation "all systems go". If it does not signal in time, instance is marked as CREATE_FAILED and deleted.


问:
Adding a separator line under custom tableview cell in UITableViewCell
I am trying to add a separator to my uitableview cell. i tried this.

```<code>let separator = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 8.0))
cell.contentView.addSubview(separator)
</code>```

But this adds the separator view on top of the cell, i need it to the bottom.

I also tried this way.

```<code>let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(view)
view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true
view.heightAnchor.constraint(equalToConstant: 8.0).isActive = true
view.topAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
</code>```

But this gives me no common ancestor error. and i don't want to use storyboard. i need it because i am using same cell at different places, somewhere i need the separator somewhere not. what should i do?

答:
Change constraint for this

```<code>view.topAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
</code>```

to

```<code>view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
</code>```

its better to create the line inside init of the custom cell and make it a property

```<code>let view = UIView()
</code>```

then mange its state from cellForRowAt

```<code>view.isHidden = true/false
</code>```

Body:
I am trying to add a separator to my uitableview cell. i tried this.

let separator = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 8.0))
cell.contentView.addSubview(separator)

But this adds the separator view on top of the cell, i need it to the bottom.

I also tried this way.

let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(view)
view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true
view.heightAnchor.constraint(equalToConstant: 8.0).isActive = true
view.topAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true

But this gives me no common ancestor error. and i don't want to use storyboard. i need it because i am using same cell at different places, somewhere i need the separator somewhere not. what should i do?

Body:
Change constraint for this

view.topAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true

to

view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true

its better to create the line inside init of the custom cell and make it a property

let view = UIView()

then mange its state from cellForRowAt

view.isHidden = true/false


问:
Generic type function with different return type
I'm running into an issue of knowledge right now and I'd appreciate any help you could offer. Here is my issue, I've got multiple function as such:

```<code>    fun read(key: Key, defaultValue: String): String? {
        return prefs.getString(key.name, defaultValue)
    }

    fun read(key: Key, defaultValue: Boolean): Boolean? {
        return prefs.getBoolean(key.name, defaultValue)
    }

    fun read(key: Key, defaultValue: Int): Int {
        return prefs.getInt(key.name, defaultValue)
    }
</code>```

instead of overloading the read function with different type I'd like to use something like this:

```<code>fun<T> read(key: Key, defaultValue: T): T? {
    return when(defaultValue){
        is String -> prefs.getString(key.name, defaultValue)
        is Boolean -> prefs.getBoolean(key.name, defaultValue)
        else -> throw IllegalArgumentException()
    }
}
</code>```

However the IDE doesn't let me because there is an issue with return type which isn't a generic Type, I know it's possible to do something like this but don't know how.
Could you give me a hand finshing the fun <T> ?

答:
As far as I am concerned, overloads are far better and clean approach, but If you are dead set doing it this way, then you can use unchecked casts

```<code>fun<T> read(key: Key, defaultValue: T): T? {
    return when(defaultValue){
        is String -> prefs.getString(key.name, defaultValue) as T
        is Boolean -> prefs.getBoolean(key.name, defaultValue) as T
        else -> throw IllegalArgumentException()
    }
}
</code>```

Body:
I'm running into an issue of knowledge right now and I'd appreciate any help you could offer. Here is my issue, I've got multiple function as such:

    fun read(key: Key, defaultValue: String): String? {
        return prefs.getString(key.name, defaultValue)
    }

    fun read(key: Key, defaultValue: Boolean): Boolean? {
        return prefs.getBoolean(key.name, defaultValue)
    }

    fun read(key: Key, defaultValue: Int): Int {
        return prefs.getInt(key.name, defaultValue)
    }

instead of overloading the read function with different type I'd like to use something like this:

fun<T> read(key: Key, defaultValue: T): T? {
    return when(defaultValue){
        is String -> prefs.getString(key.name, defaultValue)
        is Boolean -> prefs.getBoolean(key.name, defaultValue)
        else -> throw IllegalArgumentException()
    }
}

However the IDE doesn't let me because there is an issue with return type which isn't a generic Type, I know it's possible to do something like this but don't know how.
Could you give me a hand finshing the fun <T> ?

Body:
As far as I am concerned, overloads are far better and clean approach, but If you are dead set doing it this way, then you can use unchecked casts

fun<T> read(key: Key, defaultValue: T): T? {
    return when(defaultValue){
        is String -> prefs.getString(key.name, defaultValue) as T
        is Boolean -> prefs.getBoolean(key.name, defaultValue) as T
        else -> throw IllegalArgumentException()
    }
}


问:
How can I print_r an array from controller while an ajax process?
I am trying to debug my AJAX call to database.

But there is no way to see the data i am using. I have tried to do it inserting some Javascript:

I also tried to use print_r, but nothing happens.

Is there any way to see my variables? A developer tool for example, or any command i could use.

Thanks for your help.

```<code>function console_log( $data ){
    echo '<script>';
    echo 'console.log('. json_encode( $data ) .')';
    echo '</script>';
}
</code>```

This is my controller code:

```<code>public function searchEvents(){
        $request = Request::createFromGlobals();
        if($request->getMethod()=='POST') {
            $value = $request->request->get('searchBox');
            $em=$this->getDoctrine()->getManager();
            $searchFor = $request->request->get('value');
            $qb = $em->createQueryBuilder();
            //$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
            $query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
            $query->setParameter('value', '%'.$searchFor.'%');
            $eventos = $query->getResult();
            /*$qb->select('u')
                ->from('App:Evento','u')
                ->where(('u.title = '.$searchFor));
            $query = $qb->getQuery();
            $eventos = $query->getResult();*/
            $response = [];
            foreach($eventos as $evento){
                array_unshift($response,[
                    $evento->getTitle(),
                    $evento->getFecha()
                ]);
                print_r($response);
            }
            $respuesta = new JsonResponse();
            $respuesta->setData(
                array('response'=>'success',
                    'eventos'=>$response)
            );
        }
        return $respuesta;
}
</code>```

And my js code:

```<code>function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: value=2,
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}
</code>```

答:
I assume you use Symfony 4+ If this case you need to install Symfony Profiler and Var Dumper packages (https://symfony.com/doc/current/profiler.html - https://symfony.com/doc/current/components/var_dumper.html). When install that two bundle you need change print_r functions to dump function. After you do that profiler package record all your request. You can access profiler data to "_profiler" route (example: http://localhost:8000/_profiler/ or something like that).

Please notice that the browser will show you the direct link to profiler inside the headers of the request, here is an example:

Body:
I am trying to debug my AJAX call to database.

But there is no way to see the data i am using. I have tried to do it inserting some Javascript:

I also tried to use print_r, but nothing happens.

Is there any way to see my variables? A developer tool for example, or any command i could use.

Thanks for your help.

function console_log( $data ){
    echo '';
}

This is my controller code:

public function searchEvents(){
        $request = Request::createFromGlobals();
        if($request->getMethod()=='POST') {
            $value = $request->request->get('searchBox');
            $em=$this->getDoctrine()->getManager();
            $searchFor = $request->request->get('value');
            $qb = $em->createQueryBuilder();
            //$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
            $query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
            $query->setParameter('value', '%'.$searchFor.'%');
            $eventos = $query->getResult();
            /*$qb->select('u')
                ->from('App:Evento','u')
                ->where(('u.title = '.$searchFor));
            $query = $qb->getQuery();
            $eventos = $query->getResult();*/
            $response = [];
            foreach($eventos as $evento){
                array_unshift($response,[
                    $evento->getTitle(),
                    $evento->getFecha()
                ]);
                print_r($response);
            }
            $respuesta = new JsonResponse();
            $respuesta->setData(
                array('response'=>'success',
                    'eventos'=>$response)
            );
        }
        return $respuesta;
}

And my js code:

function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: value=2,
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}


问:
Modules : type problem in functor
I have a problem with types in the following code (some easy module functional graph implementation). It seems that types are living their own lives.

I have type t = NotaEdge | Edge of int*v*v implemented in module Edge, this type in module Graph becomes type edge = E.t. Everything seems fine to me, except fact i can't pattern match on it, cause the constructor Edge is still undefined in module Graph.

Exactly in function suc when i try to match with Edge(l,n,m): #Error: Unbound constructor Edge

Hope someone can present it nicely, thx in advance :)

```<code> module Vertex : Vertex with type label = int =

struct

  type t = NotaNode |  Node of int
  type label = int
  exception No of string
</code>```

...

```<code>module Edge : Edge  with type label = int and type v = Vertex.t =
struct

  type v = Vertex.t
  type t = NotaEdge | Edge of int*v*v
  type label = int

  exception No of string
</code>```

...

```<code>module Graph (E : Edge) (V : Vertex) : Graph with type vertex = V.t and type edge = E.t =
struct

  type vertex = V.t
  type edge = E.t
  type t = E.t list* V.t list

  let empty = ([],[])

 let rec suc (x:edge list) (v1:vertex) =
     match x with
         y::ys -> (match y with
   (*Error-->*)       Edge(l,n,m) -> if n == v1 then m::(suc ys v1) else suc ys v1
                     | _ -> [])
       |[] -> []

  let succ (t1:t) (v1:vertex) =
    match t1 with
        (x,_) -> suc x v1
</code>```

...

答:
Things are a bit messy here; Error is never defined, and what I presume to be a few typos.  It would be much more helpful if you gave code that compiled. Par it down, but syntactically correct. I can only make conjectures on the limited information and common pitfalls.

It would be very helpful to know the signatures to Vertex and Edge

If in the signature Edge the type t is defined the same as in the implementation of Edge that you give, then you can match the variant with E.Edge and E.NotaEdge. If the type t is abstract (the only information in the signature is type t), then you wont (and reasonably should not) be able to access the implementation or pattern match in that way. In this case the implementation is hidden behind the signature. This is usually fine (and intended) when dealing with functors since you can implement the module in any way that is necessary and convenient.

ContentLicense: CC BY-SA 3.0

Title: Modules : type problem in functor

Body:
I have a problem with types in the following code (some easy module functional graph implementation). It seems that types are living their own lives.

I have type t = NotaEdge | Edge of int*v*v implemented in module Edge, this type in module Graph becomes type edge = E.t. Everything seems fine to me, except fact i can't pattern match on it, cause the constructor Edge is still undefined in module Graph.

Exactly in function suc when i try to match with Edge(l,n,m): #Error: Unbound constructor Edge

Hope someone can present it nicely, thx in advance :)

 module Vertex : Vertex with type label = int =

struct

  type t = NotaNode |  Node of int
  type label = int
  exception No of string

...

module Edge : Edge  with type label = int and type v = Vertex.t =
struct

  type v = Vertex.t
  type t = NotaEdge | Edge of int*v*v
  type label = int

  exception No of string

...

module Graph (E : Edge) (V : Vertex) : Graph with type vertex = V.t and type edge = E.t =
struct

  type vertex = V.t
  type edge = E.t
  type t = E.t list* V.t list

  let empty = ([],[])

 let rec suc (x:edge list) (v1:vertex) =
     match x with
         y::ys -> (match y with
   (*Error-->*)       Edge(l,n,m) -> if n == v1 then m::(suc ys v1) else suc ys v1
                     | _ -> [])
       |[] -> []

  let succ (t1:t) (v1:vertex) =
    match t1 with
        (x,_) -> suc x v1

...


问:
TextField either phone number or Email format validation swift?
I having one text field for forgot password ,here user enter either mobile number or email then we send OTP to that.

I am trying to validations for that text field with my code but it is not working, any one give some idea on that please find my code with following.

It needs to valid for either mailid or Phone number format.

```<code>if emaiTF.text == "" {
            print("Enter either valid phone or email")
        }else if let validphone = emaiTF.text, validphone.isValidPhone() || validphone.isValidEmail() {
            print("Enter either valid phone or email")
        }else{
            forGotPasswordApi()
        }
</code>```

my validation methods like following.

```<code>extension String {
    func isValidEmail() -> Bool {
        // here, `try!` will always succeed because the pattern is valid
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }

    // vrify Valid PhoneNumber or Not
    func isValidPhone() -> Bool {

        let phoneRegex = "^[0-9]{10}$";
        let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phoneRegex)
        return valid
    }
}
</code>```

答:
Phone Number Validation</p>

```<code> func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let aSet = NSCharacterSet(charactersIn:"0123456789").inverted

    let compSepByCharInSet = string.components(separatedBy: aSet)

    let numberFiltered = compSepByCharInSet.joined(separator: "")

    guard let text = textField.text else { return true }

    let count = text.count + string.count - range.length

    return string == numberFiltered && count <= 10

  }
</code>```

Body:
I having one text field for forgot password ,here user enter either mobile number or email then we send OTP to that.

I am trying to validations for that text field with my code but it is not working, any one give some idea on that please find my code with following.

It needs to valid for either mailid or Phone number format.

if emaiTF.text == "" {
            print("Enter either valid phone or email")
        }else if let validphone = emaiTF.text, validphone.isValidPhone() || validphone.isValidEmail() {
            print("Enter either valid phone or email")
        }else{
            forGotPasswordApi()
        }

my validation methods like following.

extension String {
    func isValidEmail() -> Bool {
        // here, `try!` will always succeed because the pattern is valid
        let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
        return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
    }

    // vrify Valid PhoneNumber or Not
    func isValidPhone() -> Bool {

        let phoneRegex = "^[0-9]{10}$";
        let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phoneRegex)
        return valid
    }
}

Body:
Phone Number Validation

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let aSet = NSCharacterSet(charactersIn:"0123456789").inverted

    let compSepByCharInSet = string.components(separatedBy: aSet)

    let numberFiltered = compSepByCharInSet.joined(separator: "")

    guard let text = textField.text else { return true }

    let count = text.count + string.count - range.length

    return string == numberFiltered && count <= 10

  }


问:
How can I add white space to the bottom of a page with JavaScript?
I know it's a really specific question, but I need to add 56px of white space to the bottom of a page using JavaScript - like the actual page is compressed so uses less screen space. Here are some images showing what I want to do (the white space is hard to see because it blends in with the background, but you can still see the actual website is smaller):

I've tried using JavaScript to add in CSS to the page - using some different pieces of code for footers, but whatever I do, either the bar covers some of the page rather than moving the rest up or it just stays at the bottom rather than sticking when the user scrolls. For example this code:

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: white;
   text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui </p>

<div class="footer">
.
</div></code>```

gives a rough idea of what I want, but unfortunately the website content goes behind it - for example when scrolling the text goes behind it. It depends on the size of the page on your screen, but on my display when I stop the example text at "qui" (like I have done in the example) the bottom of the "q"s are cut off:

I'd also like scrollling content to stop at the top of the white space rather than the bottom of the page. Is this possible?

答:
using jquery sticky footer

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() {

       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");

       positionFooter();

       function positionFooter() {

                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";

               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }

       }

       $(window)
               .scroll(positionFooter)
               .resize(positionFooter)

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#footer { background-color:#cccc;}</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc placerat, risus ut pretium pellentesque, quam neque finibus sapien, ac placerat ligula nibh et elit. Nunc malesuada dictum nunc. Nam fringilla, est eget sodales semper, nisi nibh aliquet sapien, vel viverra ex augue nec nulla. Sed et neque at ante aliquet ornare. Donec faucibus lorem nisl, non pellentesque leo vestibulum ac. Vestibulum et dapibus lorem. Proin tristique orci vel purus placerat, vitae porta dolor accumsan. Praesent ornare porta dolor id aliquet. Vivamus id rhoncus diam. Nulla a erat in nisl ullamcorper faucibus. Maecenas aliquam nulla quis arcu fringilla, sed convallis risus fermentum. Mauris a ex varius nulla porta euismod id at nisi. Etiam non dolor ac lacus luctus imperdiet. Nunc facilisis urna elit, ut dictum dolor condimentum in.

    Footer

```

Body:
I know it's a really specific question, but I need to add 56px of white space to the bottom of a page using JavaScript - like the actual page is compressed so uses less screen space. Here are some images showing what I want to do (the white space is hard to see because it blends in with the background, but you can still see the actual website is smaller):

I've tried using JavaScript to add in CSS to the page - using some different pieces of code for footers, but whatever I do, either the bar covers some of the page rather than moving the rest up or it just stays at the bottom rather than sticking when the user scrolls. For example this code:

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: white;
   text-align: center;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui

.

gives a rough idea of what I want, but unfortunately the website content goes behind it - for example when scrolling the text goes behind it. It depends on the size of the page on your screen, but on my display when I stop the example text at "qui" (like I have done in the example) the bottom of the "q"s are cut off:

I'd also like scrollling content to stop at the top of the white space rather than the bottom of the page. Is this possible?

Body:
using jquery sticky footer

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() {

       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");

       positionFooter();

       function positionFooter() {

                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";

               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }

       }

       $(window)
               .scroll(positionFooter)
               .resize(positionFooter)

});

#footer { background-color:#cccc;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc placerat, risus ut pretium pellentesque, quam neque finibus sapien, ac placerat ligula nibh et elit. Nunc malesuada dictum nunc. Nam fringilla, est eget sodales semper, nisi nibh aliquet sapien, vel viverra ex augue nec nulla. Sed et neque at ante aliquet ornare. Donec faucibus lorem nisl, non pellentesque leo vestibulum ac. Vestibulum et dapibus lorem. Proin tristique orci vel purus placerat, vitae porta dolor accumsan. Praesent ornare porta dolor id aliquet. Vivamus id rhoncus diam. Nulla a erat in nisl ullamcorper faucibus. Maecenas aliquam nulla quis arcu fringilla, sed convallis risus fermentum. Mauris a ex varius nulla porta euismod id at nisi. Etiam non dolor ac lacus luctus imperdiet. Nunc facilisis urna elit, ut dictum dolor condimentum in.</div>

<div id="footer">
    Footer
</div>


问:
Change color of of menu drawer hamburger icon in Android
I would like to change the icon color from of the hamburger icon. I tried a lots things and nothing worked. Here my XML:

```<code><androidx.appcompat.widget.Toolbar
 android:layout_width="match_parent"
 android:layout_height="?attr/actionBarSize"
 android:background="@color/colorPrimary"
 app:titleTextColor="@color/colorPrimaryDark"
 android:id="@+id/toolbar"
 android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
 app:popupTheme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
 android:elevation="4dp"/>
</code>```

In styles.xml I have

```

答:
Looks like you are using AppCompat. Please create this or similar style:

```<code><style name="DrawerArrowStyle" parent="@style/Widget.AppCompat.DrawerArrowToggle">
    <item name="color">#D81B60</item>
</style>
</code>```

Then use it in your theme:

```<code><item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</code>```

Body:
I would like to change the icon color from of the hamburger icon. I tried a lots things and nothing worked. Here my XML:

<androidx.appcompat.widget.Toolbar
 android:layout_width="match_parent"
 android:layout_height="?attr/actionBarSize"
 android:background="@color/colorPrimary"
 app:titleTextColor="@color/colorPrimaryDark"
 android:id="@+id/toolbar"
 android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
 app:popupTheme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
 android:elevation="4dp"/>

In styles.xml I have

Body:
Looks like you are using AppCompat. Please create this or similar style:

<style name="DrawerArrowStyle" parent="@style/Widget.AppCompat.DrawerArrowToggle">
    <item name="color">#D81B60</item>
</style>

Then use it in your theme:

<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>


问:
Merge two objects List in Java
How to merge two user list, if user is common merge its attribute.

I have two user lists, getting first list from DB and second from web service, if their firstname and lastname are same then user merge attribute and return combined list.

```<code>import java.util.List;
import java.util.Objects;

 class User {
     String firstName;
     String lastName;
     Integer count;
     Integer marks;
     String status;

     @Override
     public boolean equals(Object o) {
         if (this == o) return true;
         if (!(o instanceof User)) return false;
         User user = (User) o;
         return Objects.equals(firstName, user.firstName) &&
                 Objects.equals(lastName, user.lastName);
     }

     @Override
     public int hashCode() {
         return Objects.hash(firstName, lastName);
     }

    //constructor getter setter....

 }

 public class MainTest {

     public static void main(String[] args) {

         List<User> source1 = List.of(new User("A", "A", 1, 0, null),
                 new User("B", "B", 2, 0, null),
                 new User("C", "C", 3, 0, null));

         List<User> source2 = List.of(new User("A", "A", 0, 10, "FAIL"),
                 new User("B", "B", 0, 20, "FAIL"),
                 new User("D", "D", 0, 30, "PASS"));

         List<User> combinedExpectedList = List.of(new User("A", "A", 1, 10, "FAIL"),
                 new User("B", "B", 2, 20, "FAIL"),
                 new User("C", "C", 3, 0, null),
                 new User("D", "D", 0, 30, "PASS"));

         //List<User> userList3= Stream.concat(source1.stream(), source2.stream()).distinct().collect(Collectors.toList());//Adding 4 records but marks and status not copied
         //BeanUtils.copyProperties(model2, model1); - can't user don't have library

         for (User t : source2) {
             for (User s : source1) {
                 if (t.getFirstName().equals(s.getFirstName()) && t.getLastName().equals(s.getLastName())) {
                     t.setCount(s.getCount());
                 }
             }
         }// Not adding record with firstName=C and LastName=C

         System.out.println(combinedExpectedList.equals(source2));
     }
 }
</code>```

答:
Similar to this answer but here 'User' within source list remains unchanged:

List<User> values = new ArrayList<>(Stream.concat(source1.stream(), source2.stream())
        .collect(Collectors.toMap(e -> e.firstName + e.lastName, Function.identity(),
                (User u1, User u2) ->
                        new User(u1.firstName, u1.lastName, u1.count,
                                (u1.marks == 0) ? u2.marks : u1.marks,
                                (u1.status == null) ? u2.status : u1.status
                        )
        )).values());
```

Title: Merge two objects List in Java

Body:
How to merge two user list, if user is common merge its attribute.

I have two user lists, getting first list from DB and second from web service, if their firstname and lastname are same then user merge attribute and return combined list.

import java.util.List;
import java.util.Objects;

 class User {
     String firstName;
     String lastName;
     Integer count;
     Integer marks;
     String status;

     @Override
     public boolean equals(Object o) {
         if (this == o) return true;
         if (!(o instanceof User)) return false;
         User user = (User) o;
         return Objects.equals(firstName, user.firstName) &&
                 Objects.equals(lastName, user.lastName);
     }

     @Override
     public int hashCode() {
         return Objects.hash(firstName, lastName);
     }

    //constructor getter setter....

 }

 public class MainTest {

     public static void main(String[] args) {

         List<User> source1 = List.of(new User("A", "A", 1, 0, null),
                 new User("B", "B", 2, 0, null),
                 new User("C", "C", 3, 0, null));

         List<User> source2 = List.of(new User("A", "A", 0, 10, "FAIL"),
                 new User("B", "B", 0, 20, "FAIL"),
                 new User("D", "D", 0, 30, "PASS"));

         List<User> combinedExpectedList = List.of(new User("A", "A", 1, 10, "FAIL"),
                 new User("B", "B", 2, 20, "FAIL"),
                 new User("C", "C", 3, 0, null),
                 new User("D", "D", 0, 30, "PASS"));

         //List<User> userList3= Stream.concat(source1.stream(), source2.stream()).distinct().collect(Collectors.toList());//Adding 4 records but marks and status not copied
         //BeanUtils.copyProperties(model2, model1); - can't user don't have library

         for (User t : source2) {
             for (User s : source1) {
                 if (t.getFirstName().equals(s.getFirstName()) && t.getLastName().equals(s.getLastName())) {
                     t.setCount(s.getCount());
                 }
             }
         }// Not adding record with firstName=C and LastName=C

         System.out.println(combinedExpectedList.equals(source2));
     }
 }


问:
Assigning different buttons click events to the same function with a parameter dynamically
I've faced with the problem and been trying to solve it for almost an hour. I'm sharing this just in case anyone may face with the same problem. To explain the question and answer more clearly here is an example:

1) Let's say you create some button objects dynamically and add pile them up in a List:

```<code>    private void CreateButtons(int length)
    {
        for (int i = 0; i < length; i++)
        {
            var newButton = Instantiate(buttonPrefab);

            buttonList.Add(newButton);
        }
    }
</code>```

2) Then you want to assign same function to different buttons but with different parameters:

Here is the assigned method:

```<code>    private void Test(int a)
    {
        print(a);
    }
</code>```

And here is the assigning loop:

```<code>    private void AssignClickEvents()
    {
        for (int i = 0; i < buttonList.Count; i++)
        {
            buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(i); });
        }
    }
</code>```

The problem with the above code is that when a button is clicked it won't give you 0,1,2... etc. All buttons will give you the same value which is last assigned value of loop parameter 'i'. Check answer for solution:

答:
I don't know the exact reason behind this but to get things work you need to use a local variable for function parameter. Here is the code:

```<code>    private void AssignClickEvents()
    {
        for (int i = 0; i < buttonList.Count; i++)
        {
            int a = i;
            buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(a); });
        }
    }
</code>```

I hope it helps!

Body:
I've faced with the problem and been trying to solve it for almost an hour. I'm sharing this just in case anyone may face with the same problem. To explain the question and answer more clearly here is an example:

1) Let's say you create some button objects dynamically and add pile them up in a List:

    private void CreateButtons(int length)
    {
        for (int i = 0; i < length; i++)
        {
            var newButton = Instantiate(buttonPrefab);

            buttonList.Add(newButton);
        }
    }

2) Then you want to assign same function to different buttons but with different parameters:

Here is the assigned method:

    private void Test(int a)
    {
        print(a);
    }

And here is the assigning loop:

    private void AssignClickEvents()
    {
        for (int i = 0; i < buttonList.Count; i++)
        {
            buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(i); });
        }
    }

The problem with the above code is that when a button is clicked it won't give you 0,1,2... etc. All buttons will give you the same value which is last assigned value of loop parameter 'i'. Check answer for solution:

Body:
I don't know the exact reason behind this but to get things work you need to use a local variable for function parameter. Here is the code:

    private void AssignClickEvents()
    {
        for (int i = 0; i < buttonList.Count; i++)
        {
            int a = i;
            buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(a); });
        }
    }

I hope it helps!


问:
SalesForce.com: Retrieve custom fields via PHP
I have a simple custom contact object (with API name Contact__c) that I've created in my SalesForce DE site that has a single field (for testing connectivity) of Full_Name__c.

I am then trying to retrieve all of the contacts, specifically this field via PHP:

```<code>try {
  $mySforceConnection = new SforcePartnerClient();
  $mySoapClient       = $mySforceConnection->createConnection(API_PATH . '/soapclient/partner.wsdl');
  $mylogin            = $mySforceConnection->login(API_USER, API_PASS . API_SECURITY_TOKEN);

  $query = 'SELECT C.Id, C.Full_Name__c
          FROM Contact__c C';
  $result = $mySforceConnection->query($query);
  $sObject = new SObject($result->records[0]);
  print_r($sObject);
} catch(Exception $e) {
  print_r($e);
}
</code>```

I've downloaded the latest partner.wdsl (although as a partner WSDL, it is loosely typed and does not need to be downloaded with the creation/addition of custom objects and/or updated fields, correct?).  I've verified that the user can connect and see the custom fields via the ForceExplorer.  But when I run the above code, it connects but returns just the following:

```<code>SObject Object ( [type] => Contact__c [fields] => [Id] => a )
</code>```

I am not getting any errors, invalid field error, etc, but for the life of me can't figure out why this isn't working.

I saw this example here, but it seems to be specific to Enterprise vs Partner, and the need to download the latest enterprise.wsdl every-time you change custom fields.

Any pointers?

答:
Figured it out I believe, the problem related to how I was parsing the data that was being returned.  Instead of feeding the returned data into an SObject, I am now just accessing it directly:</p>

```<code>try {
  $mySforceConnection = new SforcePartnerClient();
  $mySoapClient       = $mySforceConnection->createConnection(API_PATH . '/soapclient/partner.wsdl');
  $mylogin            = $mySforceConnection->login(API_USER, API_PASS . API_SECURITY_TOKEN);

  $query = 'SELECT C.Id, C.Full_Name__c
            FROM Contact__c C';
  $result = $mySforceConnection->query($query);

  for($i = 0; $i < count($result->records); $i++) {
    print_r($result->records[$i]->fields->Full_Name__c);
  }
} catch(Exception $e) {
  print_r($e);
}
</code>```

Body:
I have a simple custom contact object (with API name Contact__c) that I've created in my SalesForce DE site that has a single field (for testing connectivity) of Full_Name__c.

I am then trying to retrieve all of the contacts, specifically this field via PHP:

try {
  $mySforceConnection = new SforcePartnerClient();
  $mySoapClient       = $mySforceConnection->createConnection(API_PATH . '/soapclient/partner.wsdl');
  $mylogin            = $mySforceConnection->login(API_USER, API_PASS . API_SECURITY_TOKEN);

  $query = 'SELECT C.Id, C.Full_Name__c
          FROM Contact__c C';
  $result = $mySforceConnection->query($query);
  $sObject = new SObject($result->records[0]);
  print_r($sObject);
} catch(Exception $e) {
  print_r($e);
}

I've downloaded the latest partner.wdsl (although as a partner WSDL, it is loosely typed and does not need to be downloaded with the creation/addition of custom objects and/or updated fields, correct?).  I've verified that the user can connect and see the custom fields via the ForceExplorer.  But when I run the above code, it connects but returns just the following:

SObject Object ( [type] => Contact__c [fields] => [Id] => a )

I am not getting any errors, invalid field error, etc, but for the life of me can't figure out why this isn't working.

I saw this example here, but it seems to be specific to Enterprise vs Partner, and the need to download the latest enterprise.wsdl every-time you change custom fields.

Any pointers?

Body:
Figured it out I believe, the problem related to how I was parsing the data that was being returned.  Instead of feeding the returned data into an SObject, I am now just accessing it directly:

try {
  $mySforceConnection = new SforcePartnerClient();
  $mySoapClient       = $mySforceConnection->createConnection(API_PATH . '/soapclient/partner.wsdl');
  $mylogin            = $mySforceConnection->login(API_USER, API_PASS . API_SECURITY_TOKEN);

  $query = 'SELECT C.Id, C.Full_Name__c
            FROM Contact__c C';
  $result = $mySforceConnection->query($query);

  for($i = 0; $i < count($result->records); $i++) {
    print_r($result->records[$i]->fields->Full_Name__c);
  }
} catch(Exception $e) {
  print_r($e);
}


问:
Submit HTML forms that contain dynamic IDs
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with id="surveyImage13"

```<code> <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
    <div class="row">
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...
            <div class="row" style="margin-bottom: 5%;">
                <div class="col-xl-2 col-lg-3 col-md-3">
                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
                </div>
            </div>
     </form>
</code>```

Form with ID="surveyImage18"

```<code><form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
      <div class="row">
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

            </div>
        </div>

    <div class="row" style="margin-bottom: 5%;">
        <div class="col-xl-2 col-lg-3 col-md-3">
             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
        </div>
    </div>
</form>
</code>```

AJAX call

```<code><script type="text/javascript">
 $("#surveyImage13").validate({
                    rules: {
                         'responses[]': {
                            required:true
                        }
                    },
                     // change name of error class that is assigned to input fields
    errorClass: 'error_validate',

    errorPlacement: function (label, element) {

        // default
        if (element.is(':radio')) {
            label.insertAfter(element.parent('.form-check-inline'));
        }
        else {
            label.insertAfter(element);
        }
    }

     });
</script>

<script type="text/javascript">

     $("#surveyImage13").submit(function(e) {
        e.preventDefault();

        var route=$('#surveyImage13').attr('action');
        var pivot_id = $("#questionnaire_pivot_id").val();

        // Get values of checked checkboxes
        var responses = $('.form-check-inline input').filter(':checked').map(function() {
          return this.value;
        }).get();

     var isFormValid = $("#surveyImage13").valid();

    if(isFormValid){

        $.ajax({
          type: "POST",
          url: route,
          data: {'responses': responses, 'pivot_id': pivot_id},
          success: function(response){

            $("#surveyImageForm").css("display", "none");
            $("#surveyImageAjax").css("display", "block");

            $('#SurveyTableAjaxColumn1').append(response[1]);
            $('#SurveyTableAjaxColumn2').append(response[0]);
          },
          error: function(){
            console.log('Error');
          }
        })
        }
     });

</script>
</code>```

答:
Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.

```<code><form id="surveyImage13">...</form>
</code>```

```<code><form id="surveyImage18">...</form>
</code>```

```<code>$("#surveyImage").submit...
</code>```

I think you may be able to resolve the issue by using a different query selector string.

```<code>$('#surveyImage13 #surveyImage18').submit...
</code>```

or...

```<code>$('form[id^="surveyImage"]').submit...
</code>```

Body:
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with id="surveyImage13"

 <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">

            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...

                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>

     </form>

Form with ID="surveyImage18"

<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">

            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>

</form>

AJAX call

Body:
Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.

<form id="surveyImage13">...</form>

<form id="surveyImage18">...</form>

$("#surveyImage").submit...

I think you may be able to resolve the issue by using a different query selector string.

$('#surveyImage13 #surveyImage18').submit...

or...

$('form[id^="surveyImage"]').submit...


问:
How to listen for a zoom level change in Here Maps
I'd like to run some code when the zoom level changes on a map but I'm having a hard time figuring out how to listen for the change.

I've tried variations of the following without any luck:

```<code>map.addEventListener("zoomLevel",function(){...

map.addObserver("zoomLevel",function(){...
</code>```

答:
```<code>map.addEventListener('mapviewchange', function () {

});
</code>```

Body:
I'd like to run some code when the zoom level changes on a map but I'm having a hard time figuring out how to listen for the change.

I've tried variations of the following without any luck:

map.addEventListener("zoomLevel",function(){...

map.addObserver("zoomLevel",function(){...


问:
When is casting Context to Activity allowed?
In a showAlret(String message, Context ctx) method of an alert Dialog class, I am trying to get a reference to TextView in the dialog's layout XML:

```<code>TextView tv = (TextView)((MyActivity)ctx).findViewById(R.id.tv_about);
</code>```

Not before calling inflate() of course:

```<code>LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.aboutdialog, null);
</code>```

The problem is that this call returns tv as null.

Since the code compiles without any warnings, I am assuming that this is due to "illegal" casting of Context to MyActivity.

I have encountered quite a few cases in which casting Context to Activity is the only thing that really works, so why doesn't this work in this case?

When does casting Context to Activity make sense?

What are the "unspoken rules" in this regard?

答:
No it isn't otherwise you would have exception.
Are you sure that your Activity hs loaded the TextView from xml at the moment you try to get it?</p>

Body:
In a showAlret(String message, Context ctx) method of an alert Dialog class, I am trying to get a reference to TextView in the dialog's layout XML:

TextView tv = (TextView)((MyActivity)ctx).findViewById(R.id.tv_about);

Not before calling inflate() of course:

LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.aboutdialog, null);

The problem is that this call returns tv as null.

Since the code compiles without any warnings, I am assuming that this is due to "illegal" casting of Context to MyActivity.

I have encountered quite a few cases in which casting Context to Activity is the only thing that really works, so why doesn't this work in this case?

When does casting Context to Activity make sense?

What are the "unspoken rules" in this regard?


问:
Unknown Publisher issue with installer(exe/msi) build with visual studio 2019
I'm using Visual Studio 2019 to build "Installers(msi/exe)" using "Setup Wizard".
When i'm trying to run setup.exe or msi installer, the application "publisher" is being reported as "Unknown".

I've gone through some references and found that the setup.exe needs to be digitally signed with the certificate. So, i've digitally signed the installers(exe/msi) with this reference How do I create a self-signed certificate for code signing on Windows?

Now, when i try to run setup.exe locally, the application "publisher" is reported as "My CA" instead of "Unknown", but if i run the same setup.exe on another system/computer application "publisher" is reported as "Unknown".
Please provide any suggestions on fixing this "Unknown Publisher" issue

答:
You need an official code signing certificate for be "known". I do not know if there are vendors which provide it for free, I don't think so. When you are using a self-signed cert, you have to install the cert (including the whole tree of the cert chain) in "trusted root certification authorities" on all machines where you plan to install your setup.msi.

There are two types of certs:

Extended Validation (EV) Code Signing (very expensive, more secure)

Code Signing (expensive but normally enough for private / small companies)


问:
How to truncate the time on a datetime object?
What is a classy way to way truncate a python datetime object?

In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0.

I would like the output to also be a datetime object, not a string.

答:
Here is yet another way which fits in one line but is not particularly elegant:</p>

```<code>dt = datetime.datetime.fromordinal(datetime.date.today().toordinal())
</code>```

Body:
Here is yet another way which fits in one line but is not particularly elegant:

dt = datetime.datetime.fromordinal(datetime.date.today().toordinal())


问:
IllegalArgumentException: Could not locate named parameter
I pass a Map as parameter of the following method:

```<code>    public List<User> getByParameterOrAll(Map<String, String> paramsMap) {
    String email = null;
    String emailValue = null;
    String phone = null;
    String phoneValue = null;

    Iterator<Map.Entry<String, String>> entries = paramsMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        if (entry.getKey().equals("email")){
            email = entry.getKey();
            emailValue = entry.getValue();
        } else if (entry.getKey().equals("phone")){
            phone = entry.getKey();
            phoneValue = entry.getValue();
        }
    }

    List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
            setParameter(emailValue, email).
            setParameter(phoneValue, phone).
            getResultList();
    return users;
}
</code>```

And I catch for the line    "setParameter(emailValue, email)"

```<code>java.lang.IllegalArgumentException: Could not locate named parameter [gmail@gmail.com], expecting one of [phoneValue, emailValue]
</code>```

I attach the screen of my test

答:
You should correct your query in the following way (see the documentation) :

List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
            setParameter("emailValue", email).
            setParameter("phoneValue", phone).
            getResultList();
```

Body:
I pass a Map as parameter of the following method:

    public List<User> getByParameterOrAll(Map<String, String> paramsMap) {
    String email = null;
    String emailValue = null;
    String phone = null;
    String phoneValue = null;

    Iterator<Map.Entry<String, String>> entries = paramsMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        if (entry.getKey().equals("email")){
            email = entry.getKey();
            emailValue = entry.getValue();
        } else if (entry.getKey().equals("phone")){
            phone = entry.getKey();
            phoneValue = entry.getValue();
        }
    }

    List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
            setParameter(emailValue, email).
            setParameter(phoneValue, phone).
            getResultList();
    return users;
}

And I catch for the line    "setParameter(emailValue, email)"

java.lang.IllegalArgumentException: Could not locate named parameter [gmail@gmail.com], expecting one of [phoneValue, emailValue]

I attach the screen of my test


问:
CPP how to escape a quotation mark
I'm in the process of making code from 1991 work on Ubuntu 19.

I've got this file I need to run through CPP where I am forced to use the -traditional option.

```<code>#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6
Trade types = "+ITEM_WEAPON+ITEM_FIREWEAPON+"
</code>```

I want the line to become

```<code>Trade types = "+5+6+"
</code>```

This worked just fine in 1991-1997 ;-) It seems cpp for obvious reasons no longer parse between quotation marks.

I've tried to escape the quotes using the backslash character e.g.

```<code>Trade types = \""+ITEM_WEAPON+ITEM_FIREWEAPON+\""
</code>```

But still haven't found a good solution.

For clarity this is not a C program, instead we simply used cpp to expand various macros into a structured text file which was later run through a parser.

The closest I have come (with -traditional flag) to something that almost works is this:

```<code>#define WI 1
#define WJ 2

#define T(a,b) Trade types = "+a+b+"
T(1,2)
T(WI,WJ)
</code>```

Which outputs:

```<code>Trade types = "+1+2+"
Trade types = "+WI+WJ+"
</code>```

So the pre-processor does substitute the arguments between the quotes but does not expand the parametized macro.

答:
#include <iostream>
#include <string>

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

#define STRINGIFY_HELPER(x) #x
#define STRINGIFY(x) STRINGIFY_HELPER(x)

int main()
{
    std::string types = "+" STRINGIFY(ITEM_WEAPON) "+" STRINGIFY(ITEM_FIREWEAPON) "+";
    std::cout << types << '\n';
    return 0;
}
```

https://wandbox.org/permlink/R5sLKvGhcnL9Jgyj

Title: CPP how to escape a quotation mark

Body:
I'm in the process of making code from 1991 work on Ubuntu 19.

I've got this file I need to run through CPP where I am forced to use the -traditional option.

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6
Trade types = "+ITEM_WEAPON+ITEM_FIREWEAPON+"

I want the line to become

Trade types = "+5+6+"

This worked just fine in 1991-1997 ;-) It seems cpp for obvious reasons no longer parse between quotation marks.

I've tried to escape the quotes using the backslash character e.g.

Trade types = \""+ITEM_WEAPON+ITEM_FIREWEAPON+\""

But still haven't found a good solution.

For clarity this is not a C program, instead we simply used cpp to expand various macros into a structured text file which was later run through a parser.

The closest I have come (with -traditional flag) to something that almost works is this:

#define WI 1
#define WJ 2

#define T(a,b) Trade types = "+a+b+"
T(1,2)
T(WI,WJ)

Which outputs:

Trade types = "+1+2+"
Trade types = "+WI+WJ+"

So the pre-processor does substitute the arguments between the quotes but does not expand the parametized macro.

Body:
#include <iostream>
#include <string>

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

#define STRINGIFY_HELPER(x) #x
#define STRINGIFY(x) STRINGIFY_HELPER(x)

int main()
{
    std::string types = "+" STRINGIFY(ITEM_WEAPON) "+" STRINGIFY(ITEM_FIREWEAPON) "+";
    std::cout << types << '\n';
    return 0;
}

https://wandbox.org/permlink/R5sLKvGhcnL9Jgyj


问:
The toggle in the script isn't working for me
I'm using this code that I found online, but it's not working completely the way I want it to.

Basically I am wanting check boxes to hide divs based on the users selection.
I am building an allergens advice page for a restaurant. When a guest selects the allergens they have I want it to hide the dishes that they cannot have.

The above code works perfectly if the guest has one allergen. It hides the div. If they select more than one then the box will reappear.

$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="selectt Eggs Gluten">
    <strong>Dough Balls</strong><br/>
    Cheese dough balls served with chipotle butter.
</div>
<ul>
    <li>
        <input type="checkbox" id="checkboxThree" value="Eggs">
        <label for="checkboxThree"> Eggs</label>
    </li>
</ul></code>```

I'm guessing it's doing it because the code is toggling, but I don't know of any other code to prevent that.
Your help would be greatly appreciated.

答:
I just copied further code from the link

What is happening here is just checkbox from ks-cboxtags class will be affected so any other checkbox will not have this functionality.

when you click on this it will displays div and if its selected div will be hide.

check below snippet for more details.

$(document).ready(function() {
    $(".test").click("test"); //ignore this

    $(".ks-cboxtags input").click(function() {
        $("."+$(this).val()).show();
        $(".ks-cboxtags input:checked").each(function() {
            $("."+$(this).val()).hide();
        });
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<main class="inline-block-center">
  <div class="selectt Gluten" style="display: block;">
    <strong style="font-size: 18px;">MEXICAN POPPADOMS</strong><br> Crispy blue corn tortillas with roasted tomato salsa, habanero & pepper salsa, green tomatillo & jalapeÃ±o salsa.</div>

  <div class="selectt Eggs Gluten" style="display: block;">
    <strong>PAO DE QUEIJO</strong><br> Traditional Brazilian cheese dough balls served with chipotle butter.</div>

  <div class="selectt Gluten" style="display: block;">
    <strong>PERUVIAN BOTIJA OLIVES</strong><br> In a herby marinade.</div>

  <div class="selectt Milk Gluten" style="display: block;">
    <strong>TEQUENOS</strong> <br> A popular Venezuelan street food; cheese filled fried bread sticks served with chipotle butter.</div>
</main>

<ul class="ks-cboxtags">

  <li>
    <input type="checkbox" id="checkboxOne" value="Gluten">
    <label for="checkboxOne"> Gulten</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxTwo" value="Crustaceans">
    <label for="checkboxTwo"> Crustaceans</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxThree" value="Eggs">
    <label for="checkboxThree"> Eggs</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxFour" value="Fish">
    <label for="checkboxFour"> Fish</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxFive" value="Peanuts">
    <label for="checkboxFive"> Peanuts</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxSix" value="Soy Beans">
    <label for="checkboxSix"> Soy Beans</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxSeven" value="Milk">
    <label for="checkboxSeven"> Milk</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxEight" value="Tree Nuts">
    <label for="checkboxEight"> Tree Nuts</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxNine" value="Celery">
    <label for="checkboxNine"> Celery</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxTen" value="Mustard">
    <label for="checkboxTen"> Mustard</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxEleven" value="Seasame">
    <label for="checkboxEleven"> Seasame</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxTweleve" value="Sulphur">
    <label for="checkboxTweleve"> Sulphur</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxThirteen" value="Lupin">
    <label for="checkboxThirteen"> Lupin</label>
  </li>
</ul></code>```

Body:
I'm using this code that I found online, but it's not working completely the way I want it to.

Basically I am wanting check boxes to hide divs based on the users selection.
I am building an allergens advice page for a restaurant. When a guest selects the allergens they have I want it to hide the dishes that they cannot have.

The above code works perfectly if the guest has one allergen. It hides the div. If they select more than one then the box will reappear.

$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
});

    Dough Balls

    Cheese dough balls served with chipotle butter.

        <input type="checkbox" id="checkboxThree" value="Eggs">
         Eggs

I'm guessing it's doing it because the code is toggling, but I don't know of any other code to prevent that.
Your help would be greatly appreciated.

Body:
I just copied further code from the link

What is happening here is just checkbox from ks-cboxtags class will be affected so any other checkbox will not have this functionality.

when you click on this it will displays div and if its selected div will be hide.

check below snippet for more details.

$(document).ready(function() {
    $(".test").click("test"); //ignore this

    $(".ks-cboxtags input").click(function() {
        $("."+$(this).val()).show();
        $(".ks-cboxtags input:checked").each(function() {
            $("."+$(this).val()).hide();
        });
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<main class="inline-block-center">
  <div class="selectt Gluten" style="display: block;">
    <strong style="font-size: 18px;">MEXICAN POPPADOMS</strong><br> Crispy blue corn tortillas with roasted tomato salsa, habanero &amp; pepper salsa, green tomatillo &amp; jalapeÃ±o salsa.</div>

  <div class="selectt Eggs Gluten" style="display: block;">
    <strong>PAO DE QUEIJO</strong><br> Traditional Brazilian cheese dough balls served with chipotle butter.</div>

  <div class="selectt Gluten" style="display: block;">
    <strong>PERUVIAN BOTIJA OLIVES</strong><br> In a herby marinade.</div>

  <div class="selectt Milk Gluten" style="display: block;">
    <strong>TEQUENOS</strong> <br> A popular Venezuelan street food; cheese filled fried bread sticks served with chipotle butter.</div>
</main>

<ul class="ks-cboxtags">

  <li>
    <input type="checkbox" id="checkboxOne" value="Gluten">
    <label for="checkboxOne"> Gulten</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxTwo" value="Crustaceans">
    <label for="checkboxTwo"> Crustaceans</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxThree" value="Eggs">
    <label for="checkboxThree"> Eggs</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxFour" value="Fish">
    <label for="checkboxFour"> Fish</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxFive" value="Peanuts">
    <label for="checkboxFive"> Peanuts</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxSix" value="Soy Beans">
    <label for="checkboxSix"> Soy Beans</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxSeven" value="Milk">
    <label for="checkboxSeven"> Milk</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxEight" value="Tree Nuts">
    <label for="checkboxEight"> Tree Nuts</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxNine" value="Celery">
    <label for="checkboxNine"> Celery</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxTen" value="Mustard">
    <label for="checkboxTen"> Mustard</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxEleven" value="Seasame">
    <label for="checkboxEleven"> Seasame</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxTweleve" value="Sulphur">
    <label for="checkboxTweleve"> Sulphur</label>
  </li>

  <li>
    <input type="checkbox" id="checkboxThirteen" value="Lupin">
    <label for="checkboxThirteen"> Lupin</label>
  </li>
</ul>