text:
Q: Inverse of a set of ordered pairs. An exam ask me the following question.
Let $r=\{(x,y) \ | \ x \in [-1,1] \ \text{and} \ y=x^2\}$, is the following statement true?
$$r^{-1}=\{(x,y) \ | \ x \in [0,1] \ \text{and} \ y=\pm\sqrt{|x|} \}$$
I have to answer the question by explaining the reason using some referable definition. At first, I was going to use the definition of function and inverse function because I noticed that $r$ is a function from $[-1,1]$ to $[0,1]$, but when I looked at it again, $r$ is not one-to-one and $r^{-1}$ is not a function because it maps $x$ to $-\sqrt{|x|}$ and $\sqrt{|x|}$.
I have been searching for a definition of inverse of a set of ordered pairs to see if it can be useful, but could not find one.
I am wondering what the $r^{-1}$ means in this case. If the question clearly state that $r$ is a function and $r^{-1}$ is the inverse of $r$, I would answer "No" already.

A: The set $r$ is an example of a relation, which is a simply a subset $R \subseteq X \times Y$ of the Cartesian product of two given sets $X, Y$. For $r$, the sets $X$ and $Y$ are not specified, but we could certainly take
$$X = [-1, 1], \quad Y = [0, 1].$$
We say that a relation $R \subseteq X \times Y$ is a function $R: X \to Y$ iff for all $x \in X$ there is exactly one $y \in Y$ such that $(x, y) \in R$. (Note that our choice of $X$, $Y$ makes $r$ a function.) If $R$ also satisfies the reverse, or more precisely that for all $y \in Y$ there is exactly one $x \in X$ such that $(x, y) \in R$, then by definition, the relation $R^{-1} \subseteq Y \times X$ defined by
$$\phantom{(\ast)} \qquad R^{-1} := \{(y, x) : (x, y) \in R\} \qquad (\ast)$$
is a function $R^{-1}: Y \to X$; we say that $R^{-1}$ is the inverse of $R$ and that $R$ (regarded as a function) is invertible.
On the other hand, the definition $(\ast)$ makes perfectly good sense for any relation $R$, not just those relations that are functions; so, for any relation $R$, we define the inverse relation $R^{-1}$ by that formula.


text:
Q: MQTT Data Formatting of JSON object I am receiving the following JSON string over MQTT and want to extract the float values only.
The data in the str format, should I change the sending format over MQTT?
'{"data": [-0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18287938, -0.0929368, 0.18287938, 0.07806691, 0.18287938, 0.17843866, 0.18287938, 0.28252788, 0.1848249, 0.37174721]}'
I only want to deal with the float arrays, but not finding the way to get it from the str objects.
Could someone help?
Kind regards
arun

A: If you are using python here's a way
import json
data_string = '{"data": [-0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18287938, -0.0929368, 0.18287938, 0.07806691, 0.18287938, 0.17843866, 0.18287938, 0.28252788, 0.1848249, 0.37174721]}'

#covert to Python
json_data = json.loads(data_string)

#extract the value 'data'
data = json_data["data"]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get an image thumbnail from a Pinterest video? Is there a simple way to get the image thumbnail address from a Pinterest video like this?

https://assets.pinterest.com/ext/embed.html?id=227431849917701427

A: Yes you can use py3-pinterest unofficial pinterest api.
import json

pin_data = load_pin_by_id(pin_id='227431849917701427')

print(json.dumps(pin_data))

And here is the pin_data json
https://pastebin.com/415w5de2
In the json videos -> V_720P-> thumbnail
https://i.pinimg.com/videos/thumbnails/originals/31/a1/5e/31a15e837c7eae841051968184580632.0000001.jpg


text:
Q: Installing pg gem for deploying rails app via heroku (windows) Running 'heroku run rails console' I get the following error:
Running `rails console` attached to terminal... up, run.7453
    /app/vendor/bundle/ruby/2.1.0/gems/activerecord4.2.1/lib/active_record/connection_adapters/connection_specification.rb:177:in
 `rescue in spec': Specified 'postgresql' for database adapter, but the gem is
 not loaded. Add `gem 'pg'` to your Gemfile (and ensure its version is at the
 minimum required by ActiveRecord). (Gem::LoadError)

This is in my Gemfile :
gem 'pg', '~> 0.18.1'

A: You need to specify in the config file using pg gem as well as running bundle install


text:
Q: RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False, Dataloader Error, and setting pin_memory=False I am a beginner trying to evaluate this video object segmentation network paper.
When following the instructions on https://github.com/seoungwugoh/STM
It says the requirements are as follows:-
python 3.6
pytorch 1.0.1.post2
numpy, opencv, pillow

I couldn't get this pytorch version to install, so I installed the conda-forge pytorch version 1.5.
and I run this command in either Windows 10 or Ubuntu 16.04 using Anaconda
(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python eval_DAVIS.py -g '1' -s val -y 16 -D ../DAVISSemiSupervisedTrainVal480

after doing pip install matplotlib, and pip install tqdm ...
I get the following error message:-
Space-time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Traceback (most recent call last):
File "eval_DAVIS.py", line 111, in
  model.load_state_dict(torch.load(pth_path))
File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 593, in load
  return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)
File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 773, in _legacy_load
  result = unpickler.load()
File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 729, in persistent_load
deserialized_objects[root_key] = restore_location(obj, location)
File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 178, in default_restore_location
  result = fn(storage, location)
File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 154, in _cuda_deserialize
    device = validate_cuda_device(location)
File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 138, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU
My Graphics Card Driver, and System and Packages are as follows:-
(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1070    Off  | 00000000:01:00.0  On |                  N/A |
| 26%   34C    P8    10W / 151W |    392MiB /  8118MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1247      G   /usr/lib/xorg/Xorg                           229MiB |
|    0      2239      G   compiz                                       126MiB |
|    0      9385      G   /usr/lib/firefox/firefox                       2MiB |
|    0     11686      G   /proc/self/exe                                30MiB |
+-----------------------------------------------------------------------------+

I also tried this
(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python -c 'import torch; print(torch.rand(2,3).cuda())'

tensor([[0.9178, 0.8239, 0.4761],
        [0.9429, 0.8877, 0.0097]], device='cuda:0')
Which shows that cuda is working here
(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda info
    active environment : STMVOS
    active env location : /home/oneworld/anaconda3/envs/STMVOS
            shell level : 1
       user config file : /home/oneworld/.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : 3.18.11
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
                          __glibc=2.23
       base environment : /home/oneworld/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/oneworld/anaconda3/pkgs
                          /home/oneworld/.conda/pkgs
       envs directories : /home/oneworld/anaconda3/envs
                          /home/oneworld/.conda/envs
               platform : linux-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Linux/4.4.0-179-generic ubuntu/16.04.6 glibc/2.23
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda list

packages in environment at /home/oneworld/anaconda3/envs/STMVOS:
Name                    Version                   Build  Channel
_libgcc_mutex             0.1                        main
blas                      1.0                         mkl
bzip2                     1.0.8                h516909a_2    conda-forge
ca-certificates           2020.4.5.1           hecc5488_0    conda-forge
cairo                     1.16.0            hcf35c78_1003    conda-forge
certifi                   2020.4.5.1               py38_0
cudatoolkit               10.2.89              hfd86e86_1
cycler                    0.10.0                   pypi_0    pypi
dbus                      1.13.6               he372182_0    conda-forge
expat                     2.2.9                he1b5a44_2    conda-forge
ffmpeg                    4.2.3                h167e202_0    conda-forge
fontconfig                2.13.1            h86ecdb6_1001    conda-forge
freetype                  2.9.1                h8a8886c_1
gettext                   0.19.8.1          hc5be6a0_1002    conda-forge
giflib                    5.2.1                h516909a_2    conda-forge
glib                      2.64.3               h6f030ca_0    conda-forge
gmp                       6.2.0                he1b5a44_2    conda-forge
gnutls                    3.6.5             hd3a4fd2_1002    conda-forge
graphite2                 1.3.13            he1b5a44_1001    conda-forge
gst-plugins-base          1.14.5               h0935bb2_2    conda-forge
gstreamer                 1.14.5               h36ae1b5_2    conda-forge
harfbuzz                  2.4.0                h9f30f68_3    conda-forge
hdf5                      1.10.6          nompi_h3c11f04_100    conda-forge
icu                       64.2                 he1b5a44_1    conda-forge
intel-openmp              2020.1                      217
jasper                    1.900.1           h07fcdf6_1006    conda-forge
jpeg                      9c                h14c3975_1001    conda-forge
kiwisolver                1.2.0                    pypi_0    pypi
lame                      3.100             h14c3975_1001    conda-forge
ld_impl_linux-64          2.33.1               h53a641e_7
libblas                   3.8.0                    15_mkl    conda-forge
libcblas                  3.8.0                    15_mkl    conda-forge
libclang                  9.0.1           default_hde54327_0    conda-forge
libedit                   3.1.20181209         hc058e9b_0
libffi                    3.2.1             he1b5a44_1007    conda-forge
libgcc-ng                 9.1.0                hdf63c60_0
libgfortran-ng            7.3.0                hdf63c60_0
libiconv                  1.15              h516909a_1006    conda-forge
liblapack                 3.8.0                    15_mkl    conda-forge
liblapacke                3.8.0                    15_mkl    conda-forge
libllvm9                  9.0.1                he513fc3_1    conda-forge
libopencv                 4.2.0                    py38_6    conda-forge
libpng                    1.6.37               hbc83047_0
libstdcxx-ng              9.1.0                hdf63c60_0
libtiff                   4.1.0                h2733197_0
libuuid                   2.32.1            h14c3975_1000    conda-forge
libwebp                   1.0.2                h56121f0_5    conda-forge
libxcb                    1.13              h14c3975_1002    conda-forge
libxkbcommon              0.10.0               he1b5a44_0    conda-forge
libxml2                   2.9.10               hee79883_0    conda-forge
matplotlib                3.2.1                    pypi_0    pypi
mkl                       2020.1                      217
mkl-service               2.3.0            py38he904b0f_0
mkl_fft                   1.0.15           py38ha843d7b_0
mkl_random                1.1.1            py38h0573a6f_0
ncurses                   6.2                  he6710b0_1
nettle                    3.4.1             h1bed415_1002    conda-forge
ninja                     1.9.0            py38hfd86e86_0
nspr                      4.25                 he1b5a44_0    conda-forge
nss                       3.47                 he751ad9_0    conda-forge
numpy                     1.18.1           py38h4f9e942_0
numpy-base                1.18.1           py38hde5b4d6_1
olefile                   0.46                       py_0
opencv                    4.2.0                    py38_6    conda-forge
openh264                  2.1.1                h8b12597_0    conda-forge
openssl                   1.1.1g               h516909a_0    conda-forge
pcre                      8.44                 he1b5a44_0    conda-forge
pillow                    7.1.2            py38hb39fc2d_0
pip                       20.0.2                   py38_3
pixman                    0.38.0            h516909a_1003    conda-forge
pthread-stubs             0.4               h14c3975_1001    conda-forge
py-opencv                 4.2.0            py38h23f93f0_6    conda-forge
pyparsing                 2.4.7                    pypi_0    pypi
python                    3.8.1                h0371630_1
python-dateutil           2.8.1                    pypi_0    pypi
python_abi                3.8                      1_cp38    conda-forge
pytorch                   1.5.0           py3.8_cuda10.2.89_cudnn7.6.5_0    pytorch
qt                        5.12.5               hd8c4c69_1    conda-forge
readline                  7.0                  h7b6447c_5
setuptools                46.4.0                   py38_0
six                       1.14.0                   py38_0
sqlite                    3.31.1               h62c20be_1
tk                        8.6.8                hbc83047_0
torchvision               0.6.0                py38_cu102    pytorch
tqdm                      4.46.0                   pypi_0    pypi
wheel                     0.34.2                   py38_0
x264                      1!152.20180806       h14c3975_0    conda-forge
xorg-kbproto              1.0.7             h14c3975_1002    conda-forge
xorg-libice               1.0.10               h516909a_0    conda-forge
xorg-libsm                1.2.3             h84519dc_1000    conda-forge
xorg-libx11               1.6.9                h516909a_0    conda-forge
xorg-libxau               1.0.9                h14c3975_0    conda-forge
xorg-libxdmcp             1.1.3                h516909a_0    conda-forge
xorg-libxext              1.3.4                h516909a_0    conda-forge
xorg-libxrender           0.9.10            h516909a_1002    conda-forge
xorg-renderproto          0.11.1            h14c3975_1002    conda-forge
xorg-xextproto            7.3.0             h14c3975_1002    conda-forge
xorg-xproto               7.0.31            h14c3975_1007    conda-forge
xz                        5.2.5                h7b6447c_0
zlib                      1.2.11               h7b6447c_3
zstd                      1.3.7                h0b5b093_0

The code it gets stuck on in eval_DAVIS.py is as follows:-
print('Loading weights:', pth_path)
model.load_state_dict(torch.load(pth_path))

I am using Ubuntu 16.04, however I tried a similar setup in windows 10 and received the same error messages.
Any help much appreciated.
Kind regards
OneWorld

A: I just created README.md file for this project to run successfully, it's here: Install PyTorch via pip to run STM Paper. I have tested in Windows 10 with Cuda version 10.1. Just follow this README.md step by step and you should be good to go.
Your PyTorch installation command could be different based on your system configuration, get your installation command as shown in the image below:

Your requirements.txt file should look like this:

NOTE: I haven't done anything with [path/to/DAVIS] or something. You might be able to run the script eval_DAVIS.py without installation error, and that all that I tested. You should be run in Ubuntu as well, just use an appropriate command from README.md.
Happy Coding!

A: So because of the error, and recommendation that Python threw up.
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU

I tried editing the code on line 111 in eval_DAVIS.py from this
model.load_state_dict(torch.load(pth_path))

to this
model.load_state_dict(torch.load(pth_path, map_location=torch.device('cpu')))

and then reran the code.
(STMVOS) C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python eval_DAVIS.py -g '0' -s val -y 17 -D C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\DAVIS2017SemiSupervisedTrainVal480

which gets through the weights loading.
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth

However, when it starts testing, it has the following error:-
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RunTimeError('''
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RunTimeError('''
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(OneWorldeout=OneWorldeout)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\queues.py", line 108, in get
    raise Empty
_queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RunTimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RunTimeError: DataLoader worker (pid(s) 2412, 15788) exited unexpectedly

This was using Anaconda, so the error below is just using windows command console, and pip
(env) C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python eval_DAVIS.py -g '0' -s val -y 17 -D C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\DAVIS2017SemiSupervisedTrainVal480
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(Timeout=Timeout)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\queues.py", line 105, in get
    raise Empty
_queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RunOneWorldeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RunTimeError: DataLoader worker (pid(s) 11448, 16644) exited unexpectedly

I also put this code in a small file called CUDATest.py to test that torch would do a simple matrix multiplication function.
# testing CUDA
import torch
device = torch.cuda.current_device()

n = 10
# 1D inputs, same as torch.dot
a = torch.rand(n).to(device)
b = torch.rand(n).to(device)
result = torch.matmul(a, b) # torch.Size([])

print("matmul result = ", result)

I ran the code as follows:-
(env)C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python CUDATest.py

The result was as follows:-
matmul result =  tensor(2.4603, device='cuda:0')

This suggests that my CUDA and Pytorch is working fine.

A: I changed my python version from 3.8. to 3.6, using conda-forge for install, and for reinstall of matplotlib.
I ran the code eval_DAVIS.py in debug mode within MSVSCode instead of from the command line commenting out the args, as follows:-
# def get_arguments():
#     parser = argparse.ArgumentParser(description="SST")
#     parser.add_argument("-g", type=str, help="0; 0,1; 0,3; etc", required=True)
#     parser.add_argument("-s", type=str, help="set", required=True)
#     parser.add_argument("-y", type=int, help="year", required=True)
#     parser.add_argument("-viz", help="Save visualization", action="store_true")
#     parser.add_argument("-D", type=str, help="path to data",default='/local/DATA')
#     return parser.parse_args()

# args = get_arguments()

# GPU = args.g
# YEAR = args.y
# SET = args.s
# VIZ = args.viz
# DATA_ROOT = args.D

GPU = '0'
YEAR = '17'
SET = 'val'
VIZ = 'store_true'
DATA_ROOT = '..\\DAVIS2017SemiSupervisedTrainVal480'

Above the line
for seq, V in enumerate(Testloader):

I wrote this to test whether there was a cuda is available problem.
if torch.cuda.is_available() == False:
    print("********** CUDA is NOT available just before line of error **********")
else:
    print("********** CUDA is available, and working fine just before line of error ***********")

this produces the following terminal log
Space-time Memory Networks: initialized.
STM : Testing on DAVIS
using Cuda devices, num: 1
--- Produce mask overaid video outputs. Evaluation will run slow.
--- Require FFMPEG for encoding, Check folder ./viz
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
********** CUDA is available, and working fine just before line of error ***********
Space-time Memory Networks: initialized.
STM : Testing on DAVIS
using Cuda devices, num: 1
--- Produce mask overaid video outputs. Evaluation will run slow.
--- Require FFMPEG for encoding, Check folder ./viz
Space-time Memory Networks: initialized.
STM : Testing on DAVIS
using Cuda devices, num: 1
--- Produce mask overaid video outputs. Evaluation will run slow.
--- Require FFMPEG for encoding, Check folder ./viz
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
********** CUDA is available, and working fine just before line of error ***********
Start Testing: STM_DAVIS_17val
********** CUDA is available, and working fine just before line of error ***********

it gets to this line of code
for seq, V in enumerate(Testloader):

and provides the following error message:-
Exception has occurred: RuntimeError

        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 127, in <module>
    for seq, V in enumerate(Testloader):
  File "<string>", line 1, in <module>

So, this got rid of the CUDA error, without needing to switch the code to use CPU.
However, this still produces the freeze_support() error...
and the logs identify a dataloader error:-
Traceback (most recent call last):
  File "eval_DAVIS.py", line 127, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 798, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RuntimeError: DataLoader worker (pid(s) 15916, 1232) exited unexpectedly

A: because of the Python error suggestion
if __name__ == '__main__':
    freeze_support()

I added this line
if __name__ == '__main__':

above the line
for seq, V in enumerate(Testloader):

and indented that line and everything else below.
It then worked as far as to the end of [bike packing]
However requested a scipy install before [black swan]
So I did conda install scipy
and reran, and it started to go through the rest [bmx-trees], [breakdance] etc.
The resulting eval_DAVIS.py file looked like this...
from __future__ import division
import torch
from torch.autograd import Variable
from torch.utils import data

import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.utils.model_zoo as model_zoo
from torchvision import models

# general libs
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import math
import time
import tqdm
import os
import argparse
import copy

### My libs
from dataset import DAVIS_MO_Test
from model import STM

torch.set_grad_enabled(False) # Volatile

# def get_arguments():
#     parser = argparse.ArgumentParser(description="SST")
#     parser.add_argument("-g", type=str, help="0; 0,1; 0,3; etc", required=True)
#     parser.add_argument("-s", type=str, help="set", required=True)
#     parser.add_argument("-y", type=int, help="year", required=True)
#     parser.add_argument("-viz", help="Save visualization", action="store_true")
#     parser.add_argument("-D", type=str, help="path to data",default='/local/DATA')
#     return parser.parse_args()

# args = get_arguments()

# GPU = args.g
# YEAR = args.y
# SET = args.s
# VIZ = args.viz
# DATA_ROOT = args.D

GPU = '0'
YEAR = '17'
SET = 'val'
VIZ = 'store_true'
DATA_ROOT = '..\\DAVIS2017SemiSupervisedTrainVal480'

# Model and version
MODEL = 'STM'
print(MODEL, ': Testing on DAVIS')

os.environ['CUDA_VISIBLE_DEVICES'] = GPU
if torch.cuda.is_available():
    print('using Cuda devices, num:', torch.cuda.device_count())

if VIZ:
    print('--- Produce mask overaid video outputs. Evaluation will run slow.')
    print('--- Require FFMPEG for encoding, Check folder ./viz')

palette = Image.open(DATA_ROOT + '/Annotations/480p/blackswan/00000.png').getpalette()

def Run_video(Fs, Ms, num_frames, num_objects, Mem_every=None, Mem_number=None):
    # initialize storage tensors
    if Mem_every:
        to_memorize = [int(i) for i in np.arange(0, num_frames, step=Mem_every)]
    elif Mem_number:
        to_memorize = [int(round(i)) for i in np.linspace(0, num_frames, num=Mem_number+2)[:-1]]
    else:
        raise NotImplementedError

    Es = torch.zeros_like(Ms)
    Es[:,:,0] = Ms[:,:,0]

    for t in tqdm.tqdm(range(1, num_frames)):
        # memorize
        with torch.no_grad():
            prev_key, prev_value = model(Fs[:,:,t-1], Es[:,:,t-1], torch.tensor([num_objects]))

        if t-1 == 0: #
            this_keys, this_values = prev_key, prev_value # only prev memory
        else:
            this_keys = torch.cat([keys, prev_key], dim=3)
            this_values = torch.cat([values, prev_value], dim=3)

        # segment
        with torch.no_grad():
            logit = model(Fs[:,:,t], this_keys, this_values, torch.tensor([num_objects]))
        Es[:,:,t] = F.softmax(logit, dim=1)

        # update
        if t-1 in to_memorize:
            keys, values = this_keys, this_values

    pred = np.argmax(Es[0].cpu().numpy(), axis=0).astype(np.uint8)
    return pred, Es

Testset = DAVIS_MO_Test(DATA_ROOT, resolution='480p', imset='20{}/{}.txt'.format(YEAR,SET), single_object=(YEAR==16))
Testloader = data.DataLoader(Testset, batch_size=1, shuffle=False, num_workers=2, pin_memory=True)

model = nn.DataParallel(STM())
if torch.cuda.is_available():
    model.cuda()
model.eval() # turn-off BN

pth_path = 'STM_weights.pth'
print('Loading weights:', pth_path)
model.load_state_dict(torch.load(pth_path)) # , map_location=torch.device('cpu')

code_name = '{}_DAVIS_{}{}'.format(MODEL,YEAR,SET)
print('Start Testing:', code_name)

if torch.cuda.is_available() == False:
    print("********** CUDA is NOT available just before line of error **********")
else:
    print("********** CUDA is available, and working fine just before line of error ***********")

if __name__ == '__main__':

    for seq, V in enumerate(Testloader):
        Fs, Ms, num_objects, info = V
        seq_name = info['name'][0]
        num_frames = info['num_frames'][0].item()
        print('[{}]: num_frames: {}, num_objects: {}'.format(seq_name, num_frames, num_objects[0][0]))

        pred, Es = Run_video(Fs, Ms, num_frames, num_objects, Mem_every=5, Mem_number=None)

        # Save results for quantitative eval ######################
        test_path = os.path.join('./test', code_name, seq_name)
        if not os.path.exists(test_path):
            os.makedirs(test_path)
        for f in range(num_frames):
            img_E = Image.fromarray(pred[f])
            img_E.putpalette(palette)
            img_E.save(os.path.join(test_path, '{:05d}.png'.format(f)))

        if VIZ:
            from helpers import overlay_davis
            # visualize results #######################
            viz_path = os.path.join('./viz/', code_name, seq_name)
            if not os.path.exists(viz_path):
                os.makedirs(viz_path)

            for f in range(num_frames):
                pF = (Fs[0,:,f].permute(1,2,0).numpy() * 255.).astype(np.uint8)
                pE = pred[f]
                canvas = overlay_davis(pF, pE, palette)
                canvas = Image.fromarray(canvas)
                canvas.save(os.path.join(viz_path, 'f{}.jpg'.format(f)))

            vid_path = os.path.join('./viz/', code_name, '{}.mp4'.format(seq_name))
            frame_path = os.path.join('./viz/', code_name, seq_name, 'f%d.jpg')
            os.system('ffmpeg -framerate 10 -i {} {} -vcodec libx264 -crf 10  -pix_fmt yuv420p  -nostats -loglevel 0 -y'.format(frame_path, vid_path))

However...
Eventually I got an out of memory error
[car-shadow]: num_frames: 40, num_objects: 1
100%|█████████████████████████████████████████████████████████████████████████████████████████████████| 39/39 [00:09<00:00,  3.98it/s]
Traceback (most recent call last):
  File "eval_DAVIS.py", line 129, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 856, in _next_data
    return self._process_data(data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 881, in _process_data
    data.reraise()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\_utils.py", line 395, in reraise
    raise self.exc_type(msg)
RuntimeError: Caught RuntimeError in pin memory thread for device 0.
Original Traceback (most recent call last):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\_utils\pin_memory.py", line 31, in _pin_memory_loop
    data = pin_memory(data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\_utils\pin_memory.py", line 55, in pin_memory
    return [pin_memory(sample) for sample in data]
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\_utils\pin_memory.py", line 55, in <listcomp>
    return [pin_memory(sample) for sample in data]
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\_utils\pin_memory.py", line 47, in pin_memory
    return data.pin_memory()
RuntimeError: cuda runtime error (2) : out of memory at ..\aten\src\THC\THCCachingHostAllocator.cpp:278

so I set the testloader from pin_memory=True to false at around line 108 in eval_DAVIS.py
Testloader = data.DataLoader(Testset, batch_size=1, shuffle=False, num_workers=2, pin_memory=False)

and reran.
Seemed to work fine.


text:
Q: SAS to Python reshape dataframe script I am trying to move from SAS into Python and I am facing a few challenges. Specifically, I have a dataset with 301 observations with  in wide-format and I am trying to reshape it into long-format. The wide-format dataframe looks like below:
enter image description here
And I want to convert it into a long-format that would look like as below:
enter image description here
The SAS code I have used to convert my dataset from wide to long is:
 data longformat;
 set wideformat;
 array arts(*) art1-art10;
 array cits(*) cit1-cit10;
 if jobtime =. then jobtime = 11;
 do year = 1 to dur;
 if year = dur then promo=event; else promo=0;
 if year ge jobtime then jobpres=prest2; else jobpres=prest1;
 art = arts(year);
 cit = cits(year);
 output;
 end;
run;

Does anyone have any idea how to make this kind of conversion into Python?

A: From your pictures I can't tell exactly what you're trying to be but in general reshaping data in SAS is most easily done with PROC TRANSPOSE. Here is an example
proc transpose data=wideformat out=longformat;
    by year;
run;

Here is the link to current documentation for PROC TRANSPOSE


text:
Q: Ordering by multiple fields I'm wanting to order a queryset based on a couple of different related fields
Models.py
class Appointment(models.Model):
    start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True)

class Event(models.Model):
    start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True)

class Job(models.Model):
   event = models.ForeignKey(Event, on_delete=models.SET_NULL)
   appointment = models.ForeignKey(appointment, on_delete=models.SET_NULL)

views.py
qs = Job.objects.all().order_by('event__start_time','appointment__start_time')

Is this the correct way to do this? Will this always order all of the jobs in the correct order based on the associated star time?
Thanks!


text:
Q: getting unhandled exception type malformed url exception I'm pretty new to java , actually I have just started learning it
I tried to do an exercise and the exercise was to read the first five lines of a webpage
for start I wrote this code :
import java.io.* ;

import java.net.URL ;

class testcode {

    public static void main(String[] args) throws Exception {
        URL address = new URL("http://www.yahoo.com/") ;
        InputStream is = address.openStream() ;
        InputStreamReader isr = new InputStreamReader(is) ;
        BufferedReader reader = new BufferedReader(isr) ;
        String line = reader.readLine() ;
    }

}

but when I run this piece of code through Eclipse , I get this :
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.testcode.main(testcode.java:10)

Why is this happening !?
and ofcourse when I dont put the throws Exception part at the begining I get the malformed url exception !
PS : my internet connection works just fine !
Can Somebody please help me and explain why is this happening while doing that ?
I have a pretty good c++ background so feel free to explain as deep as you can :D

A: It seems like your program can't connect to the URL. Are u using internet behind proxy? If so, then make sure ur program is configured accordingly. One way is to use this code:
System.setProperty("http.proxyHost", "proxy.mydomain.com");
System.setPropery("http.proxyPort", "8080");


text:
Q: How to get the coordinates of the cv2.imshow window? I am using this code
import numpy as np
import cv2
from PIL import ImageGrab as ig
import time

last_time = time.time()
while(True):
    screen = ig.grab(bbox=(200, 200, 600, 600))
    print('Loop took {} seconds'.format(time.time()-last_time))
    cv2.imshow("test", np.array(screen))
    last_time = time.time()
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

from this question on SO.
This is my output:
output
This works fine. I am looking for a solution where I can capture the area just under the output window. When I move the window around, the output changes as well. One way would be to update this line as follows:
screen = ig.grab(bbox=(x1, y2, x2, y2))

but thing I can't figure out is that how to get these parameters values. Or how to get the coordinates of the output window?
P.S. I don't have enough reputation to embed images here directly so I added the external link.


text:
Q: facebookConnectPlugin.showDialog is not showing image on share dialog I have recently upgraded a Cordova app from V2.9 to V3.5,
I am trying to share a link to facebook in a cordova app but Dialog is not showing image in the share dialog.
Plugin used : https://github.com/Wizcorp/phonegap-facebook-plugin
Code:
facebookConnectPlugin.showDialog({
  method: 'feed',
  link: 'http://example.com'
}, function(response){});

og metatags at example.com
<meta property="og:image" content="path to logo.jpg" />
<meta property="og:url" content="http://example2.com" />

there are no og metatags at example2.com
Problem
facebookConnectPlugin.showDialog is not showing image in the dialog since in between last month.
Findings
Dialog is getting title and description from the example2.com and as there is no og:image tag there, dialog is not showing any picture.
Plugin is making call to v2.2 API of the FB graph API while our FB App in facebook is V1.0
Old cordova App is making call to V1.0 API of the FB Graph and it is also not showing the picture now.
There is a or:url in a metatag of the example.com which points to example2.com and I have no access to change the og:url.
Question
What is causing the problem, is it FB Graph API update or og:url and if it is og:url, then how was it working before?

A: I can't see where you use the PhoneGap plugin specific methods:

*

*https://github.com/Wizcorp/phonegap-facebook-plugin#show-a-dialog
IMHO, the code should be
facebookConnectPlugin.showDialog({
    method: "feed",
    link: "http://example.com",
    caption: "Such caption, very feed."
}, function(success) { }, function(error) { });

A: Try loading the image from url
First ensure that the page example.com has the image on the page
the do this  your code should work Note that where the page has more than one image the user
may be prompted to select one.
Good luck
facebookConnectPlugin.showDialog({
 method: 'feed',
 link: 'http://example.com',
}, function(response){});

You can also post the same issues here
https://github.com/Wizcorp/phonegap-facebook-plugin/issues
and someone will help you out ASAP


text:
Q: useURL hook expo-linking for background app The expo-linking React Native package has a hook named useURL that isn't working for me when the app is in the background. From the docs it Returns the initial URL followed by any subsequent changes to the URL. The problem I'm having with my managed expo app is that the hook doesn't work when the app is already open in the background. Here is the hook:
export default function App() {
  const isLoadingComplete = useCachedResources();
  const url = Linking.useURL();

  useEffect(() => {
    Alert.alert(url ? url.substring(20) : 'null');
  }, [url]);

  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      ...
    );
  }
}

If I open the URL exp://exp.host/@myprofile/myproject?a=bwhen the app is closed, I get an Alert as expected. If the app is in the background, the Alert doesn't go off. I've tested on an iOS emulator and a physical Android. Any solutions? Note that similar problems happen with Linking.addEventListener().


text:
Q: How to match an ip address in mysql? For example, I am having a column storing data like this.
Apple
12.5.126.40
Smite
Abby
127.0.0.1
56.5.4.8
9876543210
Notes

How to select out only the rows with data in IP format?
I have tried with  '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
but I have no idea why it also matches 9876543210

A: IS_IPV4() is a native mysql function that lets you check whether a value is a valid IP Version 4.
SELECT *
FROM ip_containing_table
WHERE IS_IPV4(ip_containing_column);

I don't have data, but I reckon that this must be the most solid and efficient way to do this.
There are also similar native functions that check for IP Version 6 etc.

A: This may not be the most efficient way, and it's not technically regex, but it should work:
SELECT col1 FROM t1 WHERE col1 LIKE '%.%.%.%';

A: you could also use the useful function inet_aton()
SELECT *
FROM yourtable
WHERE inet_aton(thecolumn) is not null

A: You're going to need to use REGEXP to match the IP address dotted quad pattern.
SELECT *
FROM yourtable
WHERE
  thecolumn REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$'

Technically, this will match values that are not valid IP addresses, like 999.999.999.999, but that may not be important.  What is important, is fixing your data such that IP addresses are stored in their own column separate from whatever other data you have in here.  It is almost always a bad idea to mix data types in one column.
mysql> SELECT '9876543210' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$';
+---------------------------------------------------------------------------+
| '9876543210' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$' |
+---------------------------------------------------------------------------+
|                                                                         0 |
+---------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT '987.654.321.0' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$';
+------------------------------------------------------------------------------+
| '987.654.321.0' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$' |
+------------------------------------------------------------------------------+
|                                                                            1 |
+------------------------------------------------------------------------------+

Another method is to attempt to convert the IP address to a long integer via MySQL's INET_ATON() function.  An invalid address will return NULL.
This method is likely to be more efficient than the regular expression.
You may embed it in a WHERE condition like: WHERE INET_ATON(thecolumn) IS NOT NULL
SELECT INET_ATON('127.0.0.1');
+------------------------+
| INET_ATON('127.0.0.1') |
+------------------------+
|             2130706433 |
+------------------------+

SELECT INET_ATON('notes');
+--------------------+
| INET_ATON('notes') |
+--------------------+
|               NULL |
+--------------------+

SELECT INET_ATON('56.99.9999.44');
+----------------------------+
| INET_ATON('56.99.9999.44') |
+----------------------------+
|                       NULL |
+----------------------------+

A: Lengthy but works fine:
mysql> SELECT '1.0.0.127' regexp '^([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\.([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\.([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\.([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$';


text:
Q: creating connection class to use over code base I have 2 files. Connect.php and AddUser.php.
I am trying to use the mysqli connection established in connect to insert data to my database from within AddUser. I feel like I have all the pieces in the right place, but it isn't working... Any help would be wonderful!
Here is my code:
Connect.php
<?php
class Connection
{
    public function connect()
    {
        $conn = "localhost";
        $un = "user";
        $pw = "password";
        $db = "db";
        $mysqli = new mysqli($conn, $un, $pw, $db);

        return $mysqli;
    }
}

AddUser.php
<?php
class addUser{
    public function add() {
        $conn = new Connection();
        $conn->connect();
        $sql = "INSERT INTO tbl_users (user_name) VALUES ('test')";
        $insert = $conn->query($sql);
    }
}

The connection script is included using a require_once statement at the top of my index.php router.
<?php
require_once "configs/Toro.php"; //ToroPHP router
require_once "configs/db.cnfg.php"; //db config (where class Connection is written)
require_once "handlers/addUser.php"; //adduser file

A: Temporary resolution was to take Connect() out of the class Connection and have it as a stand a lone function...
<?php
    function connect()
    {
        $conn = ($_SERVER['SERVER_NAME'] === "vagrantup") ? "50.87.147.177" : "localhost";
        $un = "tbremer_bitters";
        $pw = "4t:7*4334S";
        $db = "tbremer_bittersyndrome";
        $mysqli = new mysqli($conn, $un, $pw, $db);

        return $mysqli;
    }

This allowed me to use mysqli as an object instead of the PDO version.


text:
Q: Set button position to Horizontal I have a dialog and this have their buttons in vertical but I need to show these buttons in horizontal.
so is like it see.
http://bugtrackertesting.tecnova.cl/file_download.php?file_id=20777&type=bug
I can't change the global css style , therefore I need write css for my single view.
anyone know how to set this, thanks in advance.


text:
Q: xCode 4.5 New file > Sub Class of __add_unsigned? When i try to add a new file to my project i am not able to choose a subclass of it.
I do these steps:
Objective-C class > Next > When i open the Subclass of combobox the combobox is filled with the correct classes for like 1 nanosecond.. then it all changes to __add_unsigned..
Anyone knows why it shows like this?


text:
Q: Outlook 2007 hyperlink does not display and the display field codes option is not there I am trying to turn off the "Display Field Codes" in Outlook 2007 editor options, but my Outlook is not displaying this option!  I don't know why others can see it and I don't have this.
Meanwhile, my links show up with those darn brackets {www.google.com} etc. And I can't fix it without this button!

A: Did you try pressing ALT + F9? This keyboard shortcut typically works for any version of Outlook and Word to toggle between Field Codes and their values.


text:
Q: inserting a mysql query in codeigniter $query = $this->db->query('select
  sum(like) as atotal
from
  like
where
  sfid = '.$short);<br>
print_r($query);

and the error is

Error Number: 1064
You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'like) as atotal from like where sfid = 11' at line 2
select sum(like) as atotal from like where sfid = 11
Filename: C:\wamp\www\don\system\database\DB_driver.php
Line Number: 330

'like' in sum(like) is column name and 'like' after 'from' is table name
thank you in advance

A: $data = array(
              "category_id"=>$this->input->post('category'),
              "name"=>$this->input->post('name'),
              "description"=>$this->input->post('descri')
              );

    $this->db->insert('measurement', $data);
    $inserted_id = $this->db->insert_id();

A: like is a MySQL reserved word

*

*http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
which needs to be wrapped in backticks.
Either do that, or rename your table/column to something else.
Using reserved words is discouraged to be used. You can use them, but require special attention.

*

*I suggest you rename your table to likes and your column to another word.

If renaming them isn't an option, then modify your code to read as this:
$query = $this->db->query('select
  sum(`like`) as atotal
from
  `like`
where
  sfid = '.$short);
print_r($query);

A: You shouldn't use like keyword in your query.
It is sql-specific word treated as special keyword. To solve this task, you should change column name in database table or wrap like keyword in backticks either:
$query = $this->db->query('select sum(`like`) as atotal from `like` where sfid = '.$short);

A: You can still use it. Just use `like` instead of like OR change the table name. The backQuote helps to override the MySql keyword override.


text:
Q: sending an image from the server to android and displaying the image on the screen in my code I transfer a image from a PC to a phone via a java socket. Everything works fine, the picture is saved to the phone and there are no problems. But the question arose, is it possible to display image on the screen without saving?
Server code:
     FileInputStream fis = new FileInputStream("D:\\fon2.jpg");
     byte [] buffer = new byte[fis.available()];
     fis.read(buffer);

     ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
     oos.writeObject(buffer);
     oos.close();
     System.out.println("Done");

client code:
class ClientThread implements Runnable {
        @Override
        public void run() {
            try {
                Socket s = new Socket(HOST, 4444);
                OutputStream out = s.getOutputStream();
                PrintWriter output = new PrintWriter(out);

                output.println("hello");
                output.flush();

                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                byte [] buffer = (byte[]) ois.readObject();

               // save image
               @SuppressLint("SdCardPath") FileOutputStream fos =  new FileOutputStream("/sdcard/2.jpg");
               fos.write(buffer);
               fos.close();

                output.close();
                out.close();
                s.close();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

solution to this problem:
when you click on the image, a connection to the server is made and the image is sent
main code:
public void image(View view) {
      new Thread(new ClientThread()).start();

      do {
          if (bitmap != null) {
              imageView.setImageBitmap(bitmap);
              break;
          }
      }while (true);

  }

  class ClientThread implements Runnable {
      @Override
      public void run() {
          try {
              Socket s = new Socket(HOST, 4444);
              OutputStream out = s.getOutputStream();
              PrintWriter output = new PrintWriter(out);

              output.println(tour);
              output.flush();

              ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
              buffer = (byte[]) ois.readObject();
              bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
              bitmap = Bitmap.createScaledBitmap(bitmap,  600 ,600, true);
              Log.d("log", String.valueOf(buffer));

              output.close();
              out.close();
              s.close();

          } catch (IOException | ClassNotFoundException e) {
              e.printStackTrace();
          }

      }
  }

layout:
<ImageView
      android:id="@+id/mainImage"
      android:layout_width="150dp"
      android:layout_height="160dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:onClick="image"
      android:src="@drawable/ic_gps"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      tools:ignore="UsingOnClickInXml" />

A: Yes that is possible.
Your image is in byte [] buffer = ...
You can make a Bitmap instance with BitmapFactory.decodeByteArray().
After that assign bitmap to an ImageView.


text:
Q: Representing sentences as propostional logic formula I need to translate the following sentence:
Whenever the alarm sounds the fan must be on and the building empty
into a logical proposition.
So I defined variable as follow:
$p$ = "The alarm sounds"
$q$ = "The fan is on"
$r$ = "The building is empty"
The answer: $p \to (q ∧ r).$
I'm confused by this question because if the alarm does not sound and the fan is not on and the building is not empty then by implication doesn't this mean the statement is true?

A:
Note the three rows of truth value assignments for $p, q, r$ which yield  "F" in the right most collomn.
We can  summarize the matter as follows:  $p\to (q\land r)$ is true, except when (p is T and ($q \land r$) is false), which happens when p is true, and  either q is false, or r is false, or both q and r are false.
Simply put, we can simplify the statement as follows.  Let $s:=q\land r$.

Then we have $p \to s$, which by definition is false if and only if $p$ is true, and $s$ is false.
Note that we are using the definition of the material conditional, in which nothing is needed in terms of relevancy, correlation, or cause-and effect relations between the $p,$ and $s$ in $p\to s$.

A: Yup; in the case that the alarm does not sound, the fan is not on, and the building is not empty, the "Whenever..." sentence should come out true.
Indeed, $p \implies (q \wedge r)$ comes out true if $p$, $q$, and $r$ are all false.


text:
Q: Why is CORS Error Returned When Passing Encoded Data I'm forced to work with poor data quality. One instance is that primary key value of a given table can contain spaces and special characters, e.g.  35581/H0034-100003
What I'm trying to do is get a record by it's primary key value, so the web API I setup is a GET:
[HttpGet]
[Route("Api/SaleHeaders/{saleNumberEncoded}")]
public SaleHdrViewModel GetSaleHeader(string saleNumberEncoded)
{
    var saleNumber = HttpUtility.UrlDecode(saleNumberEncoded);
    return _saleHeaderService.Get(saleNumber);
}

Then when I go to send the value from the front-end, I use:
getSaleHeader(saleNumber: string): Observable<ISaleHeader> {
    saleNumber = encodeURIComponent(saleNumber);
    const url = `${environment.ApiUrl}/Api/SaleHeaders/${saleNumber}`;
    return this.http.get<ISaleHeader>(url);
}

The issue is that the request is failing, specifically due to a CORS error:

Access to XMLHttpRequest at 'localhost:52864/Api/SaleHeaders/%2035581%2FH0033-100000' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I don't think that this is actually a CORS error. I think this actually has to do with CORS because if I edit and resend with the Access-Control-Allow-Origin: * header, it returns a 404. I think this has to do with trying to send encoded primary key value.
I know that I can change my request type from a GET to a POST and then just pass the primary key value in the body, but I'd prefer to keep getting records in a consistent manner (GET request with Api/{table}/{pk} route).
Edit - I've verified that if I pass an unencoded value (e.g. 00007931) then the endpoint works fine.

A: You cannot use character / as a route parameter because it will be readed as a different resource access. I recommend you to use another pattern to encode your data and avoid missunderstanding the information. Otherwise you could pass the data as a query parameter using:
http://testweb.z/route?userdata=123/321
Also you can change your method signature to: (that's the way I recommend to you)
[HttpGet]
[Route("Api/SaleHeaders/{table}/{pk}")]
public SaleHdrViewModel GetSaleHeader(string table, string pk)

A: I followed Jorge Machado's advice that was posted in the comment section of encoding the value to Base64 and then decoding it on the server.
Angular:
getSaleHeader(saleNumber: string): Observable<ISaleHeader> {
    saleNumber = btoa(saleNumber);
    const url = `${environment.ApiUrl}/Api/SaleHeaders/${saleNumber}`;
    return this.http.get<ISaleHeader>(url);
}

C#:
[HttpGet]
[Route("Api/SaleHeaders/{saleNumberEncoded}")]
public SaleHdrViewModel GetSaleHeader(string saleNumberEncoded)
{
    var bytes = System.Convert.FromBase64String(saleNumberEncoded);
    var saleNumber = System.Text.Encoding.UTF8.GetString(bytes);

    return _saleHeaderService.Get(saleNumber);
}

This allows me to keep with my existing pattern of having a GET endpoint where the route follows the following pattern: Api/{table name}/{primary key value}


text:
Q: How to close EXTJS form panel when clicked in rest of the browser area. I am Working with extjs 4.2.1 and I was trying to close log in form panel when user clicks out side the Log In panel(in white area of browser).
I want to know which event should I used to check if user has clicked out side log in panel in extjs, and how to close panel using that event.
Can any one help me to understand it in better and easy way or any small code snippet which will make me easy to understand.
Thanks in advance....

A: You can register a listener on the body element.  Here's a simple example:
var panel = new Ext.Panel({
    cls: 'the-panel',
    width: 400,
    height: 400,
    renderTo: Ext.getBody()
});

Ext.getBody().on('click', function (event) {
    var targEl = Ext.get(event.getTarget());

    if (targEl === panel.getEl() || targEl.up('.the-panel')) {
        //clicked on or within the panel, do nothing
    } else {
        panel.close();
    }
});

You'll likely want to enhance the example above such that the event is unregistered once the panel is closed.

A: handler: function(button, e) {
    success: function(form, action) {
        button.up('.window').close();
    },
}


text:
Q: NHibernate Session and Transaction management in HttpModule I've seen many implementations on the web of people managing their NHibernate sessions and transactions in a HttpModule.
The HttpModule:

*

*creates a session at the start of the request

*wraps the whole request in a transaction

*commits the transaction at the end of the request

If people use this strategy how are they handling the following scenario:

*

*request comes in

*retrieve object from database

*update object

*object fails validation

*changes to the object are still persisted because the transaction is committed in the HttpModule.

It seems that there is no good way to rollback the transaction in the above scenario.  The only plan I can come up with is to:

*

*write my validation in such a way as it's guaranteed to succeed before updating my domain object (takes my validation out of my domain model).

*manage my transaction closer to my business logic and throw away the idea of doing it transparently in a HttpModule. (I've seen quite a few posts recommend this)

Seeing as so many people seem to be using the HttpModule approach I'm hoping there is a third way of managing this scenario that I haven't thought of?

A: You can use some kind of global exception handling. Now I am using System.AppDomain.CurrentDomain.UnhandledException. In this handler you will need to call Transaction.Rollback(); And also condsider setting some flag (that also lives during current request only) that will point wehether you need to commit your transaction or roll back. This can make code more clear.
Edit
Alternativly you can use Error event of the HttpApplication
public class HelloWorldModule : IHttpModule
{
    void Init(HttpApplication application)
    {
        application.BeginRequest +=
            (new EventHandler(this.Application_BeginRequest));
        application.EndRequest +=
            (new EventHandler(this.Application_EndRequest));
        //this is it
        applicaiton.Error +=
            (new EventHandler(this.Application_Error));
    }


text:
Q: Banach space - using continuity to show contradiction Let $X=(C[-1,1], \| \cdot \|_\infty)$. Let $Y=\{f \in C[-1,1] : \int_{-1}^0 f = \int_0^1 f \}$ be a subspace.
Let $\phi(f)= \int_{-1}^0 f -\int_0^1 f $.
Then we have $Y=Ker(\phi)= \phi^{-1}\{0 \}$.
Suppose there exists $v \in x$ with $\| v\|_{\infty}=1$ such that $\phi(v)= \| \phi\|$. Then I want to show that this is a contradiction.
I tried to show the contradiction by using that $\phi$ is continuous.
i.e. I used a similar argument as Let $X=\{f\in C[0,1] :f(0)=0 \}$. Prove that there does not exist $f\in X$ such that $\|f \|_{\infty}\leq 1$ and $|T(f)|= 1$., by taking $r>0$. Then I get $0 = | \phi(t)| <2 -3r$, which didn't get anywhere.
Any help is appreciated!
Thanks!

A: For every $f$ one has
$$
  |\phi(f)| \leq
  \left|\int_{-1}^0f(x)\,  dx\right| +   \left|\int_0^1f(x)\,  dx|\right| \leq  \|f\| + \|f\| = 2 \|f\|,
  $$
so $\|\phi\|\leq 2$.  Letting
$$
  f_n(x) = \left\{\matrix{
  1, & \text {if }  -1\leq x<-1/n,\hfill \cr
  -nx, & \text {if } -1/n\leq x\leq 1/n, \cr
  -1, & \text {if }  \phantom{- \ } 1/n\leq x\leq 1,\hfill \cr
  }\right.
  $$
we have $\|f_n\|=1$, and $\lim_{n\to\infty }\phi(f_n)=2$, so actually  $\|\phi\|=2$.
Given $f$ in $C[-1, 1]$ with   $\|f\|=1$, let
$$
  A=\int_{-1}^0f(x)\,  dx, \quad \text{and}\quad   B=\int_0^1f(x)\,  dx.
  $$
Observing that $-1\leq A,B\leq 1$, the only way one can get $\phi(f)=2$, that is,
$A-B=2$, is when $A=1$ and $B=-1$. In this case we have
$$
  0 = 1-A = \int_{-1}^0\,  dx - \int_{-1}^0f(x)\,  dx
  = \int_{-1}^0\, 1-f(x)\,  dx.
  $$
Since $1-f(x)$ is continuous and nonnegative, this implies that $f(x)=1$ on $[-1,0]$.  In a similar way it follows
that $f(x)=-1$ on $[0, 1]$, but this violates the continuity of $f$.  Therefore you never get $\phi(f)=2$.


text:
Q: How to mock Local Variables for unit testing in Jest? I have two files, file.component.ts containing:
  setTwoNumberDecimal(e) {
    const USER_VAL = parseFloat(e.target.value.replace(/,/g, ''));
    e.target.value = this.getTruncatedValue(USER_VAL, 1);
  }

and my test file file.component.specs.ts containing:
describe('setTwoNumberDecimal()', () => {
  it('tests commas are removed and user value is set', () => {
    const mockEvent = {target: {value: '5.777,'}};
    component.setTwoNumberDecimal(mockEvent);
    expect(component.setTwoNumberDecimal).toHaveBeenCalled();
  });
});

I want to be able to check that, after setTwoNumberDecimal(e) is run:

*

*USER_VAL is equal to '5.777' (that is, the comma has been removed); and

*e.target.value is equal to '5.77' (that is, the last value has been truncated)
The functionality already works for the comma replace and the truncate.

A: Test that the value is what you expect it to be in your mocked event.
describe('setTwoNumberDecimal()', () => {
  it('Should truncate decimal from value', () => {
    const mockEvent = {target: {value: '5.777,'}};
    expect(mockEvent.target.value).toEqual('5.77');
  });
  it('Should remove commas from value', () => {
    const mockEvent = {target: {value: '1,234,567.89,'}};
    expect(mockEvent.target.value).toEqual('1234567.89');
  });
});


text:
Q: Listview updates only after changing screens in flutter So, here is my problem.
Logic:
Get the data from firebase.
Users can update the data, refresh the listview accordingly.
Problem:
Listview DOES update but, only after I change the screen to some other screen and return to the screen with the listview.
Explanantion:
The _postData array is made within the _PostsState.
The data is updated in the array when a user navigates to a new page and comes back with Navigator.pop()
The data is successfully updated and the array size does change but the change in UI is not reflected until screen is changed.
Code:
class Posts extends StatefulWidget {
  const Posts({Key? key}) : super(key: key);

  @override
  _PostsState createState() => _PostsState();
}

class _PostsState extends State<Posts> {
  final DataRepository repository = DataRepository();
  final List<Post> _postData = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      getPosts();
      print('GET POSTS CALLED');
    });
  }

SOME MORE CODE
 SizedBox(
                height: 45.0,
                child: ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all<Color>(Color(0xFF00AC97)),
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                                RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(14.0),
                        ))),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute<void>(
                            builder: (context) => AddPost()),
                      ).then((_) => {setState(() {})}); <- This doesnot work instantly
                    },
                    child: const Text(
                      'Have anything to share? ',
                      style: TextStyle(
                        fontFamily: 'PoppinsLight',
                        fontWeight: FontWeight.w400,
                        fontSize: 20.0,
                        letterSpacing: 0.3,
                      ),
                    )),
              ),

SOME MORE CODE
      ListView.builder(
        shrinkWrap: true,
        key: UniqueKey(),
        physics: NeverScrollableScrollPhysics(),
        itemCount: _postData.length,
        itemBuilder: (context, index) {
          return Card(
            key: UniqueKey(),
            child: Padding(
              padding: const EdgeInsets.all(14.0),
              child: Column(
                children: [

                  Text(_postData[index].postContent.toString(),
                      style: const TextStyle(
                        fontFamily: 'WorkSansLight',
                        fontWeight: FontWeight.w600,
                        fontSize: 15.0,
                        height: 1.75,
                      ))
                ],
              ),
            ),
          );
        },
      )

GETTING NEW DATA
  Future getPosts() async {
    final QuerySnapshot<Map<String, dynamic>> data = await FirebaseFirestore
        .instance
        .collection('posts')
        .orderBy('createdAt', descending: true)
        .get();

    data.docs.forEach((QueryDocumentSnapshot<Map<String, dynamic>> doc) {
      final Post postdata = Post.fromSnapshot(doc);
      setState(() {
        _postData.add(postdata);
      });
    });
  }

A: You should use FutureBuilder Like This:
    FutureBuilder(
    future: getPosts(),
builder: (context,AsyncSnapshot snapshot){
if(!snapshot.hasData)
return Center(child: CircularProgressIndicator());
else{
  ListView.builder(itemBuilder: itemBuilder)
}
  )

A: I figured out the error. Data future is only called within init state. So the UI is not updating.


text:
Q: Calling Python functions from MATLAB using matpy I have just set up my system for matpy (http://algoholic.eu/matpy/), but it still does not seem to work...
Setup:
- Windows 7 64bit
- MATLAB R2014a 64bit
- WinPython 2.7.9.2 64bit
in MATLAB I entered:
>> mex py.cpp '-IC:\Program Files\WinPython-64bit-2.7.9.2\python-2.7.9.amd64\include' '-LC:\Program Files\WinPython-64bit-2.7.9.2\python-2.7.9.amd64\libs'
Building with 'Microsoft Visual C++ 2013 Professional'.
MEX completed successfully.

Now, if I type
>> py_shell
py> print "Hello, World!"
py>

nothing happens. How can I check whether my system is operational? What could be the reason it does not work?

A: Winpython must be in your PATH variable to work well.
maybe should you:

*

*call C:\Program Files\WinPython-64bit-2.7.9.2\python-2.7.9.amd64\scripts\env.bat before calling Matlab ?

*modify your default system to include it.
Hope it helps or will give you clues
The guy said that it was working with python(x,y), also
http://algoholic.eu/matpy/
==> Are you sure it works on 64 bit ?


text:
Q: How to stop interstitial ads showing up after app exit? My app shows interstitial ads in the app and sometimes after the app is closed because of slow internet speed. Showing interstitial ad after the app is closed violates admob rules. How can i stop my interstitial ads from showing ads after app is closed ??

public class des extends AppCompatActivity {

    ImageButton imageView15;
    InterstitialAd mInterstitialAd;
    private InterstitialAd interstitial;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_des);

        AdView mAdView = (AdView) findViewById(R.id.AdView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

                   // Prepare the Interstitial Ad
        interstitial = new InterstitialAd(des.this);
// Insert the Ad Unit ID
        interstitial.setAdUnitId(getString(R.string.intertitial_id));

        interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
        interstitial.setAdListener(new AdListener() {
            public void onAdLoaded() {
                // Call displayInterstitial() function
                displayInterstitial();
            }
        });

        imageView15 = (ImageButton) findViewById(R.id.imageView15);
        imageView15.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentLoadNewActivity = new Intent(des.this,vid.class);
                startActivity(intentLoadNewActivity);
            }
        });

    }

    public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
        if (interstitial.isLoaded()) {
            interstitial.show();
        }
    }

}

A: The problem is that you are showing the add in OnAdLoaded which is not advised.This results in bad behaviour and intercepts when user is doing some other work.SO you should load your ad when the activity starts and then you should show it at a time where user is not effected by checking if it is loaded.
This way you ad wont be shown after user is done with your app and your problem will be solved.

A: You can keep track of the activity lifecycle and then check if the activity is running prior to showing the ad.

*

*Create an instance variable :
private boolean isRunning;

*Keep track of the activity lifecycle :
@Override
protected void onStart() {
    super.onStart();
    isRunning = true;
}

@Override
protected void onStop() {
    super.onStop();
    isRunning = false;
}

*Check if the activity is running before showing the ad :
public void displayInterstitial() {
    // If Ads are loaded and the activity is running, show Interstitial else show nothing.
    if (isRunning && interstitial.isLoaded()) {
        interstitial.show();
    }
}

A: Or, you could use:  system.exit(0); whenever a user wants to exit your app as long as your app doesn't contain any service classes

A: you need to destroy your ad on Activity finish or (Exit application)
try this
@Override
public void onDestroy()
{
    super.onDestroy();
    if (mInterstitialAd != null) {
        mInterstitialAd.destroy();
    }
}


text:
Q: Section headings in the mobile app "Feed" display are unclear The iOS app shows the following sections:
JUST NOW
EARLIER TODAY
YESTERDAY
EARLIER THIS WEEK
EARLIER THIS MONTH

It's unclear what any of these section titles actually mean, and therefore they're not very useful. Is "EARLIER TODAY" an hour ago? Four hours? 12 hours? When does "YESTERDAY" start? My local time zone? UTC? Pacific time? When does the week start? Sunday? Monday? Whose time zone? Why am I seeing things from January in "EARLIER THIS MONTH"? It's February!
What would be more useful would be a section that shows new feed items. So the sections could be:
NEW
ALREADY VIEWED

along with specific date headings in the local time zone (10 FEB, 9 FEB, etc). The "ALREADY VIEWED" heading would be updated to indicate things I've already seen in a previous launch of the app (switching away from the app and back would be a reasonable action to update the ALREADY VIEWED marker).

A: After looking at this more closely, I'll say that the app is doing the right thing.  Just like the site, all times are with respect to UTC. The biggest source of confusion will be when your localized calendar boundaries seem to disagree with UTC boundaries, but that's really unavoidable without localizing everything to a timezone, and we're not going to do that because

*

*the site is all UTC

*it will just replace this confusion with other confusion

As for what those labels mean, I'm more than happy to share.  Here they are:

JUST NOW               < 1 hour
EARLIER TODAY          < 24 hours
YESTERDAY              < 48 hours
EARLIER THIS WEEK      < 168 hours
EARLIER THIS MONTH     < 720 hours (24 * 30)
EARLIER THIS YEAR      < 8760 hours (24 * 365)
A LONG TIME AGO        >= 8760 hours

A: I would support modifying the text as follows for relative time bins so that they don't imply so strongly a day/month/year hard boundary "THIS". By having EARLIER which means near the beginning of the particular time period and THIS MONTH referring to a specific month rather than a relative time span lasting a month.

RECENTLY               < 1 hour
LAST 24 HOURS          < 24 hours
YESTERDAY              < 48 hours
WITHIN A WEEK          < 168 hours
WITHIN A MONTH         < 720 hours (24 * 30)
WITHIN A YEAR          < 8760 hours (24 * 365)
MORE THAN A YEAR AGO   >= 8760 hours

The above terms more closely match what I would expect when looking at events that happened in the past relative to now as opposed to specific week/day/month boundaries.


text:
Q: RWD theme 1.9 attributes.phtml I cannot find the attributes.phtml in my files. I want to edit how the additional tabs content shows. I don't want it to be in table instead to be the same as the description
tab. How should I edit it?
Thanks in advance

A: The Magento rwd theme falls back on the base default theme. So if the attributes.phtml is not in the rwd theme it will be using the one from the base theme. So if you want to edit this I'd  copy it to your themes directory i.e
Copy
{magento_base}app/code/frontend/base/default/template/catalog/product/view/attributes.phtml
To
{magento_base}app/code/frontend/rwd/default/template/catalog/product/view/attributes.phtml
@see link below for a must read.
Magento CE 1.9 and EE 1.14 Responsive Web Design Developer's Guide


text:
Q: flutter geolocation take to much time to get location I have flutter app and it has location required so I get user location on splash but it took more than 5 sec to get location and during this time I use to show splash screen so user thinks app is stuck at this time and they close app so can anyone help me how to find how to get location quickly in flutter.

A: After so many times I make method to get last known location first and if that was empty then I try to get current location with low accuracy it save user time and app run smother


text:
Q: Send HTML file in Apache Camel RouteBuilder I am having HTML file which I want to send as a response for the rest call inside Apache camel RouteBuilder. The code looks like below
public class RestEndpointRouteBuilder extends RouteBuilder {

    @Override
    public void configure() {

        rest("/form")
                .post()
                .produces(MediaType.TEXT_HTML_VALUE)
                .to("file:target/classes/static/form.html");
    }

But, I am getting below error when I call the API
org.apache.camel.component.file.GenericFileOperationFailedException: Cannot write null body to file: target\classes\static\form.html\ID-*****-***-****
    at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:245)
    at org.apache.camel.component.file.GenericFileProducer.writeFile(GenericFileProducer.java:277)
    at org.apache.camel.component.file.GenericFileProducer.processExchange(GenericFileProducer.java:165)
    at org.apache.camel.component.file.GenericFileProducer.process(GenericFileProducer.java:79)
    at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)

Basically, I want to return an HTML file, which is a ReactJS application, alongwith JS minified files. Could someone please help me with this?

A: There are several problems in your code:

*

*The more appropriate HTTP method is rather GET instead of POST

*The file component here is a to endpoint so it is used as a producer, in other words, it will save into the file instead of reading it as you expect.

*The URI of the file component is incorrect, the URI format is file:directoryName[?options] which means that target/classes/static/form.html is supposed to be a directory, not a file.

What you try to achieve could be done as follow:
rest("/form")
    // Fix #1: Use "get" instead of "post"
    .get()
    .produces(MediaType.TEXT_HTML)
    .to("direct:fileContent");

from("direct:fileContent")
     // Fix #2: Use "pollEnrich" to use the file component as a
     // consumer to read the file
     // Fix #3: Fix the URI to have the directory name on one side
     // and the file name on the other side
    .pollEnrich("file:target/classes/static?fileName=form.html");

NB: Even if what I described above will work, please note that a rest endpoint is not meant to be used for static content, you are supposed to use a reverse proxy instead.


text:
Q: Multiple tables with same structure - Sqlite I have a table called Messages.But I want to create a separate table for separate users.
ex:
if my username is Ciddarth
I want a table named Ciddarth with the same structure as Messages
public class DbHandler extends SQLiteOpenHelper {

SQLiteDatabase db;
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "SocialNetwork";

// Contacts table name
private String TABLE_MESSAGES = "Messages";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_MESSAGE = "message";
private static final String KEY_SEND = "send";
private static final String KEY_STATUS = "status";
private static final String KEY_TIME = "time";

public DbHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    //TABLE_MESSAGES=name;
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    this.db=db;
    String CREATE_MESSAGE_TABLE = "CREATE TABLE " + TABLE_MESSAGES + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_MESSAGE + " MEDIUMTEXT,"
            + KEY_SEND + " TEXT," + KEY_STATUS + " INTEGER,"+KEY_TIME+" DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME'))"+")";
    db.execSQL(CREATE_MESSAGE_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addMessage(Message message) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_MESSAGE, message.getMessage());
    values.put(KEY_SEND, message.getSend());
    values.put(KEY_STATUS, message.getStatus());

    // Inserting Row
    db.insert(TABLE_MESSAGES, null, values);
    db.close(); // Closing database connection
}

// Getting single contact
Message getMessage(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_MESSAGES, new String[] { KEY_ID,
                    KEY_MESSAGE, KEY_SEND }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Message message = new Message(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(4),Integer.parseInt(cursor.getString(3)));
    return message;

}

// Getting All Contacts
public List<Message> getAllContacts() {
    List<Message> msgList = new ArrayList<Message>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_MESSAGES;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Message message = new Message();
            message.setID(Integer.parseInt(cursor.getString(0)));
            message.setMessage(cursor.getString(1));
            message.setSend(cursor.getString(2));
            message.setStatus(cursor.getInt(3));
            message.setTime(cursor.getString(4));
            // Adding contact to list
            msgList.add(message);
        } while (cursor.moveToNext());
    }

    // return contact list
    return msgList;
}

// Updating single contact
public int updateMessage(Message message) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_MESSAGE, message.getMessage());
    values.put(KEY_SEND, message.getSend());

    // updating row
    return db.update(TABLE_MESSAGES, values, KEY_ID + " = ?",
            new String[] { String.valueOf(message.getID()) });
}

// Deleting single contact
public void deleteMessage(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_MESSAGES, KEY_ID + " = ?",
            new String[] { String.valueOf(id) });
    db.close();
}

// Getting contacts Count
public int getMessageCount() {
    String countQuery = "SELECT  * FROM " + TABLE_MESSAGES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

public void deleteAll()
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from "+ TABLE_MESSAGES);
    db.close();
}

public void deleteTable()
{
    SQLiteDatabase db = this.getReadableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
    db.close();
}

public void changeStatus(int status,int id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(KEY_STATUS,status);
    db.update(TABLE_MESSAGES, cv, "id="+id, null);
    db.close();
}
}

Now I want to change the TABLES_MESSAGES related to the user how to I do this??
If I change the value of TABLE_MESSAGES to Ciddarth it still doesn't work.

A: Make a seperate method...
`createNewTable(String tablename){
     SqliteOpenDatabase db = this.getWriteableDatabase();
     String CREATE_MESSAGE_TABLE = "CREATE TABLE " + tablename + "("
         + KEY_ID + " INTEGER PRIMARY KEY," + KEY_MESSAGE + " MEDIUMTEXT,"
         + KEY_SEND + " TEXT," + KEY_STATUS + " INTEGER,"+KEY_TIME+
         "DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME'))"+")";
 db.execSQL(CREATE_MESSAGE_TABLE);`

and add String tablename to other CRUD methods.
Edit: Forgot  this.getWritableDatabase();