id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_3900
|
cast(convert(int, isnull(b.temp,0)) as varchar(500))
and then I would like to output values as written below for example
1 as 001
12 as 012
123 as 123
-1 as -001
-15 as -015
-234 as -234
and if length of the integer value is more than 3 then do not display any value or remove it.
If integer has Minus(-) sign then it is not part of the length
so -001 is consider as length 3
so 001 and -001 is acceptable as length 3
How can I do that?
A: It looks like you are trying to 0 pad numbers in a range. This is one way I do it:
select (case when val between 0 and 999
then right('000'+cast(<col> as varchar(100)), 3)
when val between -999 and 0
then '-'+right('000'+cast(abs(<col>) as varchar(100)), 3)
else ''
end)
from t
A: Solution below works. Thanks
declare @num1 as varchar(50)
set @num1 = '1'
select (case
when @num1 between 0 and 999 then right('000'+cast(@num1 as varchar(100)), 3)
when @num1 between -999 and 0 then '-'+right('000'+cast(abs(@num1) as varchar(100)), 3)
else ''
end) as t
A: There really is no efficient way to do this, but I understand there are situations where this needs to be done. I would probably go about it with something like this turned into a function.
DECLARE @myInt as INT
SET @myInt = -9
DECLARE @padding AS VARCHAR(1)
SET @padding = '0'
DECLARE @length AS INT
SET @length = 3 - LEN(ABS(@myInt))
DECLARE @result AS VARCHAR(5)
SET @result = REPLICATE(@padding, @length) + cast(ABS(@myInt) as VARCHAR(3))
IF @myInt < 0
SET @result = '-' + @result
SELECT @result
This really should be done in code and not sql.
| |
doc_3901
|
https://github.com/fireflysemantics/is
I see that the doc folder that typedoc generated is in the gh-pages branch, however when I go to:
https://fireflysemantics.github.io/is/doc/index.html
I get a 404, but the index.html pages is in the gh-pages branch at that location:
https://github.com/fireflysemantics/is/blob/gh-pages/doc/index.html
Any idea why it's not rendering?
A: OK - Got it. I had to configure the publishing source for gh-pages.
Note that for typedoc we also need to add a .nojekyll file, so that gh-pages does not ignore files staring with _. See my .travis.yml file for how I did this.
| |
doc_3902
|
i use pycharm and i have the some error when i try to run python script from the ubuntu terminal.
the error :
*** Error in `/usr/bin/python2.7': corrupted double-linked list: 0x0b83c880 ***
the error message :
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x67377)[0xb764b377]
/lib/i386-linux-gnu/libc.so.6(+0x6d2f7)[0xb76512f7]
/lib/i386-linux-gnu/libc.so.6(+0x6e2f1)[0xb76522f1]
/usr/lib/i386-linux-gnu/libstdc++.so.6(_ZdlPv+0x18)[0xb6ba9d88]
/usr/lib/libgdal.so.1(_ZN15GDALMajorObjectD0Ev+0x22)[0xb075a582]
/usr/lib/libgdal.so.1(GDALClose+0x77)[0xb074d747]
/usr/lib/qgis/plugins/libgdalprovider.so(+0xa930)[0xa4888930]
/usr/lib/qgis/plugins/libgdalprovider.so(+0xaafa)[0xa4888afa]
/usr/lib/libqgis_core.so.2.18.3(_ZN13QgsRasterPipeD1Ev+0x75)[0xb3d6a7d5]
/usr/lib/libqgis_core.so.2.18.3(_ZN14QgsRasterLayerD1Ev+0x2f)[0xb3d5cd0f]
/usr/lib/python2.7/dist-packages/qgis/_core.i386-linux-gnu.so(_ZN17sipQgsRasterLayerD1Ev+0x3b)[0xb489dd2b]
/usr/lib/python2.7/dist-packages/qgis/_core.i386-linux-gnu.so(_ZN17sipQgsRasterLayerD0Ev+0x1a)[0xb489dd5a]
/usr/lib/python2.7/dist-packages/qgis/_core.i386-linux-gnu.so(+0x43df45)[0xb4883f45]
/usr/lib/python2.7/dist-packages/qgis/_core.i386-linux-gnu.so(+0x43df8a)[0xb4883f8a]
/usr/lib/python2.7/dist-packages/sip.i386-linux-gnu.so(+0x5d49)[0xb724dd49]
/usr/lib/python2.7/dist-packages/sip.i386-linux-gnu.so(+0xc19b)[0xb725419b]
/usr/bin/python2.7[0x8144aad]
/usr/bin/python2.7[0x80fd127]
/usr/bin/python2.7(PyDict_SetItem+0x478)[0x80e9268]
/usr/bin/python2.7(_PyModule_Clear+0xba)[0x8149a1a]
/usr/bin/python2.7(PyImport_Cleanup+0x37a)[0x81495ca]
/usr/bin/python2.7(Py_Finalize+0x99)[0x8147399]
/usr/bin/python2.7(Py_Main+0x4bd)[0x80e639d]
/usr/bin/python2.7(main+0x26)[0x80e5ec6]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf7)[0xb75fc637]
/usr/bin/python2.7[0x80e5dc8]
======= Memory map: ========
08048000-0838f000 r-xp 00000000 08:01 1583892 /usr/bin/python2.7
08390000-08391000 r--p 00347000 08:01 1583892 /usr/bin/python2.7
08391000-083f1000 rw-p 00348000 08:01 1583892 /usr/bin/python2.7
083f1000-08406000 rw-p 00000000 00:00 0
0a0f7000-0ba69000 rw-p 00000000 00:00 0 [heap]
a03e0000-a03eb000 r-xp 00000000 08:01 1049930 /lib/i386-linux-gnu/libnss_files-2.23.so
a03eb000-a03ec000 r--p 0000a000 08:01 1049930 /lib/i386-linux-gnu/libnss_files-2.23.so
a03ec000-a03ed000 rw-p 0000b000 08:01 1049930 /lib/i386-linux-gnu/libnss_files-2.23.so
a03ed000-a03f3000 rw-p 00000000 00:00 0
a03f3000-a03fe000 r-xp 00000000 08:01 1048664 /lib/i386-linux-gnu/libnss_nis-2.23.so
a03fe000-a03ff000 r--p 0000a000 08:01 1048664 /lib/i386-linux-gnu/libnss_nis-2.23.so
a03ff000-a0400000 rw-p 0000b000 08:01 1048664 /lib/i386-linux-gnu/libnss_nis-2.23.so
a0400000-a0421000 rw-p 00000000 00:00 0
a0421000-a0500000 ---p 00000000 00:00 0
a0509000-a0520000 r-xp 00000000 08:01 1048674 /lib/i386-linux-gnu/libnsl-2.23.so
a0520000-a0521000 r--p 00016000 08:01 1048674 /lib/i386-linux-gnu/libnsl-2.23.so
a0521000-a0522000 rw-p 00017000 08:01 1048674 /lib/i386-linux-gnu/libnsl-2.23.so
a0522000-a0524000 rw-p 00000000 00:00 0
a0524000-a052c000 r-xp 00000000 08:01 1048675 /lib/i386-linux-gnu/libnss_compat-2.23.so
a052c000-a052d000 r--p 00007000 08:01 1048675 /lib/i386-linux-gnu/libnss_compat-2.23.so
a052d000-a052e000 rw-p 00008000 08:01 1048675 /lib/i386-linux-gnu/libnss_compat-2.23.so
a054a000-a054b000 ---p 00000000 00:00 0
a054b000-a10cb000 rw-p 00000000 00:00 0
a10cb000-a10d4000 r-xp 00000000 08:01 150141 /usr/lib/i386-linux-gnu/qt4/plugins/iconengines/libqsvgicon.so
a10d4000-a10d5000 r--p 00008000 08:01 150141 /usr/lib/i386-linux-gnu/qt4/plugins/iconengines/libqsvgicon.so
a10d5000-a10d6000 rw-p 00009000 08:01 150141 /usr/lib/i386-linux-gnu/qt4/plugins/iconengines/libqsvgicon.so
a10d6000-a1296000 rw-p 00000000 00:00 0
a1296000-a12a5000 r-xp 00000000 08:01 283552 /usr/lib/python2.7/dist-packages/scipy/stats/mvn.i386-linux-gnu.so
a12a5000-a12a6000 ---p 0000f000 08:01 283552 /usr/lib/python2.7/dist-packages/scipy/stats/mvn.i386-linux-gnu.so
a12a6000-a12a7000 r--p 0000f000 08:01 283552 /usr/lib/python2.7/dist-packages/scipy/stats/mvn.i386-linux-gnu.so
a12a7000-a12a8000 rw-p 00010000 08:01 283552 /usr/lib/python2.7/dist-packages/scipy/stats/mvn.i386-linux-gnu.so
a12a8000-a139f000 rw-p 00000000 00:00 0
a139f000-a13a8000 r-xp 00000000 08:01 283553 /usr/lib/python2.7/dist-packages/scipy/stats/statlib.i386-linux-gnu.so
a13a8000-a13a9000 ---p 00009000 08:01 283553 /usr/lib/python2.7/dist-packages/scipy/stats/statlib.i386-linux-gnu.so
a13a9000-a13aa000 r--p 00009000 08:01 283553 /usr/lib/python2.7/dist-packages/scipy/stats/statlib.i386-linux-gnu.so
a13aa000-a13ab000 rw-p 0000a000 08:01 283553 /usr/lib/python2.7/dist-packages/scipy/stats/statlib.i386-linux-gnu.so
a13ab000-a13eb000 rw-p 00000000 00:00 0
a13eb000-a13f8000 r-xp 00000000 08:01 283548 /usr/lib/python2.7/dist-packages/scipy/stats/_rank.i386-linux-gnu.so
a13f8000-a13f9000 r--p 0000c000 08:01 283548 /usr/lib/python2.7/dist-packages/scipy/stats/_rank.i386-linux-gnu.so
a13f9000-a13fb000 rw-p 0000d000 08:01 283548 /usr/lib/python2.7/dist-packages/scipy/stats/_rank.i386-linux-gnu.so
a13fb000-a147b000 rw-p 00000000 00:00 0
a147b000-a148e000 r-xp 00000000 08:01 283509 /usr/lib/python2.7/dist-packages/scipy/stats/vonmises_cython.i386-linux-gnu.so
a148e000-a148f000 r--p 00012000 08:01 283509 /usr/lib/python2.7/dist-packages/scipy/stats/vonmises_cython.i386-linux-gnu.so
a148f000-a1490000 rw-p 00013000 08:01 283509 /usr/lib/python2.7/dist-packages/scipy/stats/vonmises_cython.i386-linux-gnu.so
a1490000-a1510000 rw-p 00000000 00:00 0
a1510000-a1519000 r-xp 00000000 08:01 534502 /usr/lib/python2.7/dist-packages/scipy/optimize/_nnls.i386-linux-gnu.so
a1519000-a151a000 r--p 00008000 08:01 534502 /usr/lib/python2.7/dist-packages/scipy/optimize/_nnls.i386-linux-gnu.so
a151a000-a151b000 rw-p 00009000 08:01 534502 /usr/lib/python2.7/dist-packages/scipy/optimize/_nnls.i386-linux-gnu.so
a151b000-a1539000 r-xp 00000000 08:01 534537 /usr/lib/python2.7/dist-packages/scipy/optimize/_lsq/givens_elimination.i386-linux-gnu.so
a1539000-a153a000 r--p 0001d000 08:01 534537 /usr/lib/python2.7/dist-packages/scipy/optimize/_lsq/givens_elimination.i386-linux-gnu.so
a153a000-a153c000 rw-p 0001e000 08:01 534537 /usr/lib/python2.7/dist-packages/scipy/optimize/_lsq/givens_elimination.i386-linux-gnu.so
a153c000-a1562000 r-xp 00000000 08:01 534554 /usr/lib/python2.7/dist-packages/scipy/optimize/_group_columns.i386-linux-gnu.so
a1562000-a1563000 r--p 00025000 08:01 534554 /usr/lib/python2.7/dist-packages/scipy/optimize/_group_columns.i386-linux-gnu.so
a1563000-a1565000 rw-p 00026000 08:01 534554 /usr/lib/python2.7/dist-packages/scipy/optimize/_group_columns.i386-linux-gnu.so
a1565000-a157b000 r-xp 00000000 08:01 534540 /usr/lib/python2.7/dist-packages/scipy/optimize/_minpack.i386-linux-gnu.so
a157b000-a157c000 r--p 00015000 08:01 534540 /usr/lib/python2.7/dist-packages/scipy/optimize/_minpack.i386-linux-gnu.so
a157c000-a157d000 rw-p 00016000 08:01 534540 /usr/lib/python2.7/dist-packages/scipy/optimize/_minpack.i386-linux-gnu.so
a157d000-a1592000 r-xp 00000000 08:01 534543 /usr/lib/python2.7/dist-packages/scipy/optimize/_slsqp.i386-linux-gnu.so
a1592000-a1593000 r--p 00014000 08:01 534543 /usr/lib/python2.7/dist-packages/scipy/optimize/_slsqp.i386-linux-gnu.so
a1593000-a1594000 rw-p 00015000 08:01 534543 /usr/lib/python2.7/dist-packages/scipy/optimize/_slsqp.i386-linux-gnu.so
a1594000-a15ad000 r-xp 00000000 08:01 534495 /usr/lib/python2.7/dist-packages/scipy/optimize/_cobyla.i386-linux-gnu.so
a15ad000-a15ae000 r--p 00018000 08:01 534495 /usr/lib/python2.7/dist-packages/scipy/optimize/_cobyla.i386-linux-gnu.so
a15ae000-a15af000 rw-p 00019000 08:01 534495 /usr/lib/python2.7/dist-packages/scipy/optimize/_cobyla.i386-linux-gnu.so
a15af000-a15b7000 r-xp 00000000 08:01 534499 /usr/lib/python2.7/dist-packages/scipy/optimize/moduleTNC.i386-linux-gnu.so
a15b7000-a15b8000 r--p 00007000 08:01 534499 /usr/lib/python2.7/dist-packages/scipy/optimize/moduleTNC.i386-linux-gnu.so
a15b8000-a15b9000 rw-p 00008000 08:01 534499 /usr/lib/python2.7/dist-packages/scipy/optimize/moduleTNC.i386-linux-gnu.so
a15b9000-a15f9000 rw-p 00000000 00:00 0
a15f9000-a1689000 r-xp 00000000 08:01 412052 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/eigen/arpack/_arpack.i386-linux-gnu.so
a1689000-a168a000 r--p 0008f000 08:01 412052 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/eigen/arpack/_arpack.i386-linux-gnu.so
a168a000-a1692000 rw-p 00090000 08:01 412052 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/eigen/arpack/_arpack.i386-linux-gnu.so
a1692000-a16e9000 r-xp 00000000 08:01 412020 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/dsolve/_superlu.i386-linux-gnu.so
a16e9000-a16ea000 r--p 00056000 08:01 412020 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/dsolve/_superlu.i386-linux-gnu.so
a16ea000-a16eb000 rw-p 00057000 08:01 412020 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/dsolve/_superlu.i386-linux-gnu.so
a16eb000-a171f000 r-xp 00000000 08:01 412028 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/isolve/_iterative.i386-linux-gnu.so
a171f000-a1720000 r--p 00033000 08:01 412028 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/isolve/_iterative.i386-linux-gnu.so
a1720000-a1726000 rw-p 00034000 08:01 412028 /usr/lib/python2.7/dist-packages/scipy/sparse/linalg/isolve/_iterative.i386-linux-gnu.so
a1726000-a1727000 rw-p 00000000 00:00 0
a1727000-a1766000 r-xp 00000000 08:01 412005 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_reordering.i386-linux-gnu.so
a1766000-a1767000 ---p 0003f000 08:01 412005 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_reordering.i386-linux-gnu.so
a1767000-a1768000 r--p 0003f000 08:01 412005 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_reordering.i386-linux-gnu.so
a1768000-a176c000 rw-p 00040000 08:01 412005 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_reordering.i386-linux-gnu.so
a176c000-a1790000 r-xp 00000000 08:01 412007 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_min_spanning_tree.i386-linux-gnu.so
a1790000-a1791000 r--p 00023000 08:01 412007 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_min_spanning_tree.i386-linux-gnu.so
a1791000-a1794000 rw-p 00024000 08:01 412007 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_min_spanning_tree.i386-linux-gnu.so
a1794000-a1795000 rw-p 00000000 00:00 0
a1795000-a17b4000 r-xp 00000000 08:01 411990 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_traversal.i386-linux-gnu.so
a17b4000-a17b5000 r--p 0001e000 08:01 411990 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_traversal.i386-linux-gnu.so
a17b5000-a17ba000 rw-p 0001f000 08:01 411990 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_traversal.i386-linux-gnu.so
a17ba000-a17d9000 r-xp 00000000 08:01 411992 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_tools.i386-linux-gnu.so
a17d9000-a17da000 r--p 0001e000 08:01 411992 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_tools.i386-linux-gnu.so
a17da000-a17de000 rw-p 0001f000 08:01 411992 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_tools.i386-linux-gnu.so
a17de000-a1812000 r-xp 00000000 08:01 412004 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_shortest_path.i386-linux-gnu.so
a1812000-a1813000 r--p 00033000 08:01 412004 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_shortest_path.i386-linux-gnu.so
a1813000-a1818000 rw-p 00034000 08:01 412004 /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_shortest_path.i386-linux-gnu.so
a1818000-a1858000 rw-p 00000000 00:00 0
a1858000-a18b3000 r-xp 00000000 08:01 283597 /usr/lib/python2.7/dist-packages/scipy/sparse/_csparsetools.i386-linux-gnu.so
a18b3000-a18b4000 r--p 0005a000 08:01 283597 /usr/lib/python2.7/dist-packages/scipy/sparse/_csparsetools.i386-linux-gnu.so
a18b4000-a18b8000 rw-p 0005b000 08:01 283597 /usr/lib/python2.7/dist-packages/scipy/sparse/_csparsetools.i386-linux-gnu.so
a18b8000-a1bcd000 r-xp 00000000 08:01 283577 /usr/lib/python2.7/dist-packages/scipy/sparse/_sparsetools.i386-linux-gnu.so
a1bcd000-a1bce000 r--p 00314000 08:01 283577 /usr/lib/python2.7/dist-packages/scipy/sparse/_sparsetools.i386-linux-gnu.so
a1bce000-a1bcf000 rw-p 00315000 08:01 283577 /usr/lib/python2.7/dist-packages/scipy/sparse/_sparsetools.i386-linux-gnu.so
a1bcf000-a1beb000 r-xp 00000000 08:01 534539 /usr/lib/python2.7/dist-packages/scipy/optimize/_lbfgsb.i386-linux-gnu.so
a1beb000-a1bec000 r--p 0001b000 08:01 534539 /usr/lib/python2.7/dist-packages/scipy/optimize/_lbfgsb.i386-linux-gnu.so
a1bec000-a1bed000 rw-p 0001c000 08:01 534539 /usr/lib/python2.7/dist-packages/scipy/optimize/_lbfgsb.i386-linux-gnu.so
a1bed000-a1c2d000 rw-p 00000000 00:00 0
a1c2d000-a1c36000 r-xp 00000000 08:01 534548 /usr/lib/python2.7/dist-packages/scipy/optimize/minpack2.i386-linux-gnu.so
a1c36000-a1c37000 r--p 00008000 08:01 534548 /usr/lib/python2.7/dist-packages/scipy/optimize/minpack2.i386-linux-gnu.so
a1c37000-a1c38000 rw-p 00009000 08:01 534548 /usr/lib/python2.7/dist-packages/scipy/optimize/minpack2.i386-linux-gnu.so
a1c38000-a1c5d000 r-xp 00000000 08:01 534392 /usr/lib/python2.7/dist-packages/scipy/integrate/lsoda.i386-linux-gnu.so
a1c5d000-a1c5e000 r--p 00024000 08:01 534392 /usr/lib/python2.7/dist-packages/scipy/integrate/lsoda.i386-linux-gnu.so
a1c5e000-a1c5f000 rw-p 00025000 08:01 534392 /usr/lib/python2.7/dist-packages/scipy/integrate/lsoda.i386-linux-gnu.so
a1c5f000-a1c60000 rw-p 00000000 00:00 0
a1c60000-a1c75000 r-xp 00000000 08:01 534374 /usr/lib/python2.7/dist-packages/scipy/integrate/_dop.i386-linux-gnu.so
a1c75000-a1c76000 r--p 00014000 08:01 534374 /usr/lib/python2.7/dist-packages/scipy/integrate/_dop.i386-linux-gnu.so
a1c76000-a1c78000 rw-p 00015000 08:01 534374 /usr/lib/python2.7/dist-packages/scipy/integrate/_dop.i386-linux-gnu.so
a1c78000-a1ca3000 r-xp 00000000 08:01 534376 /usr/lib/python2.7/dist-packages/scipy/integrate/vode.i386-linux-gnu.so
a1ca3000-a1ca4000 r--p 0002a000 08:01 534376 /usr/lib/python2.7/dist-packages/scipy/integrate/vode.i386-linux-gnu.so
a1ca4000-a1ca5000 rw-p 0002b000 08:01 534376 /usr/lib/python2.7/dist-packages/scipy/integrate/vode.i386-linux-gnu.so
a1ca5000-a1ce6000 rw-p 00000000 00:00 0
a1ce6000-a1d00000 r-xp 00000000 08:01 534375 /usr/lib/python2.7/dist-packages/scipy/integrate/_quadpack.i386-linux-gnu.so
a1d00000-a1d01000 r--p 00019000 08:01 534375 /usr/lib/python2.7/dist-packages/scipy/integrate/_quadpack.i386-linux-gnu.so
a1d01000-a1d02000 rw-p 0001a000 08:01 534375 /usr/lib/python2.7/dist-packages/scipy/integrate/_quadpack.i386-linux-gnu.so
a1d02000-a1d23000 r-xp 00000000 08:01 534393 /usr/lib/python2.7/dist-packages/scipy/integrate/_odepack.i386-linux-gnu.so
a1d23000-a1d24000 r--p 00020000 08:01 534393 /usr/lib/python2.7/dist-packages/scipy/integrate/_odepack.i386-linux-gnu.so
a1d24000-a1d25000 rw-p 00021000 08:01 534393 /usr/lib/python2.7/dist-packages/scipy/integrate/_odepack.i386-linux-gnu.so
a1d25000-a1d36000 r-xp 00000000 08:01 701893 /usr/lib/python2.7/dist-packages/scipy/special/_ellip_harm_2.i386-linux-gnu.so
a1d36000-a1d37000 r--p 00010000 08:01 701893 /usr/lib/python2.7/dist-packages/scipy/special/_ellip_harm_2.i386-linux-gnu.so
a1d37000-a1d38000 rw-p 00011000 08:01 701893 /usr/lib/python2.7/dist-packages/scipy/special/_ellip_harm_2.i386-linux-gnu.so
a1d38000-a1dd4000 r-xp 00000000 08:01 701842 /usr/lib/python2.7/dist-packages/scipy/linalg/cython_lapack.i386-linux-gnu.so
a1dd4000-a1dd5000 r--p 0009b000 08:01 701842 /usr/lib/python2.7/dist-packages/scipy/linalg/cython_lapack.i386-linux-gnu.so
a1dd5000-a1dda000 rw-p 0009c000 08:01 701842 /usr/lib/python2.7/dist-packages/scipy/linalg/cython_lapack.i386-linux-gnu.so
a1dda000-a1e0f000 r-xp 00000000 08:01 701852 /usr/lib/python2.7/dist-packages/scipy/linalg/cython_blas.i386-linux-gnu.so
a1e0f000-a1e10000 r--p 00034000 08:01 701852 /usr/lib/python2.7/dist-packages/scipy/linalg/cython_blas.i386-linux-gnu.so
a1e10000-a1e13000 rw-p 00035000 08:01 701852 /usr/lib/python2.7/dist-packages/scipy/linalg/cython_blas.i386-linux-gnu.so
a1e13000-a1e5d000 r-xp 00000000 08:01 701797 /usr/lib/python2.7/dist-packages/scipy/linalg/_decomp_update.i386-linux-gnu.so
a1e5d000-a1e5e000 r--p 00049000 08:01 701797 /usr/lib/python2.7/dist-packages/scipy/linalg/_decomp_update.i386-linux-gnu.so
a1e5e000-a1e67000 rw-p 0004a000 08:01 701797 /usr/lib/python2.7/dist-packages/scipy/linalg/_decomp_update.i386-linux-gnu.so
a1e67000-a1e97000 r-xp 00000000 08:01 701803 /usr/lib/python2.7/dist-packages/scipy/linalg/_solve_toeplitz.i386-linux-gnu.so
a1e97000-a1e98000 r--p 0002f000 08:01 701803 /usr/lib/python2.7/dist-packages/scipy/linalg/_solve_toeplitz.i386-linux-gnu.so
a1e98000-a1e9b000 rw-p 00030000 08:01 701803 /usr/lib/python2.7/dist-packages/scipy/linalg/_solve_toeplitz.i386-linux-gnu.so
a1e9b000-a1edb000 rw-p 00000000 00:00 0
a1edb000-a1ee8000 r-xp 00000000 08:01 701813 /usr/lib/python2.7/dist-packages/scipy/linalg/_flinalg.i386-linux-gnu.so
a1ee8000-a1ee9000 r--p 0000c000 08:01 701813 /usr/lib/python2.7/dist-packages/scipy/linalg/_flinalg.i386-linux-gnu.so
a1ee9000-a1eeb000 rw-p 0000d000 08:01 701813 /usr/lib/python2.7/dist-packages/scipy/linalg/_flinalg.i386-linux-gnu.so
a1eeb000-a1f92000 r-xp 00000000 08:01 701847 /usr/lib/python2.7/dist-packages/scipy/linalg/_flapack.i386-linux-gnu.so
a1f92000-a1f93000 r--p 000a6000 08:01 701847 /usr/lib/python2.7/dist-packages/scipy/linalg/_flapack.i386-linux-gnu.so
a1f93000-a1fc1000 rw-p 000a7000 08:01 701847 /usr/lib/python2.7/dist-packages/scipy/linalg/_flapack.i386-linux-gnu.so
a1fc1000-a200a000 r-xp 00000000 08:01 701814 /usr/lib/python2.7/dist-packages/scipy/linalg/_fblas.i386-linux-gnu.so
a200a000-a200b000 r--p 00048000 08:01 701814 /usr/lib/python2.7/dist-packages/scipy/linalg/_fblas.i386-linux-gnu.so
a200b000-a201f000 rw-p 00049000 08:01 701814 /usr/lib/python2.7/dist-packages/scipy/linalg/_fblas.i386-linux-gnu.so
a201f000-a20b6000 r-xp 00000000 08:01 701913 /usr/lib/python2.7/dist-packages/scipy/special/specfun.i386-linux-gnu.so
a20b6000-a20b7000 r--p 00096000 08:01 701913 /usr/lib/python2.7/dist-packages/scipy/special/specfun.i386-linux-gnu.so
a20b7000-a20bc000 rw-p 00097000 08:01 701913 /usr/lib/python2.7/dist-packages/scipy/special/specfun.i386-linux-gnu.so
a20bc000-a20d0000 r-xp 00000000 08:01 701917 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs_cxx.i386-linux-gnu.so
a20d0000-a20d1000 r--p 00013000 08:01 701917 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs_cxx.i386-linux-gnu.so
a20d1000-a20d2000 rw-p 00014000 08:01 701917 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs_cxx.i386-linux-gnu.so
a20d2000-a21ea000 r-xp 00000000 08:01 701916 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs.i386-linux-gnu.so
a21ea000-a21eb000 ---p 00118000 08:01 701916 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs.i386-linux-gnu.so
a21eb000-a21ec000 r--p 00118000 08:01 701916 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs.i386-linux-gnu.so
a21ec000-a21ff000 rw-p 00119000 08:01 701916 /usr/lib/python2.7/dist-packages/scipy/special/_ufuncs.i386-linux-gnu.so
a21ff000-a22c2000 rw-p 00000000 00:00 0
a22c2000-a2307000 r-xp 00000000 08:01 147207 /usr/lib/python2.7/dist-packages/matplotlib/backends/_backend_agg.i386-linux-gnu.so
a2307000-a2308000 r--p 00044000 08:01 147207 /usr/lib/python2.7/dist-packages/matplotlib/backends/_backend_agg.i386-linux-gnu.so
a2308000-a2309000 rw-p 00045000 08:01 147207 /usr/lib/python2.7/dist-packages/matplotlib/backends/_backend_agg.i386-linux-gnu.so
a2309000-a23ca000 rw-p 00000000 00:00 0
a23ca000-a242b000 r-xp 00000000 08:01 147376 /usr/lib/python2.7/dist-packages/matplotlib/_qhull.i386-linux-gnu.so
a242b000-a242c000 r--p 00060000 08:01 147376 /usr/lib/python2.7/dist-packages/matplotlib/_qhull.i386-linux-gnu.so
a242c000-a242d000 rw-p 00061000 08:01 147376 /usr/lib/python2.7/dist-packages/matplotlib/_qhull.i386-linux-gnu.so
a242d000-a242e000 rw-p 00000000 00:00 0
a242e000-a2447000 r-xp 00000000 08:01 147399 /usr/lib/python2.7/dist-packages/matplotlib/_tri.i386-linux-gnu.so
a2447000-a2448000 r--p 00018000 08:01 147399 /usr/lib/python2.7/dist-packages/matplotlib/_tri.i386-linux-gnu.so
a2448000-a2449000 rw-p 00019000 08:01 147399 /usr/lib/python2.7/dist-packages/matplotlib/_tri.i386-linux-gnu.so
a2449000-a2509000 rw-p 00000000 00:00 0
a2509000-a252f000 r-xp 00000000 08:01 147142 /usr/lib/python2.7/dist-packages/matplotlib/_image.i386-linux-gnu.so
a252f000-a2530000 r--p 00025000 08:01 147142 /usr/lib/python2.7/dist-packages/matplotlib/_image.i386-linux-gnu.so
a2530000-a2531000 rw-p 00026000 08:01 147142 /usr/lib/python2.7/dist-packages/matplotlib/_image.i386-linux-gnu.so
a2531000-a25b2000 rw-p 00000000 00:00 0
a25b2000-a25bf000 r-xp 00000000 08:01 147249 /usr/lib/python2.7/dist-packages/matplotlib/_contour.i386-linux-gnu.so
a25bf000-a25c0000 r--p 0000c000 08:01 147249 /usr/lib/python2.7/dist-packages/matplotlib/_contour.i386-linux-gnu.so
a25c0000-a25c1000 rw-p 0000d000 08:01 147249 /usr/lib/python2.7/dist-packages/matplotlib/_contour.i386-linux-gnu.so
a25c1000-a260c000 r-xp 00000000 08:01 146816 /usr/lib/python2.7/dist-packages/PIL/_imaging.i386-linux-gnu.so
a260c000-a260e000 r--p 0004a000 08:01 146816 /usr/lib/python2.7/dist-packages/PIL/_imaging.i386-linux-gnu.so
a260e000-a2610000 rw-p 0004c000 08:01 146816 /usr/lib/python2.7/dist-packages/PIL/_imaging.i386-linux-gnu.so
a2610000-a2690000 rw-p 00000000 00:00 0
a2690000-a26a1000 r-xp 00000000 08:01 147230 /usr/lib/python2.7/dist-packages/matplotlib/ft2font.i386-linux-gnu.so
a26a1000-a26a2000 ---p 00011000 08:01 147230 /usr/lib/python2.7/dist-
bf8e6000-bf907000 rw-p 00000000 00:00 0 [stack]
A: I met a similar issue when running an web application in uwsgi + django, which was to upload files to an external FTP server.
after digging into the repo steps, I found that this issue only happened in threading context, this is my uwsgi threads line:
threads = 2
after commenting out this line, it was fixed.
| |
doc_3903
|
AttributeError: '_MultiProcessingDataLoaderIter' object has no attribute 'next'
the code I use is:
class WineDataset(Dataset):
def __init__(self):
# Initialize data, download, etc.
# read with numpy or pandas
xy = np.loadtxt('./data/wine.csv', delimiter=',', dtype=np.float32, skiprows=1)
self.n_samples = xy.shape[0]
# here the first column is the class label, the rest are the features
self.x_data = torch.from_numpy(xy[:, 1:]) # size [n_samples, n_features]
self.y_data = torch.from_numpy(xy[:, [0]]) # size [n_samples, 1]
# support indexing such that dataset[i] can be used to get i-th sample
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
# we can call len(dataset) to return the size
def __len__(self):
return self.n_samples
dataset = WineDataset()
train_loader = DataLoader(dataset=dataset,
batch_size=4,
shuffle=True,
num_workers=2)
I tried to make the num_workers=0, still have the same error.
Python version 3.8.9
PyTorch version 1.13.0
A: I too faced the same issue, when i tried to call the next() method as follows
dataiter = iter(dataloader)
data = dataiter.next()
You need to use the following instead and it works perfectly:
dataiter = iter(dataloader)
data = next(dataiter)
Finally your code should look like follows:
class WineDataset(Dataset):
def __init__(self):
# Initialize data, download, etc.
# read with numpy or pandas
xy = np.loadtxt('./data/wine.csv', delimiter=',', dtype=np.float32, skiprows=1)
self.n_samples = xy.shape[0]
# here the first column is the class label, the rest are the features
self.x_data = torch.from_numpy(xy[:, 1:]) # size [n_samples, n_features]
self.y_data = torch.from_numpy(xy[:, [0]]) # size [n_samples, 1]
# support indexing such that dataset[i] can be used to get i-th sample
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
# we can call len(dataset) to return the size
def __len__(self):
return self.n_samples
dataset = WineDataset()
train_loader = DataLoader(dataset=dataset,
batch_size=4,
shuffle=True,
num_workers=2)
dataiter = iter(dataloader)
data = next(dataiter)
A: In pytorch 1.12 the syntax:
iter(trn_loader).next()
work fine as well as:
next(iter(trn_loader))
From pytorch 1.13 the only working syntax is:
next(iter(trn_loader))
| |
doc_3904
|
I would like to use this square https://fontawesome.com/icons/square?style=regular as regular but it looks regular only with "far" square. The problem is I use them for pseudoelement like "after" and can't figure out how I can tell it to use "far" class too.
The css I'm using:
.square:before {
font-family: "Font Awesome 5 Free";
font-size: 12px;
font-weight: 900;
content: '\f0c8';
}
Thanks
A: It depends on the Font Awesome css that you include. If you include the regular.css, it displays the shapes in their regular form.
.square:before {
font-family: "Font Awesome 5 Free";
font-size: 120px;
font-weight: 900;
content: '\f0c8';
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/regular.css" integrity="sha384-avJt9MoJH2rB4PKRsJRHZv7yiFZn8LrnXuzvmZoD3fh1aL6aM6s0BBcnCvBe6XSD" crossorigin="anonymous">
<div class="square"></div>
It get's interesting, when you want the best of both worlds, solid and regular shapes. You can include the all.css from FontAwesome and change between solid and regular shapes by setting the font-weight: font-weight: 900 displays a solid shape, font-wight: 400 displays a regular shape.
.square-solid:before {
font-family: "Font Awesome 5 Free";
font-size: 120px;
font-weight: 900;
content: '\f0c8';
}
.square-regular:before {
font-family: "Font Awesome 5 Free";
font-size: 120px;
font-weight: 400;
content: '\f0c8';
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<div class="square-solid"></div>
<div class="square-regular"></div>
| |
doc_3905
|
here is my view :
<div ng-controller="clockCtrl">
{{hour}}:{{min}}:{{sec}}
</div>
here is my Controller :
angular.module('myApp').controller('clockCtrl',function($scope,$interval){
$interval(callAtInterval, 1000);
});
function callAtInterval(){
console.log("this text is getting printed after each second");
var today = new Date();
h=today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
$scope.hour=h;
$scope.min=m;
$scope.sec=s;
}
The function is getting call but view is not getting updated.
A: Your callAtInterval function is declared outside of the controller, thus it doesn't have access to $scope. You should declare it like this:
angular.module('myApp').controller('clockCtrl',function($scope,$interval){
function callAtInterval(){
console.log("this text is getting printed after each second");
var today = new Date();
h=today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
$scope.hour=h;
$scope.minutes=m;
$scope.sec=s;
}
$interval(callAtInterval, 1000);
});
| |
doc_3906
|
For example pid X has 3 threads A,B,C , but only thread B has socket for Ip Z and fd of this socket is W,
I want to find out X,B,Z,W.
I tried to read the file/proc/net/tcp but cant find pid/tid/socket id .
What is the simple way ?running all over /proc and search in each /proc/pid/task/tid/net
(in tcp/udp) whichh one has no empty file?and then how do I get the socket id(the fd of the socket)?
Or maybe running on all over proc/pid/task/fd and check which fd point to socket? (How do I know which Ip this socket bind?)
Or maybe I can get all I need from /proc/net/tcp
| |
doc_3907
|
annotations:
nginx.ingress.kubernetes.io/auth-signin: "https://vouch.example.com/login?url=$scheme://$http_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err"
nginx.ingress.kubernetes.io/auth-url: https://vouch.example.com/validate
nginx.ingress.kubernetes.io/auth-response-headers: 'X-Vouch-User, X-Vouch-Idp-Claims-Name'
nginx.ingress.kubernetes.io/auth-snippet: |
auth_request_set $auth_resp_jwt $upstream_http_x_vouch_jwt;
auth_request_set $auth_resp_err $upstream_http_x_vouch_err;
auth_request_set $auth_resp_failcount $upstream_http_x_vouch_failcount;
and a vouch config with:
vouch:
headers:
idtoken: X-Vouch-IdP-IdToken
claims:
- name
everything works, and i can authenticate fine and i can see both my email and name under the x-vouch-user and x-vouch-idp-claims-name http headers respectively. However, i would like to map the headers to use something more appropriate.
I've tried
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header Remote-User $http_x_vouch_idp_claims_name;
but it doesn't seem to work. what are the correct variable name(s) to use in my proxy_set_header?
A: I needed to proxy the original OIDC ID Token to the downstream service. I was able to solve the problem with this setup...
I set the Vouch Proxy config to add the X-Vouch-IdP-IdToken header:
vouch:
headers:
idtoken: X-Vouch-IdP-IdToken
Then in the ingress-nginx annotations, I was able rename the X-Vouch-IdP-IdToken to Authorization by adding the auth_request_header setting in the configuration-snippet annotation to the following:
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: |
auth_request_set $auth_resp_x_vouch_idp_idtoken $upstream_http_x_vouch_idp_idtoken;
proxy_set_header Authorization "Bearer $auth_resp_x_vouch_idp_idtoken";
| |
doc_3908
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct car
{
string name, model;
int year;
};
void search_car(int CarYear)
{
cout<<"1";
ifstream in;
cout<<"2";
car c1;
cout<<"3";
in.open("Cars.txt",ios::binary|ios::in);
cout<<"4"<<endl;
while(!in.eof())
{
cout<<" 5";
in.read((char *) &c1, sizeof(car));
cout<<" 6.Car Year: "<<c1.year<<endl;
if(c1.year == CarYear)
{
cout<<" 7>>> ";
cout<<c1.name<<" "<<c1.model<<" "<<c1.year;
cout<<" <<<8"<<endl;
}
}
cout<<" 9";
in.close();
cout<<" 10";
}
void main()
{
car c[100];
int carNum, menuAct = 0, CarYear = -1, cycle = 1;
ofstream out;
while (cycle == 1)
{
//clrscr();
cout<<endl<<endl<<"1.Enter New car"<<endl<<"2.Search"<<endl<<"3.Exit"<<endl;
cin>>menuAct;
cout<<" Menu Action: "<<menuAct<<endl;
if(menuAct == 1)
{
cout<<"Enter Num OF Cars: ";
cin>>carNum;
out.open("Cars.txt",ios::binary|ios::out|ios::app);
for(int i = 0; i < carNum; i++)
{
cout<<"Enter Name OF Car: ";
cin>>c[i].name;
cout<<"Enter model OF Car: ";
cin>>c[i].model;
cout<<"Enter year OF Car: ";
cin>>c[i].year;
out.write((char *) &c[i], sizeof(car));
}
out.close();
}
else if(menuAct == 2)
{
cout<<"Enter Car Year: ";
cin>>CarYear;
cout<<" 0";
//cout<<" Y: "<<CarYear;
search_car(CarYear);
cout<<" 11";
//menuAct = 0;
}
else if(menuAct == 3)
{
cycle = 0;
}
}
}
Error:
http://s3.picofile.com/file/7580464836/cpp_err11.jpg
What is happened?
I`m used some cout to trace what is happening and code is stopped at number 10.
Also last car is printed twice!!!
A: I'm not surprised you're having problems! You're saving the bytes of the struct literally, and then when you read them back from the file, you're hoping you'll get a std::string back again. It doesn't work that way at all.
The problem is that the car struct doesn't contain all the data it references: the std::string members are actually just pointers to a dynamic array containing the actual string data. You're writing out the car structures as raw bytes, so the strings are never going to file. There's no way they could ever be read back out of it.
Worse, when you read the structs back in, you're setting the pointers in the std::string to garbage values. You can't possibly hope that the memory they happen to point to contains what you want.
You need to define serialisation functions for the car struct, that send it to an outstream using a deep copy, and read it back in safely. Never write raw pointer values to file.
Example code
ostream& operator <<(ostream& os, const car& c) {
return os << c.name << endl << c.model << endl << c.year << endl;
}
istream& operator >>(istream& is, car& c) {
is >> c.name;
is >> c.model;
is >> c.year;
return is;
}
Change in.read((char *) &c1, sizeof(car)); to in >> c1;.
Change out.write((char *) &c[i], sizeof(car)); to out << c[i];.
Much neater! PS. As an excellent general rule, don't ever cast to char* until you understand what it does and how strings are handled!
| |
doc_3909
|
It seems that my code is lagging sometimes and it is also slower than in my Processing sketches. Did I get something wrong? How could I improve my code? Would this kind of calculation also work gpu computation, maybe in lwjgl?
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.Canvas;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable {
public static final int WIDTH = 1280;
public static final int HEIGHT = 800;
private int xstart;
private int ystart;
private int xend;
private int yend;
private int xPos;
private int yPos;
private Thread thread;
private boolean isRunning = false;
private BufferedImage img;
private int[] pixels;
private Random r;
public Main() {
img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
r = new Random();
xPos = WIDTH / 2;
yPos = HEIGHT / 2;
xstart = xPos - 200;
ystart = yPos - 200;
xend = xPos + 200;
yend = yPos + 200;
}
@Override
public void run() {
while (isRunning) {
render();
}
}
private void start() {
if (isRunning)
return;
isRunning = true;
thread = new Thread(this);
thread.start();
}
private void stop() {
if (!isRunning)
return;
isRunning = false;
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
private void render() {
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
}
public void mouseMoved(MouseEvent e) {
}
});
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
}
public void mousePressed(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
}
public void mouseReleased(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
xstart = xPos - 50;
ystart = yPos - 50;
xend = xPos + 50;
yend = yPos + 50;
if (xstart < 0)
xstart = 0;
if (xstart > WIDTH)
xstart = WIDTH;
if (ystart < 0)
ystart = 0;
if (ystart > HEIGHT)
ystart = HEIGHT;
if (xend < 0)
xend = 0;
if (xend > WIDTH)
xend = WIDTH;
if (yend < 0)
yend = 0;
if (yend > HEIGHT)
yend = HEIGHT;
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
for (int i = 0; i < WIDTH * HEIGHT; i++) {
pixels[i] *= 0.99;
if (pixels[i] <= 0)
pixels[i] = 0;
}
for (int y = ystart; y < yend; y++) {
for (int x = xstart; x < xend; x++) {
int i = x + y * WIDTH;
pixels[i] = r.nextInt(0xffffff);
}
}
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
Main main = new Main();
JFrame frame = new JFrame();
frame.add(main);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
main.start();
}
}
A: You're adding new MouseListeners every time render is called, this means, each time a MouseEvent occurs, they have to notify and ever increasing list of listeners, all which seem to do the same thing...
Instead, setup your listeners in the constructor
I would also suggest getting rid of the "render thread" and simply calling your render method only when you want the screen updated (use passive painting instead of active rendering)
| |
doc_3910
|
1- User login APIs
POST /oauth/login
Content-Type: application/json
{
grant_type: 'password',
username: 'USERNAME',
password: 'PASSWORD',
audience: 'API_IDENTIFIER',
scope: 'SCOPE',
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET'
}
2- Response I am planning from my server if that user needs OTP based authentication also(Server backend sends a OTP to mobile).
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": "otp_required",
"error_description": "Multi-factor authentication required",
"otp_token": "eyJ0eXAiOiJKV1QiLCJhbGciD3QCiQ",
"otpidentifier":"7789346789" // this is where otp is sent
}
3. User Triggers this API after afte they get the OTP along with temporary token sent.
POST /outh/otp/verify
Content-Type: application/json
Authorizatuin:{otp_token} // eyJ0eXAiOiJKV1QiLCJhbGciD3QCiQ
{
grant_type: 'otp',
otp: '123456',
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET'
}
4.Final response my Server with proper oauth access token.
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
"scope":"create"
}
Is this the right method or is there a other better or some simple steps exists ?
| |
doc_3911
|
.tokenLocation("url")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.buildBodyMessage();
//create OAuth client that uses custom http client under the hood
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request, OAuthJSONAccessTokenResponse.class);
This is a solution to generate OAuth 2 Access Token easily. Can Any one suggest a an equivalent solution using org.springframework.security.oauth2? Since our's is Bank side application, it won't support apche.oltu. Thank u in advance.
Can Any one suggest a similar solution using org.springframework.security.oauth2? Since our's is Bank side application, it won't support apche.oltu. Thank u in advance.
| |
doc_3912
|
Well i want to know what is difference between both. why foreach better and in which case we only need to use delegate looping.
Is there anyone who has compared both things.
A: You can implement those two solution and then compare them in IL.
Then you will know that is there some significant difference.
Regarding the performance write two apps, with some time diagnostic create a loop with 1mln entries and execute. Then at the end compare the execution time.
EDIT:
The difference might be in usage, using delegate you can perform operation on example string list by an uknow method
delegate StringListOperator(string s)
public operate(StringListOperator operator) {
String.ForEach(operator);
}
I'n not 100% sure about syntax but i hope you got the point.
If You only plan to iterate through list in some method IMHO use simple foreach, this look like only a syntax sugar for me.
A: Take a look at that link: http://www.eggheadcafe.com/software/aspnet/33593372/delegate-vs-foreach-loop.aspx
In the question is your question and in the comments there are pretty good answers.
A: Performance typically won't be a problem however you have to be careful of state capture when using the delegate vs the foreach loop. Basically the compiler will copy variables used inside the loop that are not constants into a nested set of fields. This can at times call undesirable effects
| |
doc_3913
|
I am able to keep the data on Clipboard and get it back for this purpose.
Now what I am trying is to get the same data on some other text editor through ctrl+V or paste operation provided by that text editor.
The code for setting the data on clipboard is :
/// <summary>
/// Set elements on the clipboard.
/// </summary>
/// <param name="object">object to be stored on the clipboard.</param>
private static void SetElementsOnClipboard(CustomData object)
{
Tuple<string, Type> serializedElement = null;
var data = new System.Windows.DataObject();
serializedElement = new Tuple<string, Type>(SerialiseData(object), object.GetType());
data.SetData("SomeKey", serializedElement);
System.Windows.Clipboard.SetDataObject(data);
}
Here the method SerialiseData(CustomData object) returns a string object that I want to paste in other text editor.
I would appreciate any help.
A: You can set data on the clipboard in multiple formats simultaneously. Put in a SetText with a string representation of your object in addition to your SetData, so text-only applications have something to paste from it too.
Note that unless you need to receive that data in a specific format under a specific clipboard ID, you shouldn't need to serialize that object yourself; as long you set the [Serializable] attribute at the top of your class, and you make sure the data inside is made up of serializable types, the system can take care of all that by itself. In fact even the clipboard ID can just be substituted by the object type, and SetData does that automatically if you don't specifically add the string ID.
/// <summary>
/// Set object on the clipboard, together with its string representation.
/// </summary>
/// <param name="myObject">object to be stored on the clipboard.</param>
public static void PutOnClipboardWithTextVersion<T>(T myObject) where T : class
{
DataObject data = new DataObject();
data.SetData(myObject); // identical to data.SetData(typeof(T), myObject);
data.SetText(myObject.ToString());
// The second arg makes the data stay available after the program closes.
Clipboard.SetDataObject(data, true);
}
You'll have to write the .ToString() implementation yourself, of course.
Note: DataObject and Clipboard aren't in System.Windows; they're in System.Windows.Forms. And, I'm fairly sure you can't use object as variable name.
Note on the automatic serialization: this is the way to retrieve the object:
DataObject clipData = (DataObject)Clipboard.GetDataObject();
CustomData clipPaste = null;
if (clipData.GetDataPresent(typeof(CustomData)))
clipPaste = clipData.GetData(typeof(CustomData)) as CustomData;
| |
doc_3914
|
{
"updated_at": 1598015417,
"characters": [{
"character": "A",
"companies": [{
"companyId": 133,
"companyName": "AB Company"
},
{
"companyId": 764,
"companyName": "A Company"
}
]
},
{
"character": "B",
"companies": [{
"companyId": 804,
"companyName": "AB Company"
},
{
"companyId": 472,
"companyName": "B Company"
}
]
}
]
}
The desired output when I search for "AB". It has to return the companies which are included in the search string.
{
"updated_at": 1598015417,
"characters": [{
"character": "A",
"companies": [{
"companyId": 133,
"companyName": "AB Company"
}
]
},
{
"character": "B",
"companies": [{
"companyId": 804,
"companyName": "AB Company"
}
]
}
]
}
A: You will need to map accordingly:
const data = {
"updated_at": 1598015417,
"characters": [{
"character": "A",
"companies": [
{ "companyId": 133, "companyName": "AB Company" },
{ "companyId": 764, "companyName": "A Company" }
]
}, {
"character": "B",
"companies": [
{ "companyId": 804, "companyName": "AB Company" },
{ "companyId": 472, "companyName": "B Company" }
]
}]
};
const filterCompanies = ({ characters, ...data }, fnOrName) => ({
...data,
characters: characters.map(({ companies, ...character }) => ({
...character,
companies: companies.filter(typeof fnOrName === 'function' ?
fnOrName : ({ companyName }) => companyName === fnOrName)
}))
});
const filteredCompanies = filterCompanies(data,
({ companyName }) => companyName === 'AB Company'); // More robust
console.log(filteredCompanies);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Alternatively, you could simply call:
const filteredCompanies = filterCompanies(data, 'AB Company');
A: Here is an iterative solution using object-scan
// const objectScan = require('object-scan');
const data = { updated_at: 1598015417, characters: [{ character: 'A', companies: [{ companyId: 133, companyName: 'AB Company' }, { companyId: 764, companyName: 'A Company' }] }, { character: 'B', companies: [{ companyId: 804, companyName: 'AB Company' }, { companyId: 472, companyName: 'B Company' }] }] };
const prune = objectScan(['characters[*].companies[*].companyName'], {
rtn: 'count',
filterFn: ({ gparent, gproperty, value, context }) => {
if (value.includes(context)) {
return true;
}
gparent.splice(gproperty, 1);
return false;
}
});
console.log(prune(data, 'AB')); // how many companies remain
// => 2
console.log(data);
// => { updated_at: 1598015417, characters: [ { character: 'A', companies: [ { companyId: 133, companyName: 'AB Company' } ] }, { character: 'B', companies: [ { companyId: 804, companyName: 'AB Company' } ] } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@15.0.0"></script>
Disclaimer: I'm the author of object-scan
| |
doc_3915
|
price, expected-delivery-date ...
How to do the loop and extract these informations correctly.
Thanks
Array
(
[price-quotes] => Array
(
[price-quote] => Array
(
[0] => Array
(
[service-code] => DOM.EP
[service-link] => Array
(
[@value] =>
[@attributes] => Array
(
[rel] => service
[href] => https://ct.soa-gw.canadapost.ca/rs/ship/service/DOM.EP?country=CA
[media-type] => application/vnd.cpc.ship.rate-v3+xml
)
)
[service-name] => Expedited Parcel
[price-details] => Array
(
[base] => 8.20
[taxes] => Array
(
[gst] => Array
(
[@value] => 0.41
[@attributes] => Array
(
[percent] => 5
)
)
[pst] => Array
(
[@value] => 0.82
[@attributes] => Array
(
[percent] => 9.975
)
)
[hst] => 0
)
[due] => 9.42
[options] => Array
(
[option] => Array
(
[option-code] => DC
[option-name] => Delivery confirmation
[option-price] => 0
)
)
[adjustments] => Array
(
[adjustment] => Array
(
[0] => Array
(
[adjustment-code] => FUELSC
[adjustment-name] => Fuel surcharge
[adjustment-cost] => 0.24
[qualifier] => Array
(
[percent] => 3
)
)
[1] => Array
(
[adjustment-code] => V1DISC
[adjustment-name] => SMB Savings
[adjustment-cost] => -0.25
)
)
)
)
[weight-details] =>
[service-standard] => Array
(
[am-delivery] =>
[guaranteed-delivery] => 1
[expected-transit-time] => 1
[expected-delivery-date] => 1983
)
)
[1] => Array
(
[service-code] => DOM.PC
[service-link] => Array
(
[@value] =>
[@attributes] => Array
(
[rel] => service
[href] => https://ct.soa-gw.canadapost.ca/rs/ship/service/DOM.PC?country=CA
[media-type] => application/vnd.cpc.ship.rate-v3+xml
)
)
[service-name] => Priority
[price-details] => Array
(
[base] => 16.86
[taxes] => Array
(
[gst] => Array
(
[@value] => 0.88
[@attributes] => Array
(
[percent] => 5
)
)
[pst] => Array
(
[@value] => 1.76
[@attributes] => Array
(
[percent] => 9.975
)
)
[hst] => 0
)
[due] => 20.3
[options] => Array
(
[option] => Array
(
[option-code] => DC
[option-name] => Delivery confirmation
[option-price] => 0
)
)
[adjustments] => Array
(
[adjustment] => Array
(
[0] => Array
(
[adjustment-code] => FUELSC
[adjustment-name] => Fuel surcharge
[adjustment-cost] => 1.31
[qualifier] => Array
(
[percent] => 8
)
)
[1] => Array
(
[adjustment-code] => V1DISC
[adjustment-name] => SMB Savings
[adjustment-cost] => -0.51
)
)
)
)
[weight-details] =>
[service-standard] => Array
(
[am-delivery] =>
[guaranteed-delivery] => 1
[expected-transit-time] => 1
[expected-delivery-date] => 1983
)
)
[2] => Array
(
[service-code] => DOM.RP
[service-link] => Array
(
[@value] =>
[@attributes] => Array
(
[rel] => service
[href] => https://ct.soa-gw.canadapost.ca/rs/ship/service/DOM.RP?country=CA
[media-type] => application/vnd.cpc.ship.rate-v3+xml
)
)
[service-name] => Regular Parcel
[price-details] => Array
(
[base] => 8.2
[taxes] => Array
(
[gst] => Array
(
[@value] => 0.41
[@attributes] => Array
(
[percent] => 5
)
)
[pst] => Array
(
[@value] => 0.82
[@attributes] => Array
(
[percent] => 9.975
)
)
[hst] => 0
)
[due] => 9.42
[options] => Array
(
[option] => Array
(
[option-code] => DC
[option-name] => Delivery confirmation
[option-price] => 0
[qualifier] => Array
(
[included] => 1
)
)
)
[adjustments] => Array
(
[adjustment] => Array
(
[0] => Array
(
[adjustment-code] => FUELSC
[adjustment-name] => Fuel surcharge
[adjustment-cost] => 0.24
[qualifier] => Array
(
[percent] => 3
)
)
[1] => Array
(
[adjustment-code] => V1DISC
[adjustment-name] => SMB Savings
[adjustment-cost] => -0.25
)
)
)
)
[weight-details] =>
[service-standard] => Array
(
[am-delivery] =>
[guaranteed-delivery] =>
[expected-transit-time] => 2
[expected-delivery-date] => 1982
)
)
[3] => Array
(
[service-code] => DOM.XP
[service-link] => Array
(
[@value] =>
[@attributes] => Array
(
[rel] => service
[href] => https://ct.soa-gw.canadapost.ca/rs/ship/service/DOM.XP?country=CA
[media-type] => application/vnd.cpc.ship.rate-v3+xml
)
)
[service-name] => Xpresspost
[price-details] => Array
(
[base] => 9.96
[taxes] => Array
(
[gst] => Array
(
[@value] => 0.52
[@attributes] => Array
(
[percent] => 5
)
)
[pst] => Array
(
[@value] => 1.04
[@attributes] => Array
(
[percent] => 9.975
)
)
[hst] => 0
)
[due] => 11.99
[options] => Array
(
[option] => Array
(
[option-code] => DC
[option-name] => Delivery confirmation
[option-price] => 0
)
)
[adjustments] => Array
(
[adjustment] => Array
(
[0] => Array
(
[adjustment-code] => FUELSC
[adjustment-name] => Fuel surcharge
[adjustment-cost] => 0.77
[qualifier] => Array
(
[percent] => 8
)
)
[1] => Array
(
[adjustment-code] => V1DISC
[adjustment-name] => SMB Savings
[adjustment-cost] => -0.3
)
)
)
)
[weight-details] =>
[service-standard] => Array
(
[am-delivery] =>
[guaranteed-delivery] => 1
[expected-transit-time] => 1
[expected-delivery-date] => 1983
)
)
)
)
)
example to extract code
$preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
foreach ($array as $key => $child) {
if (is_array($child)) {
$newArray =& array_flatten($child, $preserve_keys, $newArray);
} elseif ($preserve_keys + is_string($key) > 1) {
$newArray[$key] = $child;
} else {
$newArray[] = $child;
}
}
return $newArray;
}
print_r( '<br>' );
$test = array_flatten($result, 1);
echo $test;
A: you have to loop price-quote.
foreach($array['price-quotes']['price-quote'] as $key=>$value){
echo '<br/>service-name : '.$value['service-code'];
echo '<br/>price : '.$value['price-details']['due'];
echo '<br/>expected-delivery-date : '.$value['service-standard']['expected-delivery-date'];
echo "<hr/>";
// or you can create an array
$new_array[$key]['service-name'] = $value['service-code'];
$new_array[$key]['price'] = $value['price-details']['due'];
$new_array[$key]['expected-delivery-date'] = $value['service-standard']['expected-delivery-date'];
}
Output :
service-name : DOM.EP
price : 9.42
expected-delivery-date : 1983
===============
service-name : DOM.PC
price : 20.3
expected-delivery-date : 1983
===============
service-name : DOM.RP
price : 9.42
expected-delivery-date : 1982
===============
service-name : DOM.XP
price : 11.99
expected-delivery-date : 1983
===============
| |
doc_3916
|
I added
Proxy server: 127.0.0.1:9150 - To access Tor port
Rule player.exe with 192.168.58.* port with Virtual Box only network action. To isolate genymotion -> virtual box communication.
Genymotion's phone runs correctly, but without internet. How should I route 5555 wifi port for adb.exe to access internet? Got 10049 error from Proxy SOCKS5 127.0.0.1 via Virtual Box host-only network.
| |
doc_3917
|
I managed to compile the extension using:
clang -bundle -fPIC -Isqlite3 -o <desired extension name>.sqlext <filename>.c
However, I cannot seem to load the extension.
.load <path to extension file>
Error: unknown command or invalid arguments: "load". Enter ".help" for help
And when I type .help, I cannot see .load.
I have also tried to enable extensions.
int sqlite3_enable_load_extension(sqlite3 *db, int onoff==1);
Error: near "int": syntax error
I would really appreciate a step-by-step instruction on how to enable extensions in SQLite?
Thanks!
A: Most likely your sqlite compiled with SQLITE_OMIT_LOAD_EXTENSION. Get the one build without this flag, or build it yourself.
You cannot use sqlite3_enable_load_extension from SQL, it is sqlite's C API.
A: For many vendors, the default provided sqlite3 does not have a load extension enabled. (keltar clarified)
I would really appreciate a step-by-step instruction on how to enable extensions in SQLite?
*
*Go to Sqlite Downloads
*Get the appropriate build. It has the load extension enabled.
*Use it directly or replace /usr/bin/sqlite3 with the newer one.
| |
doc_3918
|
<?xml version="1.0" encoding="UTF-8"?>
<!-- _tag -->
<tag value="0" actions_tagged="0" name="adjust temperature">
<link type="application/xml" rel="list" href="/api/v1/tags.xml"/>
<link type="application/xml" rel="self" href="/api/v1/tags/adjust%20temperature.xml"/>
<actions>
<action id="105">
<link type="application/xml" rel="tagged_action" href="/api/v1/actions/105.xml"/>
<short_name>Set thermostat to 68F in the winter and 74F in the summer</short_name>
</action>
<action id="106">
<link type="application/xml" rel="tagged_action" href="/api/v1/actions/106.xml"/>
<short_name>Close windows and blinds</short_name>
</action>
</actions>
</tag>
I would like to capture each "action id" and each "short name". I'm able to capture the short name with the following code. But, how do you obtain the corresponding action id?
String action = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Actions myActions = new Actions();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xml));
Document doc = db.parse(inStream);
NodeList nodeList = doc.getElementsByTagName("action");
for (int s = 0; s < nodeList.getLength(); s++) {
Node fstNode = nodeList.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("short_name");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
String currentAction = ((Node) lstNm.item(0)).getNodeValue();
if(currentAction != null) {
myActions.setShort_name(currentAction);
}
lstNmElmntLst = fstElmnt.getElementsByTagName("action id");
// this didn't work - nor did 'id'
lstNmElmnt = (Element) lstNmElmntLst.item(0);
lstNm = lstNmElmnt.getChildNodes();
currentAction = ((Node) lstNm.item(0)).getNodeValue();
if(currentAction != null) {
myActions.setDescription(currentAction);
}
}
}
A: The id value is an attribute on the action tag, so once you're at the proper node, you'll want to get the id from it by something like
String idValue = fstElmnt.getAttribute("id");
| |
doc_3919
|
I have an Nested Array , and I want to read the values entered inside the table , also im having a option to add new text field as well . I want to know how to assign onchange function and values to these textfields.
Also how to discard values on delete button right next to text field.
Since it is an Nested array it is becoming difficult to update values on setState.
A: You have an array of states with an Id property. Just use array filter by this Id on existing state and assign it back to state
| |
doc_3920
|
As far as I can tell, this should work. I expect to see
Started
Reached mark
Done
Instead, I get
Started
Done
document.querySelector('#play').addEventListener('click', function speak() {
const utterance = new SpeechSynthesisUtterance(
`<?xml version="1.0"?>
<speak version="1.1">Foo <mark name="bar" /> baz.</speak>`
)
const log = document.getElementById('log')
utterance.addEventListener('start', () => {log.value = 'Started\n'})
utterance.addEventListener('mark', () => {log.value += 'Reached mark\n'})
utterance.addEventListener('end', () => {log.value += 'Done\n'})
log.value = 'Waiting…'
speechSynthesis.cancel()
speechSynthesis.speak(utterance)
})
<textarea id="log" disabled rows="3">Waiting…</textarea>
<hr>
<button id="play">Speak</button>
A: Sorry to let you know that it's a bug and that SSML isn't yet implemented.
https://github.com/WICG/speech-api/issues/10
https://bugs.chromium.org/p/chromium/issues/detail?id=88072
You'll see that the chronium issue is 9 years old so I doubt it'll be fixed anytime soon.
| |
doc_3921
|
Thank you for your potential help
my database has 5 fields :1.
*
*id, int(11) , AUTO_INCREMENT
*mail varchar(255)
*pseudo varchar(25)
*mdp char(32)
*Date
register.php
$ AfficherFormulaire=1;
//traitement du formulaire:
if(isset($_POST['pseudo'],$_POST['mdp'],$_POST['mail'])){//l'utilisateur à cliqué sur "S'inscrire", on demande donc si les champs sont défini avec "isset"
if(empty($_POST['mail'])){//le champ mail est vide
echo '<a id="annotation">le champ mail est vide.</a>';
} elseif(empty($_POST['pseudo'])){//le champ pseudo est vide, on arrête l'exécution du script et on affiche un message d'erreur
echo '<a id="annotation">le champ pseudo est vide.</a>';
} elseif(!preg_match("#^[a-z0-9]+$#",$_POST['pseudo'])){//le champ pseudo est renseigné mais ne convient pas au format qu'on souhaite qu'il soit, soit: que des lettres minuscule + des chiffres (je préfère personnellement enregistrer le pseudo de mes membres en minuscule afin de ne pas avoir deux pseudo identique mais différents comme par exemple: Admin et admin)
echo '<a id="annotation">Le Pseudo doit être renseigné en lettres minuscules sans accents, sans caractères spéciaux.</a>';
} elseif(strlen($_POST['pseudo'])>15){//le pseudo est trop long, il dépasse 25 caractères
echo '<a id="annotation">Le pseudo est trop long, il dépasse 15 caractères.</a>';
} elseif(empty($_POST['mdp'])){//le champ mot de passe est vide
echo '<a id="annotation">Le champ Mot de passe est vide.</a>';
} elseif(mysqli_num_rows(mysqli_query($mysqli,"SELECT * FROM membres WHERE pseudo='".$_POST['pseudo']."'"))==1){//on vérifie que ce pseudo n'est pas déjà utilisé par un autre membre
echo '<a id="annotation">Ce pseudo est déjà utilisé.</a>';
} elseif(mysqli_num_rows(mysqli_query($mysqli,"SELECT * FROM membres WHERE mail='".$_POST['mail']."'"))==1){//on vérifie que ce mail n'est pas déjà utilisé par un autre membre
echo '<a id="annotation">Ce mail est déjà utilisé.</a>';
} else {
// INSERT INTO membres VALUES('', 'mail', 'pseudo', 'mdp', NOW);
if(!mysqli_query($mysqli,"INSERT INTO membres SET pseudo='".$_POST['pseudo']."',mail='".$_POST['mail']."', mdp='".md5($_POST['mdp'])."'", ")){
echo "Une erreur s'est produite: ".mysqli_error($mysqli);
} else {
echo '<a id="annotation">Vous êtes inscrit avec succès!</a>';
header("Location: postedecontrole.php");
}
}
connection.php
session_start(); // à mettre tout en haut du fichier .php, cette fonction propre à PHP servira à maintenir la $_SESSION
if(isset($_POST['connexion'])) { // si le bouton "Connexion" est appuyé
// on vérifie que le champ "Pseudo" n'est pas vide
// empty vérifie à la fois si le champ est vide et si le champ existe belle et bien (is set)
if(empty($_POST['pseudo'])) {
echo "Le champ Pseudo est vide.";
} else {
// on vérifie maintenant si le champ "Mot de passe" n'est pas vide"
if(empty($_POST['mdp'])) {
echo "Le champ Mot de passe est vide.";
} else {
// les champs sont bien posté et pas vide, on sécurise les données entrées par le membre:
$Pseudo = htmlentities($_POST['pseudo'], ENT_QUOTES, "ISO-8859-1"); // le htmlentities() passera les guillemets en entités HTML, ce qui empêchera les injections SQL
$MotDePasse = htmlentities($_POST['mdp'], ENT_QUOTES, "ISO-8859-1");
//on se connecte à la base de données:
$mysqli = mysqli_connect("localhost", "root", "", "domoserre");
//on vérifie que la connexion s'effectue correctement:
if(!$mysqli){
echo "Erreur de connexion à la base de données.";
} else {
// on fait maintenant la requête dans la base de données pour rechercher si ces données existe et correspondent:
$Requete = mysqli_query($mysqli,"SELECT * FROM membres WHERE pseudo = '".$Pseudo."' AND mdp = '".$MotDePasse."'");//si vous avez enregistré le mot de passe en md5() il vous suffira de faire la vérification en mettant mdp = '".md5($MotDePasse)."' au lieu de mdp = '".$MotDePasse."'
// si il y a un résultat, mysqli_num_rows() nous donnera alors 1
// si mysqli_num_rows() retourne 0 c'est qu'il a trouvé aucun résultat
if(mysqli_num_rows($Requete) == 0) {
echo "Le pseudo ou le mot de passe est incorrect, le compte n'a pas été trouvé.";
} else {
// on ouvre la session avec $_SESSION:
$_SESSION['pseudo'] = $Pseudo; // la session peut être appelée différemment et son contenu aussi peut être autre chose que le pseudo
header("Location: postedecontrole.php");
}
}
}
}
}
?>
A: Keep the Attribute of Date column as on update CURRENT TIMESTAMP.
Before updating any row while connecting fetch the value from the Date column to get the old date.
I believe this should work.
Edit:
Registration: During registration, you are creating a new row hence the Date column will get a value. This is your time of registration.
Connecting/Logging In: Make another column in the same table which will keep the status of the user, logged in or logged out. You can update this status each time the user logs in or logs out. The Date cell will get updated as it has on update CURRENT TIMESTAMP attribute.
However, you can achieve this in a number of ways. This is just a method. I personally don't like cookies/js for such purposes so not suggesting it.
| |
doc_3922
|
However, I'm struck with select where I'm getting "An internal error has occurred in compiler".
template<typename R>
class linq_range
{
R range;
public:
linq_range(R range)
: range(std::move(range))
{
}
template<typename F>
auto select(const F& f) const -> linq_range<decltype(std::declval<R>() | boost::adaptors::transformed(f))>
{
return linq_range<decltype(std::declval<R>() | boost::adaptors::transformed(f))>(this->range | boost::adaptors::transformed(f));
}
};
template<typename R>
auto from(R& r) -> linq_range<boost::iterator_range<decltype(std::begin(r))>>
{
return from(std::begin(r), std::end(r));
}
template<typename I>
linq_range<boost::iterator_range<I>> from(I b, I e)
{
return linq_range<boost::iterator_range<I>>(boost::iterator_range<I>(b, e));
}
Any ideas how to get around this problem?
A: I solved it by defining:
BOOST_RESULT_OF_USE_DECLTYPE
| |
doc_3923
|
AUTHENTICATION_ERROR = HTTPException(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Authentication failed",
headers={"WWW-Authenticate": "Bearer"},
)
# ...
async def current_user(token: str = Depends(oauth2_scheme)) -> User:
"""FastAPI dependency that returns the current user
If the current user is not authenticated, raises an authentication error.
"""
try:
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
except JWTError:
raise AUTHENTICATION_ERROR
username = payload["sub"]
if username not in stub_users:
raise AUTHENTICATION_ERROR
return stub_users[username]
However, I've never actually seen this done and it feels quite wrong. It appears to work though.
In Python, is it safe to create Exception instances and raise them several times?
(Safe meaning that it works as expected with no surprises)
A: I would create a custom exception and use it.
Makes the intention clear, is very "pythonic", and you could explicitly catch (the more specific) AuthenticationError in an outer function if needed.
import fastapi
from fastapi.exceptions import HTTPException
class AuthenticationError(HTTPException):
def __init__(self):
super().__init__(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Authentication failed",
headers={"WWW-Authenticate": "Bearer"},
)
# ...
async def current_user(token: str = Depends(oauth2_scheme)) -> User:
"""FastAPI dependency that returns the current user
If the current user is not authenticated, raises AuthenticationError.
"""
try:
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
except JWTError:
raise AuthenticationError
username = payload["sub"]
if username not in stub_users:
raise AuthenticationError
return stub_users[username]
| |
doc_3924
|
val map = HashMap<String, Any>()
map["one"] = request.records
dayFormDoc.set(map)
Here request.records is an array.
A: try this,
Android
Map<String, Object> docData = new HashMap<>();
docData.put("listExample", Arrays.asList(1, 2, 3));
java
ArrayList<Object> arrayExample = new ArrayList<>();
Collections.addAll(arrayExample, 5L, true, "hello");
docData.put("arrayExample", arrayExample);
more information https://firebase.google.com/docs/firestore/manage-data/add-data
Hope it's help full.
A: You cannot simply add an array to a Cloud Firestore database because you'll get an error that looks like this:
Caused by: java.lang.IllegalArgumentException: Invalid data. Arrays are not supported; use a List instead (found in field array)
So to solve this problem, you should convert your array to a list as in the following lines of code.
For Android:
Map<String, Object> map = new HashMap<>();
String[] array = {"One", "Two", "Three"};
map.put("array", Arrays.asList(array));
dayFormDoc.update(map);
For Kotlin:
val map = HashMap<String, Any>()
val array = arrayOf("One", "Two", "Three")
map["array"] = Arrays.asList(*array)
dayFormDoc.update(map)
| |
doc_3925
|
This is what I achieved yet:
I am missing that triangle from the bottom. I want to use css/css3 to solve this. This is what I tried, but without succes:
.contact-form .parsley-errors-list .parsley-required:after{
padding: 8px;
background-color:red
margin-top: 1px;
transition: none 0s ease 0s;
position: absolute;
content: "";
left: -6px;
transform: rotate(45deg);
}
Can you guide me How do I achieve that triangle with css/css3 ? thx
A: Use this and see if it helps
.contact-form .parsley-errors-list .parsley-required{
position: relative;
}
.contact-form .parsley-errors-list .parsley-required:after{
content: '';
position: absolute;
top: 100%;
left: 10px;
border-left: 10px solid red;
border-bottom: 10px solid transparent;
transition: none 0s ease 0s;
}
A: .arrow_box {
position: relative;
background: #FF0000;
}
.arrow_box:after {
top: 100%;
left: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-color: rgba(255, 0, 0, 0);
border-top-color: #FF0000;
border-width: 15px;
margin-left: -15px;
}
For a "straight" arrow.
width: 0;
height: 0;
border-style: solid;
border-width: 20px 20px 0 0;
border-color: #ff0000 transparent transparent transparent;
This lets you create it using borders.
| |
doc_3926
|
You enter the page with a (high-)chart in it displaying a series for current year fetched from mysql - Works fine, no problem.
Selection from dropdown should update the query to show the year selected from dropdown.
The dropdown:
<select id="set_data">
<?php
$sql = "SELECT DISTINCT year FROM chartdata ORDER BY year DESC";
$r = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($r)){
echo '<option value="'.$row['year'].'">'.$row['year'].'</option>';
}
?>
</select>
jQuery
<script type="text/javascript">
$('#set_data').change(function() {
$('.data_set').load('fetch_charts/highchart_ad.php?id='+this.options[this.selectedIndex].value);
});
</script>
So basically what i'm doing is loading a new set of highchart script on the same content - that doesn't give me much... obviously, but I have totally stopped
Please help
- UPDATE -
Basicly what i'm looking for:
1. Entering the the page = 2014 visible... 2. Select 2013 from dropdown and chart updates with 2013 data.
A: Ok, after some trying and failing - my own result on the problem above..
(thought i could be nice to share, also to close this post)
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<select name="set_year" onchange="this.form.submit()">
<?php
$sql = "SELECT DISTINCT year FROM chartdata ORDER BY year DESC";
$r = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($r)){
echo '<option value="'.$row['year'].'">'.$row['year'].'</option>';
}
?>
</select>
</form>
<?php
$year = date('Y');
$set_year = mysqli_real_escape_string($con, $_POST['set_year']);
if(empty($set_year)){
$A = "SELECT * FROM chartdata WHERE year = $year";
}
else{
$A = "SELECT * FROM chartdata WHERE year = $set_year";
}
$da = mysqli_query($con, $A);
while($result = mysqli_fetch_array($da)){
$dataset[]= $result['data'];
//getting the data and putting them into highchart series -> data.
}
?>
<script>
//highchart script
//...
series: [{
data: [<?php echo join($dataset, ',')?>]
}]
</script>
Above works fine.
Any other solutions/ comments are welcome =)
| |
doc_3927
|
I've tested a method :
1 - Select 100000 Rows By Rowid From top of table and insert to another Temp table . (Estiated Time : 0.87s)
2 - insert Selected Rows To Second Table By Temp Table Map . (Estiated Time : 1m12.59s)
3 - Delete Selected Rows From First (Online) Table By Temp Table Map (Estiated Time : 5m39.38s -> it's Too Long Help Me Please ).
informix 12.10
A: Run your queries with SET EXPLAIN ON enabled and confirm that the optimizer is performing the slow step the way you presume. If it is not, you may need to apply optimizer directives or adjust your index strategy. (Bear in mind the more indexes, the more pages that need to be modified.)
If the INSERT and then DELETE operations are taking too long, is it feasible to use expression based fragmentation? This would give you the option to DETACH yesterday's fragment, and attach it to the off-line table.
| |
doc_3928
|
SyntaxError: Unexpected identifier
> 1 | const screenSize = require("../src/index.js").screenSize;
| ^
I'm using Phaser 3, Webpack, Babel, and React.
I'm relatively new to all except React.
I followed Jest's Getting Started tutorial and using with webpack tutorial, but I'm still getting the error.
package.json
{
"name": "phaser3-project-template",
"version": "1.1.0",
"description": "A Phaser 3 Project Template",
"main": "src/index.js",
"scripts": {
"build": "webpack --config webpack/prod.js ",
"start": "webpack-dev-server --config webpack/base.js --open",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/photonstorm/phaser3-project-template.git"
},
"author": "Richard Davey <rdavey@gmail.com> (http://www.photonstorm.com)",
"license": "MIT",
"licenseUrl": "http://www.opensource.org/licenses/mit-license.php",
"bugs": {
"url": "https://github.com/photonstorm/phaser3-project-template/issues"
},
"homepage": "https://github.com/photonstorm/phaser3-project-template#readme",
"devDependencies": {
"@babel/core": "^7.4.3",
"@babel/plugin-proposal-class-properties": "^7.4.0",
"@babel/preset-env": "^7.4.3",
"@babel/preset-react": "^7.0.0",
"babel-jest": "^24.7.1",
"babel-loader": "^8.0.5",
"clean-webpack-plugin": "^1.0.0",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"jest": "^24.7.1",
"path": "^0.12.7",
"raw-loader": "^1.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"terser-webpack-plugin": "^1.2.1",
"webpack": "^4.28.3",
"webpack-cli": "^3.2.1",
"webpack-dev-server": "^3.1.14",
"webpack-merge": "^4.2.1"
},
"dependencies": {
"babel-core": "^6.26.3",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^2.1.1",
"phaser": "^3.16.2",
"react-redux": "^7.0.2",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"style-loader": "^0.23.1"
},
"jest": {
"modulePaths": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
webpack/base.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = {
mode: "development",
devtool: "eval-source-map",
entry: "./src/index.js", //do we need this?
output: {
path: path.resolve("dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: "babel-loader"
},
{
test: [/\.vert$/, /\.frag$/],
use: "raw-loader"
},
{
test: /\.(gif|png|jpe?g|svg|xml)$/i,
use: "file-loader"
}
]
},
plugins: [
new CleanWebpackPlugin(["dist"], {
root: path.resolve(__dirname, "../")
}),
new webpack.DefinePlugin({
CANVAS_RENDERER: JSON.stringify(true),
WEBGL_RENDERER: JSON.stringify(true)
}),
new HtmlWebpackPlugin({
template: "./index.html",
filename: "index.html",
inject: "body"
})
]
};
.babelrc.js
const presets = [
[
"@babel/env",
{
targets: {
browsers: [">0.25%", "not ie 11", "not op_mini all"],
node: "current"
},
modules: false
}
],
"@babel/preset-react"
];
const plugins = ["@babel/plugin-proposal-class-properties"];
module.exports = { presets, plugins };
jest.config.js
"use strict";
module.exports = {
testMatch: ["<rootDir>/**/*.test.js"],
testPathIgnorePatterns: ["/src/", "node_modules"]
};
index.test.js
const screenSize = require("../src/index.js").screenSize;
//import toBeType from "jest-tobetype";
console.log(screenSize);
test("screenSize is an object", () => {
expect(typeof screenSize).toBe("object");
});
Github Repo
How can I get Jest to process the es6 syntax?
A: Require is a node environment syntax for importing variables, and Jest runs in node. More background on the differences between import/require and node can be seen in this SO question
You can add support for this with
npm install --save-dev @babel/plugin-proposal-class-properties @babel/plugin-transform-modules-commonjs
and include these as presets in your babelrc.js
const presets = [
[
"@babel/env",
{
targets: {
browsers: [">0.25%", "not ie 11", "not op_mini all"]
},
modules: false
}
],
"@babel/preset-react"
];
const plugins = [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-modules-commonjs"
];
module.exports = { presets, plugins };
The above code will still run into a number of errors details to resolve those can be seen here: https://medium.com/@Tnodes/setting-up-jest-with-react-and-phaser-422b174ec87e
| |
doc_3929
|
if (!(C is contained into A)) insert C into B
I'm using SQLite. Thanks for help
A: Actually, in your specific case it may happen to be as easy as
insert into B (c_value) select c_value from A where c_value = @your_c_value_here
see INSERT statement
sorry I haven't noticed the negation in your question for the C in A condition
I have another option for you
with temp_val as (select @your_val_goes_here as val)
insert into b
select val from temp_val where not exists
(select 1 from a where c = val)
check out this fiddle
| |
doc_3930
|
Unfortunately, as the scene is being rendered without a browser, I can not use THREE.ImageUtils.loadTexture.
I am given an error when using this - I understand that document does not exist as I am rendering it server side.
var materials = [
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('url here'')}),
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('url here'')}),
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('url here'')}),
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('url here'')}),
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('url here'')}),
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture('url here')})
];
returns
/usr/src/node-v0.10.40/node_modules/three/three.js:13028
var image = document.createElement( 'img' );
^
ReferenceError: document is not defined
So in a sum - I need to load a texture onto a cube using SoftwareRenderer in three.js, however the catch is I am rendering it with node, not loading it in a browser. How would I go about doing this?
| |
doc_3931
|
I have some Data in the DB, and the problem is, when I login into the application, I always get only the state of Data from the DB when the Server was started - not the new data. Everything writen into the DB after the start won't appear. When I restart the server, it's there, but again the new Data won't appear. The data is needed in the homepage of the application, so this Init() method is executed during the login process.
If I manually delete some Data from the DB, I can still see them in the application.
It's like some kind of cache that produces this problem...
It's a Java EE application, running on a Glasfish server, using Apache web server, Oracle DB and Solr.
Anyways, the Init method looks something like this:
private MyClass mc;
private List<MyData> myList;
@Override
@PostConstruct
public void initDefaults() {
myList= mc.getDataList();
}
In MyClass:
public List<MyData> fetchAllData(){
return this.em.createNamedQuery(someClass.FINDALL).getResultList();
}
I don't thing that this is a Problem related to the code, it works fine in a other part of the application. Could it be some setting?
Any expirience?
| |
doc_3932
|
routing code:
$route['api'] = 'omega_api';
$route['api/makes/(:any)'] = 'omega_api/makes/$1';
$route['terms-and-conditions'] = 'home/terms_and_conditions';
$route['contact-us'] = 'home/contact_us';
$route['404_override'] = '';
$route['default_controller'] = 'home';
$route['(:any)'] = 'home/$1';
controller code:
class omega_api extends REST_Controller {
function __construct() {
parent::__construct();
$this->load->model('allcars_model');
}
public function makes_get($year) {
$this->response($this->allcars_model->get_makes($year));
}
}
model code:
Class allcars_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function get_makes($year) {
return $this->db->distinct()->select('om_allmakes.makeid,om_allmakes.make_name')->from('om_allmakes')->join('om_allcars', 'om_allmakes.makeid=om_allcars.model_make_id')->where('om_allcars.model_year = ', $year)->get()->result();
}
}
so when i goto this url http://www.omegalocal.com/api/makes/2014/format/json it always gives me xml output as below:
<xml>
<item>
<makeid>3</makeid>
<make_name>acura</make_name>
</item><item><makeid>4</makeid>
<make_name>Alfa Romeo</make_name>
</item>
</xml>
I really dont get whats the problem guys but i think it has to do something with routing.
Thanx in advance.
A: Try with query string format: ?format=json
$route['api/makes/(:num)/format/(xml|json)'] = 'omega_api/makes/$1/?format=$2';
| |
doc_3933
|
A: Node.js by default is setup to be highly performant due to it's asynchronous event loop.
However, for multi-core systems, you could look at the cluster module to scale out your api: https://nodejs.org/api/cluster.html
Note that your Node.js backend should ideally be stateless for scalability.
| |
doc_3934
|
302947298 2340974238 0 0 cat
345098948 8345988989 0 0 dog
098982388 2098340923 0 0 fish
932840923 0923840988 0 0 parrot
I have another file, mess.txt.gz, which is compressed using GNU zip (.gz file).
It basically looks like a massive string of letters:
sdihfoiahdfosparrotdhiafoihsdfoijaslkdogoieufoiweuf
Basically, for every line in the tab delimited text file, I want to see
if any of the animal names are present within this .gz file.
Ideally, it would return something like this:
302947298 2340974238 0 0 cat no
345098948 8345988989 0 0 dog yes
098982388 2098340923 0 0 fish no
932840923 0923840988 0 0 parrot yes
At the moment I am doing the following:
gunzip -cd mess.txt.gz | grep cat
gunzip -cd mess.txt.gz | grep dog
To automate it, I've tried the following:
cat animals.txt | awk '{print $5}' > animal_names.txt
cat animal_names.txt | while read line
do
gunzip -cd mess.txt.gz | grep $line > output.txt
done
I've also tried:
cat animal_names.txt | while read line
do
if [ gunzip -cd mess.txt.gz | grep $line ]
then
echo "Yes"
else
echo "No"
fi
; do
done > output.txt
What is the best way to do this in bash?
A: You can pass all the search strings to zgrep -Ff - in one pass:
cut -f5 animals.txt |
zgrep -Ff - mess.txt.gz
The -F option says to look for literal strings, not regular expressions (avoids false positives if the input contains dots or other regex metacharacters, and besides, will be significantly faster) and -f - says to read the search patterns from standard input (i.e. from the pipe from cut).
If you want a list of the matched animals, add an -o option and a brief postprocessing step;
cut -f5 animals.txt |
zgrep -Ff - -o mess.txt.gz |
sort | uniq -c
You can replace | uniq -c with just -u if you don't care how many there were of each.
This works as intended on Linux with GNU grep, but macOS (and thus probably generally *BSD) grep -o only prints the first match in each input line when combined with -f -. If you need *BSD portability, I'd go with either of the other solutions here (currently there's one for sed and one for Awk).
A: You may use this awk solution with gzcat:
awk 'BEGIN{FS=OFS="\t"} FNR==NR {s=s $0; next} {print $0, (index(s, $NF) > 1 ? "yes" : "no")}' <(gzcat mess.txt.gz) animals.txt
302947298 2340974238 0 0 cat no
345098948 8345988989 0 0 dog yes
098982388 2098340923 0 0 fish no
932840923 0923840988 0 0 parrot yes
A more readable form:
awk '
BEGIN {FS=OFS="\t"}
FNR == NR {
s = s $0
next
}
{
print $0, (index(s, $NF) > 1 ? "yes" : "no")
}
' <(gzcat mess.txt.gz) animals.txt
A: What about this?
gunzip -cd mess.txt.gz | grep "$(< animals.txt sed -e 's/.*\t//' | sed -z 's/\n/\\|/g;s/\\|$//')"
It is basically the version of your
gunzip -cd mess.txt.gz | grep dog
where, instead of dog, the regex dog\|cat\|whatever is generated from the file animals.txt.
My command should give you the output that you get with the example you write after
To automate it, I've tried the following:
with which you don't end up with the result you refer to as ideal.
A: Many nice answers here, and a very good one from @triplee.
Just adding the 'in memory' bash way :
#!/bin/bash
search() {
local patterns="$2"
local string="$(gunzip -cd $1)"
while IFS= read -r line; do
local pattern="${line/[^$'\t']*$'\t'/}"
local suffix="no"
[ "${string/${pattern}/}" != "${string}" ] && suffix="yes"
echo "${line} ${suffix}"
done < "${patterns}"
}
search mess.txt animals.txt
The goal here is to limit I/O, one read from the gziped mess.txt, one read from animals and match in memory with strings patterns.
| |
doc_3935
|
In my bootstrap, I create my new route as follows:
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route(":company/:dpt", array('controller' => 'browse'));
$router->addRoute("browse", $route);
When I browse to http://www.site.com/ABC_Co/dry_goods it routes me to IndexAction in BrowseController. Great! The problem is that my other admin-related URLS - such as /company/create, etc - are directing there too.
Is there some way to get Zend to do its default Controller/Action matching first, and revert to the Browse route only on failure?
Thanks!
A: Routes are handled on LIFO, you'll need to do something like this:
$router->removeDefaultRoutes();
//add your routes
//add in the default route:
$route = new Zend_Controller_Router_Route(":module/:controller/:action"
Instead, you may just want to sonsider adding a "static" component to your "browse" route. That would make is more specific:
$route = new Zend_Controller_Router_Route("browse/:company/:dpt", array('controller' => 'browse'));
IMO, the second one is the better option
| |
doc_3936
|
text1
text2
text3
text4
List 2
value1
value2
value3
value4
Result
text1=value1
text2=value2
text3=value3
text4=value4
How do I do this in Notepad++?
A: Follows my solution.
First, concatenate the two lists separating them by a special character (in the following, I will use §):
text1
text2
text3
text4
§
value1
value2
value3
value4
Then:
*
*Find what: ^(?!§$)(?!.*=)(.*)([\w\W]*?^§\r?\n)(.*)\r?\n?
*Replace with: $1=$3$2
*Ensure to have the following settings:
*Click as many times as needed on the Replace key.
*Finally remove the special character.
| |
doc_3937
|
For example here is Case 1:
#include <pthread.h>
pthread_mutex_t count_mutex;
long long count;
void
increment_count()
{
pthread_mutex_lock(&count_mutex);
count = count + 1;
pthread_mutex_unlock(&count_mutex);
}
Here is Case 2:
struct order_que
{
struct order **orders;
int size;
int head;
int tail;
pthread_mutex_t lock;
};
void *ClientThread(void *arg)
{
struct client_arg *ca = (struct client_arg *)arg;
int i;
for(i=0; i < ca->order_count; i++) {
......
queued = 0;
while(queued == 0) {
pthread_mutex_lock(&(ca->order_que->lock));
......
if(next == ca->order_que->tail) {
pthread_mutex_unlock(&(ca->order_que->lock));
continue;
}
......
pthread_mutex_unlock(&(ca->order_que->lock));
......
}
}
return(NULL);
}
Could anyone tell me what's the difference between these two cases and why I need declare the mutex in this way?
A:
Could anyone tell me what's the difference between these two cases and why I need declare the mutex in this way?
Generally speaking, mutex is designed to synchronize accesses (protect against race conditions) to a resource. Thus mutex declaration often follows the declaration of the resource it is intended to protect.
In case #1, the mutex syncs accesses to the global variable count - and thus it is declared globally, along with the variable. It guarantees that, when the increment_count() is called on different CPUs from different threads, the non-atomic arithmetics on the count variable would be performed in a consistent fashion, producing expected results.
In case #2, the mutex syncs accesses to the order_que ring buffer which (apparently) might be accessed from multiple threads. (Appears to be code for a job queue: the queue of items/jobs/etc, the threads should process in parallel.) The generic ring buffer requires arithmetics on the head and the tail pointers to enqueue and dequeue items. To guarantee the consistent results of the arithmetics on the head/tail (missing from your example) the mutex is used to synchronize the accesses to them. Thus the mutex is declared in the same context as the variables.
| |
doc_3938
|
I assume perl2exe is a tool that serves this purpose. More or less.
When I am trying to generate the exe file, I am getting library issues.
One of the library issues is:
Warning: Can't locate VMS/Stdio.pm
at C:\Perl\lib\File\Temp.pm line 19
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
When I went to line 19 of Temp.pm, the line is written as follows:
require VMS::Stdio if $^O eq 'VMS';
But,my OS is MSWin32.
I am coming to a conclusion that, perl2exe is not compiling the script properly. Its reading my OS wrong.
Sample script is as follows:
my_libraries.pl
use Tk;
use lib 'C:\Perl\lib\Digest';
use strict;
use strict;
use warnings;
use strict;
use warnings;
use LWP::Simple qw(getstore);
use LWP::UserAgent;
use Digest::MD5 qw( md5_hex );
use Digest::MD5::File qw( file_md5_hex );
use File::Fetch;
use WWW::Mechanize ;
use Tk::ErrorDialog;
c:\perl2exe\perl2exe-16.00-Win> perl2exe my_libraries.pl my_libraries.exe
Warning: Can't locate File/BSDGlob.pm
at C:\Perl\lib\File\GlobMapper.pm line 13
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
Warning: Can't locate Digest/Perl/MD5.pm
at C:\Perl\lib\Digest\MD5.pm line 30
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
Warning: Can't locate VMS/Stdio.pm
at C:\Perl\lib\File\Temp.pm line 19
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
Warning: Can't locate VMS/DCLsym.pm
at C:\Perl\lib\IPC\Cmd.pm line 227
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
Warning: Can't locate VMS/Filespec.pm
at C:\Perl\lib\ExtUtils\Manifest.pm line 31
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
Warning: Can't locate HTML/FormatText.pm
at C:\Perl\lib\HTML\Element.pm line 1297
@INC = C:\Perl\site\lib, C:\Perl\lib, ., C:\Perl\lib\Digest, must be directory, not file)
Sorry. let me put my obvious question here:
Why is perl2exe giving library issues which are not intended to come? Is it a bug in perl2exe or am I doing something wrong?
I mean, you can see in line 19 that if the OS is 'VMS', then stdio.pm is required. My os is 'MSWin32'.
A: I tried a to z possible remediation to make the perl2exe work. I removed the sections that was producing warnings (Hacked the modules). Studied and tried various flags. I have to say it is not at all feasible to convert Perl programs using diverse modules to exe files using perl2exe.
I found a software that exactly did what I wanted- Cava Packager.
It took sometime to find the below page-
How can I package my Perl script to run on a machine without Perl?
It converted my Perl program to Exe and also generated an installation file. Awesome.
Thanks,
Anoop.
A: The problem is
C:\Perl\lib\File\Temp.pm line 19
Open the file you will see this
require VMS::Stdio if $^O eq 'VMS';
Change the file not read-only, then place # for this line, go back to perl2exe the file again, then it should be gone.
A: It may be of interest to readers of this issue that in addition to the VMS/Stdio.pm error, I also received "Can't locate the.pm". The line in my perl code that it pointed to was the text "Use the 't' command..." that was inside a double-quoted print statement. Apparently perl2exe looked for the 'use' statement regardless of where in my code it appeared. The fix was to either re-word the text to remove the word 'use' or put the text in single quotes.
| |
doc_3939
|
trap '' SIGTERM
python main.py
and Python script (main.py).
import time
from multiprocessing import Pool
def f(i):
print(i + 1)
if __name__ == '__main__':
with Pool(processes=3, maxtasksperchild=1) as pool:
pool.starmap(
f,
[(i,) for i in range(10)]
)
when I run this script, it did not finish (and I must kill -9 <pid>).
> chmod +x ./run.sh
> ./run.sh
1
2
3
...
8
9
<--- stop here
But when I add time.sleep(1) after with block, it finished.
if __name__ == '__main__':
with Pool(processes=3, maxtasksperchild=1) as pool:
pool.starmap(
f,
[(i,) for i in range(10)]
)
time.sleep(1) # added this line
Why adding "sleep 1 sec" fix the issue?
Or, why "trapping SIGTERM" have no effect when I added "sleep 1 sec" ?
*
*Python 3.8.13
*tested on MacOS Big Sur and Windows WSL2 (Ubuntu)
| |
doc_3940
|
I am running this in the command line and getting the following error:
myname@MacBook-Pro-8 ~> brew install postgresql
Warning: postgresql 10.4 is already installed, it's just not linked
You can use `brew link postgresql` to link this version.
myname@MacBook-Pro-8 ~> brew link postgresql
Linking /usr/local/Cellar/postgresql/10.4...
Error: Could not symlink share/man/man7/ABORT.7
/usr/local/share/man/man7 is not writable.
myname@MacBook-Pro-8 ~> sudo brew link postgresql
Password:
Error: Running Homebrew as root is extremely dangerous and no longer supported.
As Homebrew does not drop privileges on installation you would be giving all build scripts full access to your system.
I also tried:
brew prune; brew link postgresql
which gave me the same error:
Error: Could not symlink share/man/man7/ABORT.7
/usr/local/share/man/man7 is not writable.
Why is that folder not writable and what can I do to change that?
A: It was really painful solving this problem, so I figured I would leave it here for others to see.
Issue:
Homebrew install of Postgresql will not execute successfully. $ brew link postgresql results in failure due to directory not writable. New version of Homebrew will not allow sudo commands and System Integrity Protection prevents changing permissions.
Details:
I tried to use homebrew to install postgres and kept running into issues with syslink. When I ran $ brew link postgresql as homebrew suggested, I kept running into an error that it couldn't be completed because certain folders were not writable. I thought this would be easily remedied by running sudo but unfortunately the most current version of homebrew no longer allows the use of sudo commands due to security risks. My next thought was to my root user and use the macOS GUI interface to change the permissions on this folder because I am not sure how to do this on the terminal. Regardless of being logged in as 'root,' the OS would not let me change the permissions of the folder. I also attempted to use sudo and change the permissions in terminal and it did not work either. After several days of banging my head against the wall try all kinds of things to find a solution, I discovered that since El Capitan, macOS introduced System Integrity Protection aka 'SIP' or 'rootless.' As it turned out, once I disabled SIP, logged back into 'root' and changed my regular accounts permissions to Read/Write on the problem directories, I was able to go back to my regular account and successfully execute $ brew install postgresql.
(Assuming you currently have postgresql installed through homebrew but unable to link due a scenario like the one mentioned above, here is what I suggest to resolve your issue...)
*
*Run $ brew link postgresql
*Write down the directory path that the error says it is not able to write to. (e.g. usr/local/share/man/man7) NOTE: you'll want to actually write this down on paper or take a picture of the screen on your phone because you will not be able to use copy and paste)
*Enable your 'root' user account if you have not already done so.
(instructions here) NOTE: make sure to make a really good password for this account and write it down somewhere safe. This is a powerful account and there's no way to recover the password.
*Disable System Integrity Protection.
(instructions here)
*Log into 'root' user account
*In Finder menu bar select GO > GO TO FOLDER... (CMND + SHFT + G) and type in the path from Step 2.
*Right-Click/ Cntrl-Click the folder and select Get Info
*Click the plus sign at the bottom of Sharing & Permissions
*Add your regular account to the list and change the permission to Read & Write
*Go back to your regular account, run $ brew uninstall postgresql, then $ brew update and $ brew doctor . If those are all set run $ brew install postgresql.
*You should be able to install without any problems now. However, if you run into a linking and permissions problem again, run $ brew link postgresql to figure out the problematic directory and repeat Steps 5 - 10 with whatever other directories are giving you trouble.
*If everything is up and running properly. It is probably best to at least enable SIP again (instruction in the article linked in Step 4).
(To check that everything is working. I recommend running $ brew services start postgresql then $ createdb 'test' . In my case, it was when I originally tried to run createdb and got "command not found" that I realized something was wrong.)
A: Running this solves it. This gets around SIP.
sudo chown -R $(whoami) $(brew --prefix)/*
brew link postgresql
| |
doc_3941
|
http://www.mulesoft.org/documentation/display/current/Batch+Processing
Update - I got this to work looks like there is an issue with the filter on one of the batch steps and should be
but is
Logs published below(Mule version 3.5.2EE, SalesForce v5.4.10
INFO 2015-01-24 12:50:59,951
[[batchexample].connector.file.mule.default.receiver.01]
org.mule.transport.file.FileMessageReceiver: Lock obtained on file:
C:\MuleProjects\MuleTraining\batchexample\src\test\resources\input\sample_data_1
copy.csv
INFO 2015-01-24 12:51:00,052
[[batchexample].connector.file.mule.default.receiver.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance
8e6fb990-a3f1-11e4-9375-74e50bd0f700 for batch job Create_Leads
INFO 2015-01-24 12:51:00,056
[[batchexample].connector.file.mule.default.receiver.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input
phase
INFO 2015-01-24 12:51:00,591
[[batchexample].connector.file.mule.default.receiver.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase
completed
INFO 2015-01-24 12:51:00,600
[[batchexample].connector.file.mule.default.receiver.01]
com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting
loading phase for instance '8e6fb990-a3f1-11e4-9375-74e50bd0f700' of
job 'Create_Leads'
INFO 2015-01-24 12:51:00,649
[[batchexample].connector.file.mule.default.receiver.01]
com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished
loading phase for instance 8e6fb990-a3f1-11e4-9375-74e50bd0f700 of job
Create_Leads. 9 records were loaded
INFO 2015-01-24 12:51:00,654
[[batchexample].connector.file.mule.default.receiver.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution
of instance '8e6fb990-a3f1-11e4-9375-74e50bd0f700' of job
'Create_Leads'
INFO 2015-01-24 12:51:03,969 [batch-job-Create_Leads-work-manager.01]
com.mulesoft.module.batch.DefaultBatchStep: Step lead-check finished
processing all records for instance
8e6fb990-a3f1-11e4-9375-74e50bd0f700 of job Create_Leads
INFO 2015-01-24 12:51:03,978 [batch-job-Create_Leads-work-manager.08]
com.mulesoft.module.batch.DefaultBatchStep: Step Batch_Step finished
processing all records for instance
8e6fb990-a3f1-11e4-9375-74e50bd0f700 of job Create_Leads
INFO 2015-01-24 12:51:04,002 [batch-job-Create_Leads-work-manager.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting
execution of onComplete phase for instance
8e6fb990-a3f1-11e4-9375-74e50bd0f700 of job Create_Leads
INFO 2015-01-24 12:51:04,028 [batch-job-Create_Leads-work-manager.01]
org.mule.api.processor.LoggerMessageProcessor: 9 Loaded Records 0
Failed Records
INFO 2015-01-24 12:51:04,028 [batch-job-Create_Leads-work-manager.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Finished
execution of onComplete phase for instance
8e6fb990-a3f1-11e4-9375-74e50bd0f700 of job Create_Leads
INFO 2015-01-24 12:51:04,029 [batch-job-Create_Leads-work-manager.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine: Finished
execution for instance '8e6fb990-a3f1-11e4-9375-74e50bd0f700' of job
'Create_Leads'. Total Records processed: 9. Successful records: 9.
Failed Records: 0
INFO 2015-01-24 12:51:04,031 [batch-job-Create_Leads-work-manager.01]
com.mulesoft.module.batch.engine.DefaultBatchEngine:
INFO 2015-01-24 12:51:04,042 [batch-job-Create_Leads-work-manager.01]
com.mulesoft.module.batch.DefaultBatchStep: Step log-failures finished
processing all records for instance
8e6fb990-a3f1-11e4-9375-74e50bd0f700 of job Create_Leads
| |
doc_3942
|
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of ...
| |
doc_3943
|
To generate a random number, I am using the following function:
Int((900-100+1)*Rnd()+100)
This function generates the number randomly between 100 and 900 for the first record returned in the query. The problem is that each record below that 1st record contains the same number, hence creating duplicated serial numbers for each record returned in the query.
What I need is to either implement an increment function that can increase the value of the original randomly generated number by 1, or create syntax that tells Access to randomly generate numbers without the 100-900 range for all records returned without the possibility of a duplicate number assigned.
Thank you SO MUCH in advance for the help!
Erik
A: You must seed Rnd. The traditional method is to Timer for that:
=Int((900-100+1)*Rnd(-Timer())+100)
To prohibit dupes, have in mind please, that random is random, thus the only method is to check that each generated number hasn't been used before - and if it has, run the function again.
This means, that when you approach the limit, it will take more and more loops to generate an unused number.
| |
doc_3944
|
! Processes have temporarily been disabled.
Attempting to run from collaborator or owner results in same issue. I have a trouble-ticket in with Heroku with no response, yet. Their status app says everything is fine right now. I can console into other apps in my account, just not this one.
How to fix?
A: From heroku: "This was caused by an lock placed on your application during the shared database migration some time ago; in the vast majority of cases, this lock was automatically removed when the migration finished, but it appears a small handful of applications did not get this flag removed."
| |
doc_3945
|
> Sys.getlocale()
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
My classmate gave me a UTF8 csv file sample.csv produced in linux system,this file can be produced by php script as below:
<?php
$a=
array (
'col1' => 12,
'col2' => 'Y' ,
'col3' => '<p style="text-align: center;">
<strong style="text-align: center;"><span style="color: rgb(105, 105, 105); font-family: verdana, arial, sans-serif; font-size: 13px;">版权</span></strong></p>
<p>
<span style="color: rgb(105, 105, 105); font-family: verdana, arial, sans-serif; font-size: 13px;">bla</span></p>
<p>
<span style="color: rgb(105, 105, 105); font-family: verdana, arial, sans-serif; font-size: 13px;"><img alt="" src="/functions/2.jpg" style="width: 400px; height: 500px;" /></span></p>
<p>
<span style="color: rgb(105, 105, 105); font-family: verdana, arial, sans-serif; font-size: 13px;">bla</span></p>
' ,
'col4' => '<br />
' );
$fp = fopen("sample.csv", "wb");
$question_list_cols=array('col1','col2','col3','col4');
fputcsv($fp, $question_list_cols);
if (!fputcsv($fp, array_values($a))) {
echo "fail<br />";
}
fclose($fp);
?>
When I read sample.csv in R df<-read.csv("sample.csv",header=TRUE), I got error invalid input found on input connection.
I tried similar questions in SO, but no one is workable.
The problem caused by Chinese characters 版权. Everything is OK when I remove these Chinese Characters.
How to read utf8 csv with Chinese character in R?
| |
doc_3946
|
<ui:define name="content" >
<h:outputScript name="js/graphics/paths.js"/>
<h:outputScript name="js/graphics/draw.js"/>
Tag to be evaluated when function is called(is that possible)?
function showMap(){
var data = {
<c:forEach items="${list.KPI}" var="ctag" varStatus="loop">
'${ctag.USTER}': ${ctag.Value}
${!loop.last ? ',' : ''}
</c:forEach>
}
}
Error:
Is it possible to use jstl with facelets? Why am i getting this error? I am using there links:
1) is it possible for javascript to extract value from cforeach tag
2) populating-javascript-array-from-jsp-list
A: Surely JSTL works in Facelets. There are only some technical implications which can only be understood by really understanding the Facelets lifecycle: JSTL in JSF2 Facelets... makes sense?
As to your concrete problem, you most likely forgot to declare the JSTL taglib in the XML namespace.
xmlns:c="http://java.sun.com/jsp/jstl/core"
Not doing so would cause the JSTL tags not being interpreted at all and end up in a syntax error in the generated HTML/JS code because JSTL tags are not recognizeable by the webbrowser as valid HTML/JS code. Rightclick page in webbrowser and do View Source. You should not see any unparsed/plain JSTL tags in there.
| |
doc_3947
|
This is difficult for me to explain, I don't know why, maybe I am lacking the terminology.
What I am trying to do is have 1 type that can register several observables with it, so I can pass this type around and group up all the observables and expose a a single observable from it.
So my first question I get a feeling I am not thinking about things in the correct way, I was wondering if this correct or there is a more "reactive" way of doing it?
What I mean by this is that I have this type that you can register observables with and also this same type will expose the single Observable that I can also subscribe to.
I will try to explain it a little with a code example below.
So, the SomeTypeWithObservable just could be one of many types that will expose an IObservable<SomeEvents>
The ReactiveTesting type is the type that tries to group all the observables together and exposes a single IObservable<SomEvents>. There is a RegisterObservable method which will send it to the internal Subject<IObservable<SomeEvents>>. The constructor sets up the Observable I want to expose as being a SelectMany of this subject.
Using the below implementation, in the ReactiveTesting constructor I perform a SelectMany.Publish.RefCount, following with a dummy subscription to start the observable, I noticed if I didn't use the dummy subscription the registration of observables are not used.
So my second question is that code OK to have a dummy subscription to start off the observable, or should I do what I did underneath in the comment where I just had a connectable from Publish and then connected it immediately after, or they are both wrong and in that case, could someone point me in the right direction?
My third question Should I be using a subject?
If I call RegisterObservable earlier than the subscriptions and if I don't put the dummy Subscribe in or the Connect then I won't observer any of the events triggered.
My Fourth question Could someone explain the latter please?
I am kind of thinking that because it is Publish and RefCount then there is nothing to do until there is a subscription which starts off the Observable.
The code
--Edited - To show there is more than one observable I want to register in ReactiveTesting
enum SomeEvents
{
event1,
event2,
event3,
event4
}
interface ISomeTypeWithObservable
{
IObservable<SomeEvents> SomeObservableEvents { get; }
}
class SomeTypeWithObservable2 : ISomeTypeWithObservable
{
private event EventHandler SpecialEvent;
public SomeTypeWithObservable2()
{
var observableFromSpecialEvent = Observable.FromEventPattern(h => SpecialEvent += h, h => SpecialEvent -= h).Select(x => SomeEvents.event2);
SomeObservableEvents = Observable.Create<SomeEvents>(observer =>
{
return observableFromSpecialEvent.Subscribe(observer);
})
.Publish()
.RefCount();
}
public IObservable<SomeEvents> SomeObservableEvents { get; }
public void TriggerEvent()
{
SpecialEvent.Invoke(this, new EventArgs());
}
}
class SomeTypeWithObservable : ISomeTypeWithObservable
{
private event EventHandler SpecialEvent;
public SomeTypeWithObservable()
{
var observableFromSpecialEvent = Observable.FromEventPattern(h => SpecialEvent += h, h => SpecialEvent -= h).Select(x => SomeEvents.event1);
SomeObservableEvents = Observable.Create<SomeEvents>(observer =>
{
return observableFromSpecialEvent.Subscribe(observer);
})
.Publish()
.RefCount();
}
//Some code in here that will produce things to observe, maybe Observable.FromEventPattern...
public IObservable<SomeEvents> SomeObservableEvents { get; }
public void TriggerEvent()
{
SpecialEvent.Invoke(this, new EventArgs());
}
}
class ReactiveTesting
{
private Subject<IObservable<SomeEvents>> _innerEvents = new Subject<IObservable<SomeEvents>>();
public IObservable<SomeEvents> AllEvents;
public ReactiveTesting()
{
AllEvents = _innerEvents.SelectMany(x => x).Publish().RefCount();
AllEvents.Subscribe(next => { }, exception => { }, () => { });
//This instead of the above??
//var connectableObservable = _innerEvents.SelectMany(x => x).Publish();
//AllEvents = connectableObservable;
//connectableObservable.Connect();
}
public void RegisterObservable(ISomeTypeWithObservable someTypeWithObservable)
{
_innerEvents.OnNext(someTypeWithObservable.SomeObservableEvents);
}
}
class Program
{
static void Main(string[] args)
{
var reactiveTesting = new ReactiveTesting();
var someTypeWithObservable = new SomeTypeWithObservable();
var someTypeWithObservable2 = new SomeTypeWithObservable2();
reactiveTesting.AllEvents.Subscribe(next => Console.WriteLine(string.Format("Subscriber 1 - {0}", next.ToString("G"))));
reactiveTesting.AllEvents.Subscribe(next => Console.WriteLine(string.Format("Subscriber 2 - {0}", next.ToString("G"))));
reactiveTesting.RegisterObservable(someTypeWithObservable);
reactiveTesting.RegisterObservable(someTypeWithObservable2);
someTypeWithObservable.TriggerEvent();
someTypeWithObservable.TriggerEvent();
someTypeWithObservable.TriggerEvent();
someTypeWithObservable2.TriggerEvent();
someTypeWithObservable2.TriggerEvent();
someTypeWithObservable2.TriggerEvent();
Console.WriteLine("Press key...");
Console.ReadLine();
}
}
A:
So my first question I get a feeling I am not thinking about things in
the correct way, I was wondering if this correct or there is a more
"reactive" way of doing it?
Using a Subject in ReactiveTesting is normally a cue that you have some imperative code that could be eliminated, or pushed further out. It may require re-writing some of your surrounding code. In this case, you would end up with something like this:
class ReactiveTesting
{
public IObservable<SomeEvents> AllEvents { get; }
public ReactiveTesting(IObservable<IObservable<SomeEvents>> eventSource)
{
AllEvents = eventSource.Merge().Publish().RefCount();
}
}
class Program
{
public static void Main(string[] args)
{
var someTypeWithObservable = new SomeTypeWithObservable();
var reactiveTesting = new ReactiveTesting(Observable.Return(someTypeWithObservable.SomeObservableEvents));
reactiveTesting.AllEvents.Subscribe(next => Console.WriteLine(string.Format("Subscriber 1 - {0}", next.ToString("G"))));
reactiveTesting.AllEvents.Subscribe(next => Console.WriteLine(string.Format("Subscriber 2 - {0}", next.ToString("G"))));
someTypeWithObservable.TriggerEvent();
someTypeWithObservable.TriggerEvent();
someTypeWithObservable.TriggerEvent();
Console.WriteLine("Press key...");
Console.ReadLine();
}
}
So my second question is that code OK to have a dummy subscription to
start off the observable, or should I do what I did underneath in the
comment where I just had a connectable from Publish and then connected
it immediately after, or they are both wrong and in that case, could
someone point me in the right direction?
It shouldn't be necessary. It works for me the same as removing it. Dummy subscription helps with .Replay().Refcount(). I don't see the point with .Publish().
My third question Should I be using a subject?
They're a code smell basically. If you can eliminate them, or push them away from your business logic, you're better off.
| |
doc_3948
|
model = Sequential()
model.add(layers.LSTM(100, input_shape=(None,1)))
model.add(Conv1D(256, 8, padding='same', activation="relu"))
model.add(Conv1D(256, 8, padding='same', activation="relu"))
model.add(Dropout(0.25))
model.add(MaxPooling1D(pool_size=(8)))
model.add(Conv1D(128, 8, padding='same', activation="relu"))
model.add(Conv1D(128, 8, padding='same', activation="relu"))
model.add(Conv1D(128, 8, padding='same', activation="relu"))
model.add(Conv1D(128, 8, padding='same', activation="relu"))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=(8)))
model.add(Conv1D(64, 8, padding='same', activation="relu"))
model.add(Conv1D(64, 8, padding='same', activation="relu"))
#model.add(Flatten())
model.add(bidirectionnel(layers.LSTM(256)))
model.add(Dense(256, activation="relu"))
model.add(Dropout(0.3))
model.add(Dense(2))
model.add(Activation('softmax'))
model.compile(optimizer="Adam",
loss="binary_crossentropy",
metrics = ['accuracy'])
but i keep getting this error
Input 0 of layer conv1d_3 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (None, 100)
it works with replacing the firrst lstm layer with a cnn layer with fixed inputs but i want to have a flexible input layer for inference i know that 0 padding is a solution but during inference i cannot define the max length of my audio
A: LSTMs, or RNNs in general, are fundamentally incapable of dealing with varying length of input. It is one of the motivations behind transformer architectures (as you might have noticed by adding CNN in front).
You probably want to do padding or apply transformer-like architecture.
| |
doc_3949
|
Im working on page using
const transform = (data) => {
if (option === 'status') {
return {
comment: data.comment,
ids: udiEditDisplayInfo.selectedIds,
status: data.statusToBe,
};
} else if (option === 'customer') {
console.error('Transform option is Customer!!');
//To be implemented
}
};
return (
<Edit {...props} actions={<TopToolbar />} transform={transform} onSuccesss={onSuccess} onFailure={onFailure}>
<SimpleForm toolbar={<CustomToolbar />} redirect={false}>
...
<RadioGroup name="option" value={option} onChange={handleChange}>
<FormControlLabel value="customer" control={<Radio />} label="Customer" />
...
)
when Radio button clicked, 'option' state changed.
the problem is .. in transform method, they can not recognize the change of option state!
options is still default value(customer)
somebody help me please..
| |
doc_3950
|
The array at the top of the file
var item = [ // fix bad needs update dirty fix
{ "dirty": " " },
{ "tclass": "", "Order": '', "Fulltitle:": '', "ItemOrderUpdated": false },
{ "tclass": "", "Order": '', "Fulltitle:": '', "ItemOrderUpdated": false },
{ "tclass": "", "Order": '', "Fulltitle:": '', "ItemOrderUpdated": false },
]
function UpdatVal(txt, ordernum, currnety) {
item[currnety].ItemOrderUpdated = true; // locks this item into being changed
item[currnety].Fulltitle = txt
item[currnety].Order = ordernum
cy.log(`Updating local values ${(item[currnety].Fulltitle)} ${(item[currnety].Orderin)}`) // how to make global
}
I call this function when I want to update the data and when I read it its fine and i get the expect result.
cy.log("SUM UP") // at the end of the file
cy.log(`t1 test local: ${(item[1].tclass)} order:${item[1].Order} Fulltitle:${item[1].Fulltitle} has been updated:${item[1].ItemOrderUpdated}`)
cy.log(`t2 test local ${(item[2].tclass)} order:${item[2].Order} Fulltitle:${item[2].Fulltitle} has been updated:${item[2].ItemOrderUpdated}`)
cy.log(`t3 test local ${(item[3].tclass)} order:${item[3].Order} Fulltitle:${item[3].Fulltitle} has been updated:${item[3].ItemOrderUpdated}`)
But at the end of the file I check the values again and it comes back as undefined
| |
doc_3951
|
style="border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">
However it has no effect at all even when I tweak the width etc., what am I missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="AnimalGrid" style="border:solid; border-width:2px; border-color:lightgray; padding-left:12px;padding-top:8px;margin:10px">
<table style="width:100%">
<tr>
<td style="font-family:Calibri; font-size:large; color:midnightblue; text-align:left"><b>RESULT DETAILS</b></td>
</tr>
<tr>
<td style="width:25%; font-size:large; padding-left: 2px"><i>Animal<sup>1</sup></i></td>
<td style="width:25%; font-size:large; padding-left: 6px"><i>Animal</i></td>
<td style="width:25%; font-size:large; padding-left: 6px"><i>Speed<sup>2</sup></i></td>
<td style="width:25%; font-size:large; padding-left: 6px"><i>Type<sup>3</sup></i></td>
</tr>
<tr style="border-bottom-style:dotted; border-bottom-color: black; border-bottom-width:2px">
<td style="width:25%; font-size:large; padding-left: 6px">Cheetah</td>
<td style="width:25%; font-size:large; padding-left: 6px">Tiger</td>
<td style="width:25%; font-size:large; padding-left: 6px">60mph</td>
<td style="width:25%; font-size:large; padding-left: 6px">Carnivore</td>
</tr>
<tr style="border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">
<td style="width:25%; font-size:large; padding-left: 6px">Lion</td>
<td style="width:25%; font-size:large; padding-left: 6px">Zebra</td>
<td style="width:25%; font-size:large; padding-left: 6px">40mph</td>
<td style="width:25%; font-size:large; padding-left: 6px">Mixed</td>
</tr>
<tr style="border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">
<td style="width:25%; font-size:large; padding-left: 6px">Horse</td>
<td style="width:25%; font-size:large; padding-left: 6px">Cow</td>
<td style="width:25%; font-size:large; padding-left: 6px">10mph</td>
<td style="width:25%; font-size:large; padding-left: 6px">Herbivore</td>
</tr>
</table>
</div>
</body>
</html>
A: Like this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="AnimalGrid" style="border:solid; border-width:2px; border-color:lightgray; padding-left:12px;padding-top:8px;margin:10px">
<table style="width:100%">
<tr>
<td style="font-family:Calibri; font-size:large; color:midnightblue; text-align:left"><b>RESULT DETAILS</b></td>
</tr>
<thead>
<th style="width:25%; font-size:large; padding-left: 2px"><i>Animal<sup>1</sup></i></th>
<th style="width:25%; font-size:large; padding-left: 6px"><i>Animal</i></th>
<th style="width:25%; font-size:large; padding-left: 6px"><i>Speed<sup>2</sup></i></th>
<th style="width:25%; font-size:large; padding-left: 6px"><i>Type<sup>3</sup></i></th>
</thead>
<tr>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Cheetah</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Tiger</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">60mph</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Carnivore</td>
</tr>
<tr>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Lion</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Zebra</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">40mph</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Mixed</td>
</tr>
<tr>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Horse</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Cow</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">10mph</td>
<td style="width:25%; font-size:large; padding-left: 6px; border-bottom:dotted; border-bottom-color: black; border-bottom-width:2px">Herbivore</td>
</tr>
</table>
</div>
</body>
</html>
| |
doc_3952
|
Flask: 0.9
Hi, I want to make car simulator using Apscheduler. Each car has distance column in the database that will be incremented regularly.
Here's the import part
from __future__ import with_statement
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash, views
from sqlite3 import dbapi2 as sqlite3
from contextlib import closing
from apscheduler.scheduler import Scheduler
and here's the snippet of the code:
sched = Scheduler()
sched.add_interval_job(moveAllCars, seconds = 5)
sched.start()
def moveAllCars():
print "debug 1"
dbCommand = g.db.execute('SELECT CarID FROM Car')
print "debug 2"
#and so on
I did not write the full code because the error happened right after 'debug 1' with the error message: no handlers could be found for logger "apscheduler.scheduler". Google does not help much.
But the scheduler is still running, printing only 'debug1' every 5 seconds. The error message only come out during the first loop.
Anyone know the solution? Thanks before
[UPDATE]
After using logging, I found out it is RunTimeError: working outside of request context. Is there any other solution other than using with app.test_request_context?
A: g is probably a threading.local(). Different threads see different values in it.
g.db is probably assigned a new db connection per request. No current request – no connection.
You could create db connection in move_all_cars() or pass it explicitly as a parameter.
A: from os import getcwd
import logging
logging.basicConfig(
filename=''.join([getcwd(), '/', 'log_file_name']),
level=logging.DEBUG,
format='%(levelname)s[%(asctime)s]: %(message)s'
)
Above did help in my case.
KAcper
| |
doc_3953
|
<div class="container-fluid">
<form class="form-signin" action="" method="post" style="max-width:500px; margin-left:auto; margin-right:auto;">
<h2 class="form-heading">Yeni Musteri Kayit</h2>
<div class="panel panel-success">
<div class="panel-body">
<div class="form-group">
<label for="adsyd">Ad Soyad</label>
<input type="text" id="adsyd" name="adsoyad" class="form-control" placeholder="Ad Soyad" required autofocus>
</div>
<div class="form-group">
<label for="name">Telefon Numarasi</label>
<input type="text" id="tel" name="tel" class="form-control" placeholder="Telefon Numarası" required autofocus>
</div>
<div class="form-group">
<label for="surname">Adres</label>
<input type="text" id="adres" name="adres" class="form-control" placeholder="Adres" required autofocus>
</div>
<div class="form-group">
<label for="surname">Kayit Tarihi</label>
<input type="text" id="kyt" name="kyt" class="form-control" placeholder="Kayıt Tarihi" required autofocus>
</div>
</div>
</div>
<button class="btn btn-success btn-block" type="submit">Kaydet</button>
</form>
</div>
<?php
if(isset($_POST['adsoyad'])) {
$db = new mysqli('localhost', 'root', '1234', 'esranur');
if($db->connect_errno) die ('Bağlantı hatası:' . $db->connect_errno);
$stmt=$db->prepare("insert into musteri values (NULL,?,?,?,?)");
if($stmt === FALSE) die("Sorgu hatası". $db ->error);
$stmt->bind_param("sss", $_POST['adsoyad'],$_POST['telefon'],$_POST['adres']);
$stmt->execute();
?>
I dont have problem with html and css codes but when i try to add php code after last div it doesn't recognize the code, it recognize like text and doesn't run code, just print like text. Am I doing it with wrong place? I working with netbeans. Thank you
A: i still have same problem. i moved my project file into xampp/htcdocs. here my path ; file:///C:/xampp/htdocs/mine/new.php and here my php code;
You are not running your file on localhost and rather file:///
Change your url from this:
file:///C:/xampp/htdocs/mine/new.php
to this:
http://localhost/mine/new.php
A: create a folder test in C:/xampp/htdocs/, result : C:/xampp/htdocs/test
copy all project to test folder.
open a browser and go to this address: http://localhost/test
*
*You must have an active apache service on your machine(Ex. Windows).
*apache must be in run mode without error!
*all .html files that have php code in it, muse change to .php
*If http://localhost/test not work, write your file name end of address(Ex. http://localhost/test/my_file.php);
A: Install a apache webserver server for example wamp:
http://www.wampserver.com/en/
Watch some tutorials about it.
A: Put a info.php file on your server having code
<?php phpinfo(); ?>
if this code execute and show you server information then your server configuration is ok and your file name is added with some other extention, if not then you need to first setup it.
| |
doc_3954
|
Input:
x <- c(1, 2, 3, 11, 15)
y <- c(1.1, 1.2, .4, 2.1, 1.5)
plot(log2(x + 1), y, axes=FALSE)
axis(1, at=(labels=as.character(formatC(x))), cex.axis=0.9)
But plot I get still has the original x-axis values.
How can I make my x-axis powers of 2 (1, 2, 4, 16, etc.)?
A: I guess this is what you want.
x<-c(1,2,3,11,15)
y<-c(1.1,1.2,.4,2.1,1.5)
lab<-c(1,2,4,16)
plot(log2(x+1),y,xaxt="n",xlab="x")
axis(1,at=log2(lab+1),labels=lab)
It might also be useful to calculate equally spaced labels:
lab<-round(2^seq(min(log2(x+1)),max(log2(x+1)),length.out=4)-1)
| |
doc_3955
|
rdd1 = sc.parallelize([("cat", [1,2,3,4])])
rdd2 = sc.parallelize([(1, 100), (2, 201), (3, 350), (4, 400)])
What would be the most optimized way of getting:
rdd_expected = sc.parallelize([("cat", [1,2,3,4], [100, 201, 350, 400])])
| |
doc_3956
|
public static void StartWithErrorLogging(Func<Task> task, IAresLogger logger, CancellationToken token = default(CancellationToken))
{
new Task(async () =>
{
try
{
await task.Invoke();
}
catch (Exception e)
{
logger?.Log(LogMessageSeverity.Error, e.Message, e);
}
}, token).Start();
}
Which is called by using the following code:
ErrorLoggedTask.StartWithErrorLogging(async () => await _recentSearchRepository.InsertAsync(new RecentSearch
{
AuthUserId = user.Subject.UserAuthId,
SearchDate = DateTimeOffset.Now,
SearchText = filter.SearchTerm
}, token), _logger, token);
Sometime it raises the following exception:
{
"exception" : "System.InvalidOperationException: Start may not be called on
a task that has completed.\r\n at
System.Threading.Tasks.Task.Start(TaskScheduler scheduler)\r\n at
Ares.Core.Scheduling.ErrorLoggedTask.StartWithErrorLogging(Func`1 task,
IAresLogger logger, CancellationToken token) in
C:\..\ErrorLoggedTask.cs:line 15\r\n at
Ares.Api.Controllers.SearchController.d__17.MoveNext() in
C:\...\SearchController.cs:line 97\r\n--- End of
stack trace from previous location where exception was thrown ---\r\n at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at
InvalidOperationException: Start may not be called on a task that has completed
What I can do in that?
A: You should never use the Task constructor.
A straightforward translation of your code using Task.Run instead would look like this:
public static void StartWithErrorLogging(Func<Task> task, IAresLogger logger)
{
Task.Run(async () =>
{
try
{
await task.Invoke();
}
catch (Exception e)
{
logger?.Log(LogMessageSeverity.Error, e.Message, e);
}
});
}
(I removed the CancellationToken, since it most likely wasn't doing anything useful anyway). In fact, the code you posted only causes that exception if the CancellationToken is cancelled before Start is called.
However, you almost certainly shouldn't use this code, because it is fire-and-forget on the threadpool, which is an antipattern on ASP.NET.
| |
doc_3957
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.text.DecimalFormat;
public class AverageGrades extends JFrame
{
//construct conponents
static JLabel title = new JLabel("Average of Grades");
static JTextPane textPane = new JTextPane();
static int numberOfGrades = 0;
static int total = 0;
static DecimalFormat twoDigits = new DecimalFormat ("##0.00");
//set array
static int[] grades = new int[50];
//create content pane
public Container createContentPane()
{
//create JTextPane and center panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(title);
JPanel centerPanel = new JPanel();
textPane = addTextToPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500,200));
centerPanel.add(scrollPane);
//create Container and set attributes
Container c = getContentPane();
c.setLayout(new BorderLayout(10,10));
c.add(northPanel,BorderLayout.NORTH);
c.add(centerPanel,BorderLayout.CENTER);
return c;
}
//method to add new text to JTextPane
public static JTextPane addTextToPane()
{
Document doc = textPane.getDocument();
try
{
// clear previous text
doc.remove(0,doc.getLength());
//insert title
doc.insertString(0,"Grades\n",textPane.getStyle("large"));
//insert grades and calculate average
for(int j=0; j<grades.length; j++)
{
doc.insertString(doc.getLength(), grades[j] + "\n", textPane.getStyle("large"));
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text");
}
return textPane;
}
//method to sort array
public void grades(int grdArray[])
{
//sort int array
for (int pass = 1; pass<grdArray.length; pass++)
{
for (int element = 0; element<grdArray.length -1; element++)
{
swap(grades, element, element + 1);
}
}
addTextToPane();
}
//method to swap elements of array
public void swap(int swapArray[], int first, int second)
{
int hold;
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
}
//execute method at run time
public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
AverageGrades f = new AverageGrades();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//accept first grade
int integerInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a grade (0-100) or -1 to calculate the average"));
//while loop accepts more grades, keeps count, and calulates the total
int count = 0;
int[] grades = new int[50];
int num = 0;
while (count<50 && num!= -1)
{
num = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a grade (0-100) or -1 to calculate the average" + (count+1)));
if(num!=-1)
grades[count] = num;
count++;
}
//create content pane
f.setContentPane(f.createContentPane());
f.setSize(600,375);
f.setVisible(true);
}
}
A: You are defining your grade array twice: once inside your class:
static int[] grades = new int[50];
then in main():
int[] grades = new int[50];
A: Here's the corrected code which solves your issues.
There were two major issues, you were using a local array grades instead of your static global array grades. (So remove the declaration from main)
Secondly, you were never inserting the first value integerInput which caused the first element to be lost.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.text.DecimalFormat;
class AverageGrades extends JFrame {
// construct conponents
static JLabel title = new JLabel("Average of Grades");
static JTextPane textPane = new JTextPane();
static int numberOfGrades = 0;
static int total = 0;
static DecimalFormat twoDigits = new DecimalFormat("##0.00");
// set array
static int[] grades = new int[50];
// create content pane
public Container createContentPane() {
// create JTextPane and center panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(title);
JPanel centerPanel = new JPanel();
textPane = addTextToPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 200));
centerPanel.add(scrollPane);
// create Container and set attributes
Container c = getContentPane();
c.setLayout(new BorderLayout(10, 10));
c.add(northPanel, BorderLayout.NORTH);
c.add(centerPanel, BorderLayout.CENTER);
return c;
}
// method to add new text to JTextPane
public static JTextPane addTextToPane() {
int counter = 0;
Document doc = textPane.getDocument();
try {
// clear previous text
doc.remove(0, doc.getLength());
// insert title
doc.insertString(0, "Grades\n", textPane.getStyle("large"));
//BREAKING IF NUMBER IS 0, SIGNIFIES THAT ALL ELEMENTS ARE COVERED
//counter IS USED TO CALCULATE THE TOTAL NUMBER OF ELEMENTS
// insert grades and calculate average
for (int j = 0; j < grades.length; j++) {
if (grades[j] != 0) {
doc.insertString(doc.getLength(), grades[j] + "\n",
textPane.getStyle("large"));
counter++;
} else {
break;
}
}
//THIS LINE INSERTS THE AVERAGE IN THE PANEL
doc.insertString(doc.getLength(), "Average is :"
+ (total / counter) + "\n", textPane.getStyle("large"));
} catch (BadLocationException ble) {
System.err.println("Couldn't insert text");
}
return textPane;
}
//CORRECT THE SORTING FUNCTION
// THE SORTING SHOULD BE IN REVERSE ORDER FOR YOUR REQUIREMENTS
// method to sort array
public void grades(int grdArray[]) {
// sort int array
for (int pass = 1; pass < grdArray.length; pass++) {
for (int element = 0; element < grdArray.length - 1; element++) {
swap(grades, element, element + 1);
}
}
addTextToPane();
}
// method to swap elements of array
public void swap(int swapArray[], int first, int second) {
int hold;
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
}
// execute method at run time
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
AverageGrades f = new AverageGrades();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// accept first grade
int integerInput = Integer.parseInt(JOptionPane.showInputDialog(null,
"Please enter a grade (0-100) or -1 to calculate the average"));
// while loop accepts more grades, keeps count, and calulates the total
int count = 0;
grades[0] = integerInput;
count++;
int num = 0;
while (count < 50 && num != -1) {
num = Integer.parseInt(JOptionPane.showInputDialog(null,
"Please enter a grade (0-100) or -1 to calculate the average"
+ (count + 1)));
//USING TOTAL FIELD TO CALCULATE SUM
if (num != -1) {
grades[count] = num;
total += grades[count];
}
count++;
}
//CALL THE SORTING FUNCTION AFTER CORRECTING IT
//f.grades(grades);
// create content pane
f.setContentPane(f.createContentPane());
f.setSize(600, 375);
f.setVisible(true);
}
}
| |
doc_3958
|
Here is my schema:
Root/
|_ includes
|_ db_connect.php
|_ functions.php
|_ var_list.php
|_ wp-includes
|_ wp-content
|_ themes
|_ NameTheme
|_ header.php
|_ wp-admin
I need to include this lines on my header.php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
include_once 'includes/var_list.php';
sec_session_start(); // function to start session, placed in functions.php
What I tryed:
*
*With $_SERVER['DOCUMENT_ROOT']
*With dirname(_FILE_)
*With ABSPATH // this are define on my wp-config.php
*With home_url
*With site_url
All return blank page (500 internal error)
Can help me, please?
Thanks.
A: If you have a standard wp-config.php file, ABSPATH should be defined. This means you should be able to use:
include_once(ABSPATH . 'includes/db_connect.php');
Read more in this related answer.
| |
doc_3959
|
A: I guess specflow uses nunit tests. you need to set up nunit in build server
http://www.mytechfinds.com/articles/software-testing/6-test-automation/72-running-nunit-tests-from-team-foundation-server-2012-continuous-integration-build
A: If you use SpecRun, it will automatically take care of TFS Build integration. Installing SpecRun is just referring the NuGet package from the SpecFlow project.
| |
doc_3960
|
Anyone came across any issues like this before? The PrinceXML documentation mentions that they support the background color and image.
A: Background Color
Prince seems to recognise border-color, but not color (text color) or background-color or background-image.
You can simulate a background color by using an after pseduo-element and a thick border. Prince renders this correctly.
CSS
.bgRED:after {
content: "";
display:block;
border-top: 25px solid red;
margin-top: -25px;
}
.bgRED-ib {display: inline-block;}
HTML
<p class='bgRED'>This is a p with a red background</p>
<span class='bgRED bgRED-ib span6'>This is a span with a red background</span>
This requires that you know the height of the element in pixels to make it work.
Background Images
I'm trying a similar thing with making a background image 'water-mark' across the whole page
Prince ignored CSS like this:
background-image: url(HUGE_sunset.jpg)
However I managed to get it to work using something like this:
HTML
<img class="behind" src='HUGE_sunset.jpg'>
<div class="infront">
<p>with the lights out, it's less dangerous, here we are now entertain us </p>
</div>
CSS
.behind {position: absolute; width:100%; height:100%; z-index:1;}
.infront {position: absolute; z-index:500;}
A: In the Prince docs it mentions that background-color defaults to transparent, and that color defaults to black. On a whim I tried adding the !important directive to my color/background-color styles and it worked.
I do not know what Prince has applied as its default style selectors in these cases, but it appears that it either applies its base styles after (or with some other more specific selectors) that necessitates this unpleasant !important war.
Without any way to inspect the applied styles it's a bit opaque, or I'd definitely recommend going a different route. Fortunately in my case the styles I need are specific to the Prince-generated pdf only. If you have styles you need to use both for Prince and web, I'd recommend posting it as a bug in the Prince forum and hope they fix it.
A: Here is a css of backgorund image for Prince Pdf
<style>
@page{
background: url(background.png) #ffffff;
-webkit-background-size: 100%;
prince-background-image-resolution: 72dpi;
background-position: 0px 0px;}
</style>
by the way if you want to use bootstrap , use version 3.7
| |
doc_3961
|
class base {
T &operator!() { return *this; }
};
base b; b = !b;
class child : public base {};
child c; c = !c;
Because of the operator, I can't just return the pointer and dynamic_cast it, it has to be a reference.
Is that even possible? Using decltype(*this) for T doesn't work, neither does auto f()->decltype(*this), because of this (although I don't understand why, in the auto-case)
In Scala you can write something like:
template<typename T> class base {
T &f() { return *this; }
};
class child : public base<child> {};
But my g++ won't accept this (not sure if that's bug or just not in the spec?)
Of course there's the explicit way, but I wonder if this can be avoided using C++11 features?
class child : public base {
child &operator!() { base::operator!(); return *this }
};
A: You can use the CRTP to do this if you're allowed to make base a template:
template <typename Derived> class Base {
protected:
Derived& refToThis() {
return *static_cast<Derived*>(this);
}
};
Note the extra cast here. The reason this works is that if you have a class like this one:
class Subclass: public Base<Subclass> {
/* ... */
};
Then if you call refToThis from inside that class, it will call the base class version. Since the class inherits from Base<Subclass>, the instantiated template for refToThis will be
Subclass& refToThis() {
return *static_cast<Subclass*>(this);
}
This code is safe, because the this pointer does indeed point to a Subclass object. Moreover, the static_cast will ensure that the cast fails at compile-time if the derived class doesn't inherit from Base properly, as the pointer type won't be convertible.
The reason that the cast is necessary here is that if you just say
template <typename Derived> class Base {
protected:
Derived& refToThis() {
return *this;
}
};
Then there is a type error in the program, since a Base by itself is not a Derived, and if you could convert a Base& into a Derived& without any checks you could break the type system.
That said... I wouldn't do this at all. Overloading operator! for this purpose makes the code less readable, and just writing *this is so idiomatic that hiding it will make your code much harder to understand. Using all of this template machinery to avoid something that's common C++ seems misguided. If you're doing something else before returning the reference that's fine, but this just doesn't seem like a good idea.
Hope this helps!
A: Please don't do this. There's already a way to do it in the language, *whatever_pointer_you_want_to_use_this_crazy_operator_upon. Creating a new way of doing something in the language will just confuse your future maintainers. Is there something else you're actually trying to achieve here?
| |
doc_3962
|
Thanks guys for all the help, I have made some changes and those errors have gone away, but now I am getting these:
Error 5 error LNK2019: unresolved external symbol "void __cdecl searchID(struct StudentRecord *,int)" (?searchID@@YAXPAUStudentRecord@@H@Z) referenced in function _main
Error 6 error LNK2019: unresolved external symbol "void __cdecl sortRecordsByName(struct StudentRecord *,int)" (?sortRecordsByName@@YAXPAUStudentRecord@@H@Z) referenced in function _main
Error 7 error LNK2019: unresolved external symbol "void __cdecl getInformation(struct StudentRecord * const,int)" (?getInformation@@YAXQAUStudentRecord@@H@Z) referenced in function _main
Error 8 error LNK1120: 3 unresolved externals
Here is the revised code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
const int MAX_SIZE = 20;
struct Answers
{
char answer1;
char answer2;
char answer3;
char answer4;
char answer5;
};
struct StudentRecord
{
int ID;
char student_name[MAX_SIZE];
Answers answer;
double score;
double average;
char letter_grade;
};
void getInformation(StudentRecord student[], int&);
void enterKey(char[]);
void calculateAvgAndLetter(StudentRecord *student, int, char[]);
void sortRecordsByName(StudentRecord * student, int);
void displayResults(StudentRecord * student, int);
bool displayReport(StudentRecord * student, int);
void searchID(StudentRecord * student, int);
int main()
{
int search;
int ID = 0;
bool check = false;
char repeat = 'y';
const int MAX_STUDENTS = 10;
int number_of_students = 0;
char key[5];
do {
cout << "How many students: ";
cin >> number_of_students;
StudentRecord student[MAX_STUDENTS];
enterKey(key);
getInformation(student,number_of_students);
calculateAvgAndLetter(student, number_of_students, key);
sortRecordsByName(student, number_of_students);
displayResults(student, number_of_students);
cout << "Would you like to search for a student (y for yes and n for no)?: ";
cin >> search;
while (search != 'n' && search != 'y')
{
cout << "Wrong ID" << endl;
cout << "Would you like to search for another student (y for yes and n for no)?: ";
cin >> search;
}
if (search == 'y')
{
searchID(student, number_of_students);
check = true;
}
else
check = false;
while (check)
{
cout << "Would you like to search for another student (y for yes and n for no)?: ";
cin >> search;
while (search != 'n' && search != 'y')
{
cout << "Wrong ID" << endl;
cout << "Would you like to search for another student (y for yes and n for no)?: ";
cin >> search;
}
if (search == 'y')
{
searchID(student, number_of_students);
check = true;
}
else
check = false;
}
cout << "Would you like to process another group of students(y for yes and n for no)?: " << endl;
cin >> repeat;
} while (repeat == 'y');
return 0;
}
void enterKey(char key[5])
{
for (int i = 0; i < 6; i++) {
cout << "Please enter the answer to question " << i + 1 << ": ";
cin >> key[i]; }
}
void getInformation(StudentRecord *student[],int number_of_students)
{
int max_students;
char again;
int i = 0;
cout << "Would you like to enter student information? " << endl;
cin >> again;
if (again == 'Y' || again == 'y')
{
do
{
cout << "Please enter student " << i + 1 << " information:" << endl;
cout << "Please Enter Student Name Last name first with no spaces: " << endl;
cin >> student[i]->student_name;
cout << "Please Enter Student Id Number: " << endl;
cin >> student[i]->ID;
cout << "Please enter the student's answer to question 1: ";
cin >> student[i]->answer.answer1;
cout << "Please enter the student's answer to question 2: ";
cin >> student[i]->answer.answer2;
cout << "Please enter the student's answer to question 3: ";
cin >> student[i]->answer.answer3;
cout << "Please enter the student's answer to question 4: ";
cin >> student[i]->answer.answer4;
cout << "Please enter the student's answer to question 5: ";
cin >> student[i]->answer.answer5;
i++;
if (i < number_of_students) {
cout << "Would you like to enter student information? " << endl;
cin >> again;
}
else again='n';
}
while(again == 'y' || again == 'Y');
cout<<"Reports:"<<endl;
}
}
void sortByID(StudentRecord student[], int number_of_students)
{
bool swap = true;
int j = 0;
int temp;
while (swap)
{
swap = false;
j++;
for (int i = 0; i < number_of_students - j; i++)
{
if (student[i].ID > student[i + 1].ID)
{
temp = student[i].ID;
student[i].ID = student[i + 1].ID;
student[i + 1].ID = temp;
swap = true;
}
}
}
}
int LinearSearch(StudentRecord student[], int number_of_students, int ID, int first, int last)
{
int i = 0;
int position;
for (int i = 0; i < number_of_students; i++)
{
if (ID == student[i].ID) {
position = i; }
}
return position;
}
void SortRecordsByName(StudentRecord student[], int number_of_students)
{
bool swap = true;
int j = 0;
StudentRecord temp;
while (swap)
{
swap = false;
j++;
for (int i = 0; i < number_of_students - j; i++)
{
if (student[i].student_name > student[i + 1].student_name)
{
strcpy(temp.student_name,student[i].student_name);
strcpy(student[i].student_name,student[i + 1].student_name);
strcpy(student[i + 1].student_name,temp.student_name);
swap = true;
}
}
}
}
void calculateAvgAndLetter(StudentRecord student[], int number_of_students, char key[5])
{
int points1;
int points2;
int points3;
int points4;
int points5;
int i = 0;
int j = 0;
for (int i = 0; i < number_of_students; i++)
{
if (student[i].answer.answer1 == key[0])
points1 = 10;
else
points1 = 0;
if (student[i].answer.answer2 == key[1])
points2 = 10;
else
points2 = 0;
if (student[i].answer.answer3 == key[2])
points3 = 10;
else
points3=0;
if (student[i].answer.answer4 == key[3])
points4 = 10;
else
points4 = 0;
if (student[i].answer.answer5 == key[4])
points5 = 10;
else
points5 = 0;
student[i].score= points1 + points2 + points3 + points4 + points5;
student[i].average = student[i].score * 2 ;
if((student[i].average >= 90) && (student[i].average <= 100))
student[i].letter_grade='A';
else if ((student[i].average >= 80) &&(student[i].average <= 89))
student[i].letter_grade='B';
else if ((student[i].average >= 70) && (student[i].average <= 79))
student[i].letter_grade='C';
else if ((student[i].average >= 60) && (student[i].average <= 69))
student[i].letter_grade='D';
else if ((student[i].average >= 0) && (student[i].average <= 59))
student[i].letter_grade='F'; }
}
void displayResults(StudentRecord student[], int number_of_students)
{
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) << "Answers" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(50) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
cout << setw(3) << student[i].ID << setw(15) << student[i].student_name << setw(10) << student[i].answer.answer1 << student[i].answer.answer2 << student[i].answer.answer3 << student[i].answer.answer4
<< student[i].answer.answer5 << setw(9) << student[i].score << setw(10) << student[i].average << setw(13) << student[i].letter_grade << endl;
cout <<"\n\n\nStudents admitted to graduate program: \n" << endl;
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(40) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
{
if (student[i].letter_grade == 'A' || student[i].letter_grade == 'B') {
cout << setw(2) << student[i].ID << setw(12) << student[i].student_name << setw(10) << student[i].score
<< setw(10) << student[i].average << setw(10) << student[i].letter_grade << endl; }
}
cout <<"\n\n\nStudents with Conditional Admission to Graduate Program: \n" << endl;
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(40) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
{
if (student[i].letter_grade == 'C') {
cout << setw(2) << student[i].ID << setw(10) << student[i].student_name << setw(10) << student[i].score
<< setw(10) << student[i].average << setw(10) << student[i].letter_grade << endl; }
}
cout <<"\n\n\nStudents Not Allowed Admission: \n" << endl;
cout << fixed<< setprecision(2);
cout << "Student ID" << setw(10) << "StudentName" << setw(10) <<"Total Pts" << setw(10) << "Average" << setw(12) << "Letter Grade"<<endl;
cout << setfill('-');
cout << setw(40) << "-" << endl;
cout << setfill(' ');
for (int i = 0; i < number_of_students; i++)
{
if (student[i].letter_grade == 'D' || student[i].letter_grade == 'F') {
cout << setw(2) << student[i].ID << setw(10) << student[i].student_name << setw(10) << student[i].score
<< setw(10) << student[i].average << setw(10) << student[i].letter_grade << endl; }
}
}
void searchIDandDisplay(StudentRecord student[], int number_of_students, int ID)
{
bool check = true;
string acceptence;
cout << "\n\n\nEnter the ID of the student: ";
cin >> ID;
while (check)
{
for(int i = 0; i < number_of_students; i++)
{
if (ID == student[i].ID)
{
check = false;
}
}
if (check == true)
{
cout << "No student with this ID" << endl;
cin >> ID;
}
}
int i = LinearSearch(student, number_of_students, ID, student[0].ID, student[number_of_students].ID);
if (student[i].letter_grade == 'A' || student[i].letter_grade == 'B' || student[i].letter_grade == 'C') {
acceptence = "Accepted"; }
else
acceptence = "Denied";
cout << fixed << setprecision(2);
cout << "Student ID" << setw(10)
<< "StudentName"
<< setw(10) << setw(10)
<<"Total Pts" << setw(10)
<< "Average" << setw(10)
<< "Letter Grade"
<< "Status" << endl;
cout << setfill('-');
cout << setw(48) << "-" << endl;
cout << setfill(' ');
cout << setw(2) << student[i].ID
<< setw(10) << student[i].student_name
<< setw(10) << student[i].score
<< setw(10) << student[i].average
<< setw(10) << student[i].letter_grade
<< setw(10) << acceptence <<endl;
}
Like I said a real beginner so any help will be greatly appreciated, and hope I posted right, sorry if anything wrong. And again thanks guys for any help!
A: void getInformation(StudentRecord *student[], int& num_std);
This says getInformation takes an array of pointers to StudentRecord. You want just
void getInformation(StudentRecord student[], int& num_std);
which takes an array of StudentRecords.
A: void getInformation(StudentRecord *student[], int& num_std);
In this declaration, student is taken as a pointer to pointer to StudentRecord. Change it to:
void getInformation(StudentRecord *student, int& num_std);
or
void getInformation(StudentRecord student[], int& num_std);
A: The problem is this line
getInformation(student,number_of_students);
The type of student here is a StudentRecord[] but the parameter of getInforamtion is typed to StudentRecord[]*. In order to make the types line up you need to change the type of the parameter to StudentRecord* or pass the address of student.
Given that you are passing the size along with the set of values I would favor changing the signature of getInformation to
void getInformation(StudentRecord *student, int& num_std);
A: Some comments
int search;
int ID = 0;
bool check = false;
char repeat = 'y';
const int MAX_STUDENTS = 5;
int number_of_students = 0;
char key[5];
do {
cout << "How many students: ";
cin >> number_of_students;
you should check if (number_of_students < MAX_STUDENTS) before continuing
your array key has dimension 5 but in your for loop you go from 0..5 which is six, better still give the dimension as an argument to the function enterKey(char *key, int maxsize) { ... }
void enterKey(char key[5]) -> (char* key, int maxsize)
{
for (int i = 0; i < 6; i++) -> for (int i=0; i<maxsize; ++i)
{
cout << "Please enter the answer to question " << i + 1 << ": ";
cin >> key[i];
}
}
the formal argument specifies an array of StudentRecord pointers
void getInformation(StudentRecord *student[],int number_of_students)
but you do not supply that in this way:
StudentRecord student[MAX_STUDENTS];
enterKey(key);
getInformation(student,number_of_students);
if you write as above then student is an array of StudentRecords
instead you should change the prototype to look like this (remember array decays to ptr):
void getInformation(StudentRecord *student,int number_of_students)
another tip
your struct Answers has 5 answer characters answer1,answer2,.. it would be more convenient to have it as an array, then you could shorten down the way you input the answers
A: Your prototypes don't need names for their arguments. They just need the data types.
void getInformation(StudentRecord*, int&);
void enterKey(char[]);
void calculateAvgAndLetter(StudentRecord*, int, char[]);
void sortRecordsByName(StudentRecord*, int);
void displayResults(StudentRecord*, int);
bool displayReport(StudentRecord*, int);
void searchID(StudentRecord*, int);
Your prototype for getInformation:
void getInformation(StudentRecord *student[], int& num_std);
has its second parameter typed as int&, whereas your definition:
void getInformation(StudentRecord *student[],int number_of_students)
is missing the &. In this case, you could either remove the & from the prototype or add it to the definition and your current implementation should work the same.
And as others have said, you're overstating the first parameter. Try Removing either the [] or the * (arrays are always passed by reference anyway).
| |
doc_3963
|
Below is the model and store definition:
Ext.define('Plant', {
extend: 'Ext.data.Model',
fields: [
// the 'name' below matches the tag name to read, except 'availDate'
// which is mapped to the tag 'availability'
{name: 'common', type: 'string'},
{name: 'botanical', type: 'string'},
{name: 'light'},
{name: 'price', type: 'float'},
// dates can be automatically converted by specifying dateFormat
{name: 'availDate', mapping: 'availability', type: 'date', dateFormat: 'm/d/Y'},
{name: 'indoor', type: 'bool'}
]
});
// create the Data Store
var store = Ext.create('Ext.data.Store', {
// destroy the store if the grid is destroyed
autoDestroy: true,
model: 'Plant'
});
On click of the save button, I am able to get the store like this:
{
text: 'Save',
handler : function(){
//Getting the store
var records = grid.getStore();
console.log(records.getCount());
Ext.Ajax.request({
url: '/CellEditing/CellEditingGridServlet',
method: 'POST',
jsonData: {
//How to assign the store here such that
//it is send in a JSON format to the server?
},
callback: function (options, success, response) {
}
});
}
But I don't know like how to convert the store content into JSON and send it in the jsonData of the ajax request.
I want the JSON data something like this in the server side:
{"plantDetails":
[
{
"common": Plant1,
"light": 'shady',
"price": 25.00,
"availDate": '05/05/2013',
"indoor": 'Yes'
},
{
"common": Plant2,
"light": 'most shady',
"price": 15.00,
"availDate": '12/09/2012',
"indoor": 'No'
},
]
}
Please let me know how to achieve this.
Regards,
A: Agreed with Neil, the right way to do this is through an editable store outfited with a proxy and a writer. See example here: http://docs.sencha.com/ext-js/4-1/#!/example/grid/cell-editing.html
A: Store
writer :
{
type : 'json',
allowSingle : true
}
Experiment with allowSingle as per your use case
In your controller
//if you want to set extra params
yourStore.getProxy().setExtraParam("anyParam",anyValue);
// sync the store
yourStore.sync({success : function() {
yourGrid.setLoading(false);
.. },
scope : this // within the scope of the controller
});
You should be creating the model with a new id ( you can ignore it at the server side and use your own key generation , but it lets extjs4 for its internal purposes know that a new record has been created).
creating a model instance
var r = Ext.create('yourModel', { id: idGen++, propA : valA , ... });
insert to grid
store.insert(0,r);
var editPlugin = grid.getPlugin(editPluginId);
editPlugin.startEdit(0,1);
Once you receive a response back the id's can be update to their true value.
in the Store
reader :
{
type : 'json',
root : 'yourdata',
successProperty : 'success',
idProperty : 'id'
}
If you were to use the same grid for handling and editing then you could use the write event or the appropriate event
for more advanced handling in the Store
listeners :
{
write : function(store,operation, eOpts)
{
var insertedData = Ext.decode(operation.response.responseText);
.. do something
}
}
I would recommend using the mvc architecture of Extjs4
A: This is what I tried and it seems to work:
var store = Ext.create('Ext.data.Store', {
// destroy the store if the grid is destroyed
autoDestroy: true,
model: 'Plant',
proxy: {
type: 'ajax',
url: '/CellEditing/CellEditingGridServlet',
writer: {
type: 'json',
root: 'plantDetails'
}
}
handler : function(){
grid.getStore().sync();
But I am getting an additional parameter in the JSON at the server side:
"id": null
I don't have this id set in my model then where is this coming from? Is there some way to set some values to it rather than having a default null value?
| |
doc_3964
|
SplitApp root view
But it's not using my Master and detail pages, I believe this is just the default structure of SplitApp.
For testing I put some content in the master and detail pages, but they are not appearing.
This is the file structure:
File Structure
I'm attaching the manifest.json code
{
"_version": "1.3.0",
"sap.app": {
"_version": "1.3.0",
"id": "com.md1",
"type": "application",
"i18n": "i18n/i18n.properties",
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"applicationVersion": {
"version": "1.0.0"
},
"dataSources": {
"ES4": {
"uri": "/destinations/ES4/sap/opu/odata/IWBEP/GWSAMPLE_BASIC/",
"type": "OData",
"settings": {
"odataVersion": "2.0"
}
},
"GWSAMPLE_BASIC": {
"uri": "/destinations/ES4/sap/opu/odata/IWBEP/GWSAMPLE_BASIC/",
"type": "OData",
"settings": {
"odataVersion": "2.0",
"localUri": "webapp/localService/metadata.xml"
}
}
},
"sourceTemplate": {
"id": "servicecatalog.connectivityComponent",
"version": "0.0.0"
}
},
"sap.ui": {
"_version": "1.3.0",
"technology": "UI5",
"icons": {
"icon": "sap-icon://detail-view",
"favIcon": "",
"phone": "",
"phone@2": "",
"tablet": "",
"tablet@2": ""
},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
},
"supportedThemes": [
"sap_hcb",
"sap_bluecrystal"
]
},
"sap.ui5": {
"_version": "1.2.0",
"rootView": {
"viewName": "com.md1.view.App",
"type": "XML",
"id": "app"
},
"dependencies": {
"minUI5Version": "1.36.0",
"libs": {
"sap.ui.core": {
"minVersion": "1.36.0"
},
"sap.m": {
"minVersion": "1.36.0"
}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "com.md1.i18n.i18n"
}
},
"": {
"dataSource": "ES4"
}
},
"routing": {
"config": {
"routerClass": "sap.m.routing.Router",
"viewType": "XML",
"viewPath": "com.md1.view",
"controlId": "idAppControl",
"controlAggregation": "detailPages",
"bypassed": {
"target": [
"master",
"notFound"
]
},
"async": true
},
"routes": [
{
"pattern": "",
"name": "master",
"target": [
"object",
"master"
]
},
{
"pattern": "SalesOrderSet/{objectId}",
"name": "object",
"target": [
"master",
"object"
]
}
],
"targets": {
"master": {
"viewName": "Master",
"viewLevel": 1,
"viewId": "master",
"controlAggregation": "masterPages"
},
"object": {
"viewName": "Detail",
"viewId": "detail",
"viewLevel": 2
},
"detailObjectNotFound": {
"viewName": "DetailObjectNotFound",
"viewId": "detailObjectNotFound"
},
"detailNoObjectsAvailable": {
"viewName": "DetailNoObjectsAvailable",
"viewId": "detailNoObjectsAvailable"
},
"notFound": {
"viewName": "NotFound",
"viewId": "notFound"
}
}
}
}
}
.
I know it's too much to ask, but I'll be really grateful if you help me resolve this. I have found many examples of using SplitApp in google, but they all are using Javascript view in Eclipse. I need to do it in webide with XML view.
Thanks,
Sarif
| |
doc_3965
|
I've read several posts, and tried several approaches with PDO and mysqli, but I have still yet to get this script to function properly. Any help would be greatly appreciated.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])&& !empty($_POST['firstname'])&& !empty($_POST['lastname'])&& !empty($_POST['phone'])&& !empty($_POST['address'])&& !empty($_POST['city'])&& !empty($_POST['zip'])):
//check to see if e-mail is already being used
//This method always says that the email is already in use, even if I am entering a new one.
/*
$records = $conn->prepare('SELECT * FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if( count($results) > 0){
$message = "Sorry, that E-mail address is already registered to an account.";
}
*/
//this one never says that the email is in use.
/*
$email = $_POST['email'];
$query = mysqli_query($conn, "SELECT * FROM users WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
$message = "Sorry, that E-mail address is already registered to an account.";
}
*/
//this was the last method I tried, and it also never says that the email is in use.
try{
$stmt2 = $conn->prepare('SELECT `email` FROM `user` WHERE email = ?');
$stmt2->bindParam(1, $_POST['email']);
$stmt2->execute();
while($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
if($stmt2->rowCount() > 0){
//echo "The record exists!";
$message = "Sorry, that E-mail address is already registered to an account.";
}
else{
// Enter the new user in the database
$sql = "INSERT INTO users (email, password, firstname, lastname, phone, address, city, zip) VALUES (:email, :password, :firstname, :lastname, :phone, :address, :city, :zip)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':firstname', $_POST['firstname']);
$stmt->bindParam(':lastname', $_POST['lastname']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':address', $_POST['address']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':zip', $_POST['zip']);
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
}
endif;
?>
A: When doing COUNT(*) the server(MySQL) will only allocate memory to store the result of the count and its faster too.
this part of your code that must be corrected:
$records = $conn->prepare('SELECT count(*) FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_NUM);
echo $results[0];
| |
doc_3966
|
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
if(item.getFieldName().equals("txtPrdModel")){
String ProductModel = item.getString();
}
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getString());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
This code gets the fieldName but getString doesn't return any value.
I need to use enctype="multipart/form-data" and need the absolute path of the file I am trying to upload.
I am using netbeans 8.0.2 and servlet version is 3.1.
A: For security reasons, the absolute path of the file isn't sent as part of the file name. You can only know the current name of the file that is uploaded to the server, so it's futile trying to obtain the absolute path that the file has on the client.
Once you have the file name and its binary data, use this info to store it in your specific path for files, in database or in another data source you're using.
| |
doc_3967
|
When I add profile page link, navbar doesn't work. If I remove articles:profile article.author_id from navbar.html all links works.
My Error Message is here:
NoReverseMatch at /
Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['articles/profile/(?P<author_id>[0-9]+)$']
views.py
def profile(request,author_id):
article = get_object_or_404(Article,author_id = author_id)
context = {
"article":article,
}
form = ArticleForm(request.POST or None,request.FILES or None)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
messages.success(request,"Dosya Yüklendi")
return redirect("article:dashboard")
return render(request,"profile.html",{"article":article,'form':form})
navbar.html
<nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-inverse">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="{% url 'index' %}">YB Blog</a>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{% url 'about' %}">Hakkımızda</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{% url 'article:articles' %}">Makaleler</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
{% if request.user.is_authenticated %}
<li class="nav-item active">
<a class="nav-link" href="{% url 'article:dashboard' %}">Makale Ekle</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{% url 'article:profile' article.author_id %}">Makale Ekle</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{% url 'user:logout' %}">Çıkış Yap</a>
{% else %}
<li class="nav-item active">
<a class="nav-link" href="{% url 'user:login' %}">Giriş Yap</a>
</li>
{% endif %}
<li class="nav-item active">
<a class="nav-link" href="{% url 'user:register' %}">Kayıt Ol</a>
</li>
</ul>
</div>
</nav>
urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = "article"
urlpatterns = [
path('profile/<int:author_id>',views.profile,name = "profile"),
path('dashboard/',views.dashboard,name = "dashboard"),
path('addarticle/',views.addArticle,name = "addarticle"),
path('article/<int:id>',views.detail,name = "detail"),
path('update/<int:id>',views.updateArticle,name = "update"),
path('delete/<int:id>',views.deleteArticle,name = "delete"),
path('',views.articles,name = "articles"),
path('comment/<int:id>',views.addComment,name = "comment"),
]
profile.html
{% extends 'layout.html' %}
{% block body %}
<h1>Profile Sayfası<h1>
<small> Merhaba Hoşgeldin, {{article.author.username}}<small>
<hr>
<p>
</p>
{% if article.author.username == "admin" %}
<h2>Admin Hakları:</h2>
<small>Buradan Dosya Yükleyebilirsin</small>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Dosya Yükle</button>
</form>
{% endif %}
{% endblock body %}
models.py
from django.db import models
from ckeditor.fields import RichTextField
class Article(models.Model):
author = models.ForeignKey("auth.User",on_delete = models.CASCADE,verbose_name = "Yazar ")
title = models.CharField(max_length = 50,verbose_name = "Başlık")
content = RichTextField()
created_date = models.DateTimeField(auto_now_add=True,verbose_name="Oluşturulma Tarihi")
article_image = models.FileField(blank = True,null = True,verbose_name="Makaleye Fotoğraf Ekleyin")
def __str__(self):
return self.title
| |
doc_3968
|
This is what empty div tags are getting replaced by <p> </p>
& HTML5 tags header, nav, etc. are been displayed at all?
My questions are;
Why is this happening, can I stop it?
And how do I work around the HTML5 elements?
| |
doc_3969
|
A: Spring can only initialize/destroy beans it also controllers and basically prototype scoped beans aren't under the control of spring (after construction). It doesn't know when it is cleaned up, destroyed or what so ever. As such the @PreDestroy method isn't callable for prototype beans (as they do not have a clearly defined lifecycle like singletons or request scoped beans).
A: The @PreDestroy annotation does not belong to Spring, it’s located in the jsr250-api library jar under javax.annotation package.
By default, Spring will not aware of the @PreDestroy annotation. To enable it, you have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean XML configuration file.
A: For "prototype" scoped beans, Spring does not call the @PreDestroy method.
Here is the answer from the Spring reference manual. Section 7.5.2
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-prototype
In contrast to the other scopes, Spring does not manage the complete lifecycle of a
prototype bean: the container instantiates, configures, and otherwise assembles a
prototype object, and hands it to the client, with no further record of that prototype
instance.
Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
| |
doc_3970
|
I expected to be able to do this using QtQuick.LocalStorage, or some other javascript SQLite library but am yet to find a solution.
QtQuick.LocalStorage does not seem to be able to open an existing .db file easily, and seems to be designed for storing temporary application data
SQL.js seems likely but as it is packaged as a sql-asm.js and sql-wasm.js, I can't easily import the functionality into my .qml test files.
e.g. following QtQuick examples:
import QtTest 1.2
import QtQuick.LocalStorage 2.9 as Sql
function test_database_connection(){
var database = "../Database/d.db"
db = Sql.openDatabaseSync(database, version, description, estimated_size, callback(db))
db.transaction(function (tx) {
var rs = tx.executeSql('SELECT * FROM Songs where id is "5" ');
}
}
I expected this to open my database "d.db", and execute the query on it. Instead it seems to just create a new empty "d.db" somewhere and run the query.
Is there an easier way I can do this?
A: you can use the command
QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db= setDatabaseName(database);
| |
doc_3971
|
Below are my code snippets:
FormType - UserType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
...
}
Entity - User.php
class User extends BaseUser
{
//no mention of any of the fosuser properties here
...
}
Validation: validation.yml
Project\MyBundle\Entity\User:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: username
errorPath: username
message: 'This username is already in use.'
properties:
dob:
- NotBlank: ~
- Type: \DateTime
Controller: UserController.php
public function createAction(Request $request, $brandId)
{
$entity = new User();
$form = $this->createCreateForm($entity, $brandId);
$form->handleRequest($request);
if ($form->isValid()) {
...
}
}
The validation always fails, ie. $form->isValid()is true even when I enter an already existing username in the form. Please help as I have not been able to figure out a solution so far. I tried copying the orm.xml file to myBundle under the validation folder. But it still takes no effect. Any help will be appreciated.
And when the saving happens i get a duplicate insert error as well.
An exception occurred while executing 'UPDATE user SET username = ?, username_canonical = ? WHERE id = ?' with params ["sub5", "sub5", 27]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'sub5' for key 'UNIQ_7BB0CD5292FC23A8'
A: Did you tried using @UniqueEntity("username") in User.php, this automatically throws an error in the form saying it's already used.
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* @ORM\Table(name="users")
* @ORM\Entity()
* @UniqueEntity("username")
*
*/
That worked for me. However I do not use FosUserBundle but the principle should be the same.
Also, I found this which could help you or maybe this, those are using FosUserBundle.
| |
doc_3972
|
df=
product_name 0 1 2
0 laptop 1200 1000 100
1 printer 150 10 100
2 tablet 300 30 560
3 desk 450 40 640
4 chair 200 20 207
I want to add the sum of column 1 and 2 but with multiplying the column 1 with 0.7 and 2 by 0.3.
I tried to make the sum for these 2 columns like:
df[[1, 2].sum(axis = 1)
I can do like that
df['Value'] = df.apply(lambda cols: cols[1]*0.7+cols[2]*0.3, axis=1)
But I am looking to send the 0.7 and 0.3 as parameter not hard coded.
A: Let's say you have a = 0.7. You can always do
df['Value'] = a * df[1] + (1 - a) * df[2]
Alternatively, you can use numpy for many columns. Say you have weights = [0.5, 0.3, 0.2] as the weights for the numerical columns, and index = [0, 1, 2] to mark which columns correspond to the weights:
df[index].to_numpy().dot(weights)
A: I solved this question finally like that:
def weighted_average(data, cols, weights):
columns = data.columns
weight = pd.DataFrame(pd.Series(weights, index=columns, name=0))
weight_index = []
for name in cols:
index_no = data.columns.get_loc(name)
weight_index.append(index_no)
weight = weight.iloc[weight_index]
return data[cols].dot(weight)
| |
doc_3973
|
library("bcrypt")
my_password <- "password1"
my_salt <- "$2a$10$abcdefghijklmnopqrstuv"
hashpw(my_password, my_salt)
[1] "$2a$10$abcdefghijklmnopqrstuu2njjerFUdKeNqVoGia/slSqhJQ.vuAy"
So the salt I used was "$2a$10$abcdefghijklmnopqrstuv" but the text in the hashed password only contains the salt up to the letter u. But here it is said that: "Looking at a previous hash/salt result, notice how the hash is the salt with the hash appended to it".
A: For some reason the salt must end with ".", "O", "e" or "u" in bcrypt. You can see here that this is the case:
# Generate a bunch of salts
library("bcrypt")
lots_salt <- NULL
for(i in 1:99999) {
lots_salt[i] <- gensalt(10)
}
# See unique last character
salt_end <- unique(substring(lots_salt, nchar(lots_salt[1]), nchar(lots_salt[1])))
salt_end
[1] "." "O" "e" "u"
Now we use the salt from the question but with one of the valid last characters ".", "O", "e" or "u" and we indeed get back the salt we used in the resulting hash:
sapply(salt_end, function(salt_end_i){
substring(hashpw(my_password, paste0(my_salt, salt_end_i)), 8, 8+21)
})
On the other hand, we get salts in the reulting hash that differ from the input salt if we use other last characters than ".", "O", "e" or "u". See here for example:
sapply(letters, function(salt_end_i){
substring(hashpw(my_password, paste0(my_salt, salt_end_i)), 8, 8+21)
})
Thus, the resulting hash salt is not complete for the salt used in the question because it does not use ".", "O", "e" or "u" as the last characters. The questions why only ".", "O", "e" or "u" are valid as last characters remains though.
| |
doc_3974
|
const int runs{ 1000 };
for (int run = 0; run < runs; ++run)
{
const int num{ 4 };
std::vector<bool> res(num, false);
std::vector<std::future<void>> futs(num);
for (int i = 0; i < num; ++i)
{
futs[i] = std::async(std::launch::async, [&res, i]
{
res[i] = true;
});
}
for (auto& fut : futs) fut.wait();
for (auto v : res) // I expect all values of res to be set to true.
{
if (!v) std::cerr << "Bad!!!\n"; // But this happens!
}
}
A: You have data races which lead to undefined behaviour.
Different items of vector<bool> should not be modified concurrently by different threads.
You can read about it here
Does not guarantee that different elements in the same container can
be modified concurrently by different threads.
or here
Notwithstanding [res.on.data.races], implementations are required to
avoid data races when the contents of the contained object in
different elements in the same container, excepting vector, are
modified concurrently.
| |
doc_3975
|
What I am trying to achieve is to have a sign up sequence where the user populates 5 screens of data one by one. I was going to use a PageViewController for this and each click on Next would transfer them to the next page in the sequence. All the while, adding all their input data to a parent model object which stayed around for all five screens, at the end you can submit the whole lot to the database to sign up.
The only way I can see so far to do this is to create five separate ViewControllers, one for each screen of the sign up, and create the navigation logic to display them as you click through. However this a) seems overkill and b) means each subsequent screen and viewcontroller doesn't know about the information the user entered in the previous steps.
What is the correct way to do this in iOS?
A: You can do it in many ways. If you like to use UIPageViewController, you can actually have one view controller for all steps of the sign up process.
A main view controller would implement protocol UIPageViewControllerDataSource. It has two required methods, which return an instance of a content view controller. These instances can be of any UIViewController subclass, so you could have five separate view controller classes or you could have five instances of the same class.
Xcode has a project template "Page-Based Application". It might be a good sample code for you. There is one class DataViewController and it is instantiated for each page. If your case is really simple then this might be the best solution.
If you use multiple view controllers, you can pass data between them by overriding the method prepareForSegue(segue:sender:). The UIStoryboardSegue object has access to the destination view controller, you can cast it and set up the properties. (I am assuming you are using storyboards and segues.)
Another approach would be not to use UIPageViewController and implement the whole process within one view controller. There could be one view with five container subviews. Initially the first one would be shown, then the second one, and so on. This requires manual implementation of navigation between those steps, but gives a lot of flexibility. It's also more aligned with MVVM, because there is one-to-one mapping between a ViewModel and ViewController.
In general, iOS apps have lots of view controllers. It doesn't seem an overkill for me to use five in your case. It might be more code, but it's less complexity.
| |
doc_3976
|
get comments(): [any] {
return this.commentsTest;
}
set comments(comments: [any]) {
this.commentsTest = comments;
}
the field it self is defined as private :
private commentsTest: [any];
in the constructor i initialized the object as follow :
this.comments = commentsTest;
when i am trying to use that field using the get method it is always undefined,
but if i am accessing it directly(while getting access warning)
i do get the values i am looking for :
openExtendedDetailsModal(comments) {
console.log("***" + this.investorObject.comments); // undefined
console.log(this.investorObject.commentsTest); // defined
//this.commentsdDetails.altOpen(comments);
}
UPDATE
here is the code i am using :
investorObject: Investor;
prametersSubscription: Subscription;
id: string;
constructor(private investorService: InvestorsService, private route: ActivatedRoute) {}
ngOnInit() {
this.prametersSubscription = this.route.params.subscribe(
(params: Params) => {
this.id = params.id;
this.getInvestorData();
}
);
}
ngOnDestroy() {
this.prametersSubscription.unsubscribe();
}
getInvestorData() {
this.investorService.getSingleInvestorById(this.id).subscribe(
data => {
this.investorObject = data.data;
console.log(this.investorObject.commentsTest);
});
}
openExtendedDetailsModal(comments) {
console.log("***" + this.investorObject.lastName); // defined
console.log("***" + this.investorObject.comments); // undefined
console.log(this.investorObject.commentsTest); // defined
//this.commentsdDetails.altOpen(comments);
}
here is part of the Investor class :
what am i missing here ?
Thanks
A: i manged to solve this issue,
i have changed the model as followed :
1)changed the constructor
constructor() {}
2)changed the name and the type of the commentsTest field:
private commentsTest: [Object];
3)Initiated as followed :
this.investorObject = new Investor();
Object.assign(this.investorObject, data.data as Investor);
so now ,i am getting the comments as i wanted to,also the type of the object is Investor.
Thanks all
| |
doc_3977
|
anyone who helps Thanks in advance
A: The difference between API calls and a normal HTML app are basically on the response, usually your controllers respond with views(), so they can be rendered:
/// Get the data
$books=Book::all();
/// HTML response
return view('books.index',compact('books'));
An API usually responds with JSON, which in Laravel is as easy as doing
/// Get the data
$books=Book::all();
/// JSON response
return response()->json($books);
or as simple as
return Book::all();
or
return Book::all()->toJson();
Another thing you have to think about in your app architecture are the routes, to differentiate web from api, I usually create my endpoints as
/api/books/1
Instead of
/books/1
This is done in your routes
Route::get('/api/books/{id}', 'BookController@show');
You should read a little about API creation too, because API architecture is is hard, endpoints get messy really fast and easy, this is a nice book on APIs https://leanpub.com/build-apis-you-wont-hate
| |
doc_3978
|
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=filename.xls");
File excelFile = new File(filename);
HSSFWorkbook workbook = new HSSFWorkbook(excelFile);
// ...
// populate workbook with user list from Database here
// ...
workbook.write(response.getOutputStream()); // Write workbook to response.
workbook.close();
this code working in Windows without any issue. But when I try to deploy on Tomcat 7 in ubuntu server, When I execute (download excel), it throws FileNotFoundException. The excel file is not created in webapps/(my application folder), it creates excel file in Windows.
I've already set tomcat's webapps and it's subdirectories as 777 and changed owner to tomcat7 user.
Apache POI version is 3.10-FINAL
| |
doc_3979
|
One obvious way is to use synchronized blocks or Lock.lock()/unlock() methods. Under thread contention , these will cause context switches. Is there any simple design strategy for achieving this in a non-blocking manner ? may be using some Atomic constructs ?
A: I don't think you can rely on any mechanism, except the ones you pointed out yourself, simply because you're operating on two structures.
There's decent support for concurrent/atomic operations on one data structure (like "put if not exists" in a ConcurrentHashMap), but for a sequence of operations, you're stuck with either a lock or a synchronized block.
A: Since the contention case is the relevant case you should look at "spin locks". They do not give away the CPU but spin on a flag expecting the flag to be free very soon.
Note however that real spin locks are seldom useful in Java because the normal Lock is quite good. See this blog where someone had first implemented a spinlock in Java only to find that after some corrections (i.e. after making the test correct) spin locks are on par with the standard stuff.
A: For some operations you can employ what is called a "safe sequence", where concurrent operations may overlap without conflicting. For instance, you might be able to add a member to a set (in theory) without the need to synchronize, since two threads simultaneously adding the same member do not conceptually conflict with each other.
But to query one object and then conditionally operate on a different object is a much more complicated scenario. If your sequence was to query the set, then conditionally insert the member into the set and into the queue, the query and first insert could be replaced with a "compare and swap" operation that syncs without stalling (except perhaps at the memory access level), and then one could insert the member into the queue based on the success of the first operation, only needing to synchronize the queue insert itself. However, this sequence leaves the scenario where another thread could fail the insert and still not find the member in the queue.
A: You can use java.util.concurrent.ConcurrentHashMap to get the semantics you want. They have a putIfAbsent that does an atomic insert. You then essentially try to add an element to the map, and if it succeeds, you know that thread that performed the insert is the only one that has, and you can then put the item in the queue safely. The other significant point here is that the operations on a ConcurrentMap insure "happens-before" semantics.
ConcurrentMap<Element,Boolean> set = new ConcurrentHashMap<Element,Boolean>();
Queue<Element> queue = ...;
void maybeAddToQueue(Element e) {
if (set.putIfAbsent(e, true) == null) {
queue.offer(e);
}
}
Note, the actual value type (Boolean) of the map is unimportant here.
| |
doc_3980
|
I am loading a Chrome into Facebook and I do a simple JQuery GET request to my own website. I get the following error in the console when the GET request is called...
"Refused to connect to 'https://www.istyla.com/Popup/t2.php' because it violates the
following Content Security Policy directive: "connect-src https://*.facebook.com
http://*.facebook.com https://*.fbcdn.net http://*.fbcdn.net *.facebook.net
*.spotilocal.com:* https://*.akamaihd.net ws://*.facebook.com:* http://*.akamaihd.net"."
This happened all of a sudden. It worked yesterday...
Here is part of my Chrome Extension Manifest with the CSP definition:
"content_security_policy": "default-src 'self'; script-src 'self'; object-src 'self'; connect-src *"
Here is my GET request (loaded via a content script - JQuery is also loaded as a seperate content script):
$.get("https://www.istyla.com/Popup/t2.php" + c, function (d) {
//do my other stuff here
}
By the way... t2.php does allow all origins. Is it Facebook that set a CSP on their site?? What can I do to connect to my URL via JQuery GET?
Thanks for any advice... :)
A: I had the same issue with my script. I moved all my AJAX calls to a background script.
A: I think a direct .get would not work cross-domain. Can you try using $.jsonp.
http://www.jquery4u.com/json/jsonp-examples/
| |
doc_3981
|
Finally, I deleted the tmp folder and restarted the rails server. Only then was I able to see my changes on the browser. I want to know if there is an easier way to see the changes directly on saving the scss file?
PS: I have development environment set up and my Gemfile has rails of version '>= 5.0.0.1' and I have sass-rails to '~> 5.0'.
Please let me know if any additional information is required
A: It was a problem with WSL. we have just shifted ROR project folder outside of 'C:\Users\username\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\home' and it worked.
| |
doc_3982
|
private Mock<RealDBContext> GetDbContextMock()
{
var realDB= new RealDBContext();
var dbContextMock = new Mock<RealDBContext>();
dbContextMock.SetupAllProperties();
dbContextMock.Object.SomeTable1= realDB.SomeTable1; //here I want the real data from the real tables
dbContextMock.Object.SomeTable2= realDB.SomeTable2; //also here I want the real data
dbContextMock.Object.SomeTable3= dbContextMock.Object.Set<SomeTable3Model>(); // here I want to create a new and empty DbSet
dbContextMock.Object.SomeTable3Model.AddRange(GetMockSomeTable3ModelList());
return dbContextMock;
}
After the line with the Set I've expected to get a new and empty DbSet, but it remains null. How do I create a new and empty DbSet?
A: Here is a working example. If you put a breakpoint on the end of the test, you can see that the list now contains what was added. You should obviously setup the mock dbset's addrange.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TestProject1
{
[TestClass]
public class UnitTest1
{
public class Person
{
public string Name { get; set; }
}
#pragma warning disable EF1001 // Internal EF Core API usage.
public interface IRealDbContext : IDisposable, IAsyncDisposable, IInfrastructure<IServiceProvider>, IDbContextDependencies, IDbSetCache, IDbContextPoolable, IResettableService
{
DbSet<Person> Persons { get; set; }
}
#pragma warning restore EF1001 // Internal EF Core API usage.
[TestMethod]
public void TestMethod1()
{
var mockedContext = new Mock<IRealDbContext>();
var persons = new List<Person>();
var mockedPersonSet = new Mock<DbSet<Person>>();
mockedPersonSet.Setup(o => o.Add(It.IsAny<Person>())).Callback(new Action<Person>(person => persons.Add(person)));
mockedContext.Setup(o => o.Persons).Returns(mockedPersonSet.Object);
mockedContext.Object.Persons.Add(new Person()
{
Name = "John Smith"
});
}
}
}
| |
doc_3983
|
command regex logImageFile 's/(.+) (.+)/ expr (int) [ (id)UIImagePNGRepresentation(%1) writeToFile: @"%2.png" atomically: YES ]/'
The problem is that I have to enter the full path every time. It would be much better for me to have a directory that it always uses. So I tried this:
command regex logImageFile 's/(.+) (.+)/ expr (int) [ (id)UIImagePNGRepresentation(%1) writeToFile: @"/users/myUsername/Desktop/tempImages/%2.png" atomically: YES ]/'
Now, when I enter something like the following in the Xcode console, lldb always says that logImageFile is not a valid command.
logImageFile fooImage barFile
The problem is likely the slashes inside the path. I assume I have to escape them somehow, but how? Note that what I have is an NSString inside an lldb regex -- but I don't know what flavor of regex that actually is.
A: I think the problem is that you're using the / character to separate the parts of your regular expression and that character also appears in your substitution text in the file path. The easiest fix is to use a different separator. The s/// format is the most common but you can use s### just as easily. e.g.
(lldb) command regex logImageFile 's#(.+) (.+)#expr (int) puts("[ (id)UIImagePNGRepresentation(%1) writeToFile: @\"/users/myUsername/Desktop/tempImages/%2.png\" atomically: YES ]")#'
(lldb) logImageFile fooImage barFile
(int) $1 = 10
[ (id)UIImagePNGRepresentation(fooImage) writeToFile: @"/users/myUsername/Desktop/tempImages/barFile.png" atomically: YES ]
I told expr that the return type was (int) here so it is printing that (assigning it to convenience variable $1) - but if you'd used (void), it would have avoided printing anything.
I'm using puts() here instead of the real call that you're trying to set up - but I think I spotted the problem with your original regular expression command alias. Give this a try.
| |
doc_3984
|
function recursiveDecodeURIComponent(uriComponent){
try{
var decodedURIComponent = decodeURIComponent(uriComponent);
if(decodedURIComponent == uriComponent){
return decodedURIComponent;
}
return recursiveDecodeURIComponent(decodedURIComponent);
}catch(e){
return uriComponent;
}
}
console.log(recursiveDecodeURIComponent("http://www.yelp.com/biz/carriage-house-caf%25C3%25A9-houston-2"))
Outputs: "http://www.yelp.com/biz/carriage-house-café-houston-2".
I would like to get the same in python.
I tried the following:
print urllib2.unquote(urllib2.unquote(urllib2.unquote("http://www.yelp.com/biz/carriage-house-caf%25C3%25A9-houston-2").decode("utf-8")))
but I got http://www.yelp.com/biz/carriage-house-café-houston-2. Instead of Expected character é, I got 'é' irrespective of any number of calling urllib2.unquote.
I am using python2.7.3, can anyone help me?
A: I guess a simple loop should do the trick:
uri = "http://www.yelp.com/biz/carriage-house-caf%25C3%25A9-houston-2"
while True:
dec = urllib2.unquote(uri)
if dec == uri:
break
uri = dec
uri = uri.decode('utf8')
print '%r' % uri
# u'http://www.yelp.com/biz/carriage-house-caf\xe9-houston-2'
| |
doc_3985
|
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
srand ( time(NULL) ); //initialize the random seed
const char arrayNum[4] = {'5', '6', '7', '8'};
int RandIndex = rand() % 4; //generates a random number between 0 and
cout << arrayNum[RandIndex];
int ceva = arrayNum[RandIndex] ;
if (ceva == 6){
cout << "hey";
}
else{
cout << "nu";
}
}
The code is showing only "nu" and it's not working properly.
If arrayNum[RandIndex] is equal to 6 show "hey" if else show "nu"
A: I suspect that the problem resides in the type of your array, I'll try to explain it:
Since your array is of type char, you are storing a character, not a number, which is ok. But then you're assigning the character to a int in
int ceva = arrayNum[RandIndex];
When you assign a character to a number, at least in C, it doesn't assign the number directly, but the the decimal representation of the encoding of the character.
So if you do int i = '0', for example, in unicode, it will assign to i 48, which is it's decimal representation.
Now, for the solution:
*
*The easy and 'proper' way should be to change the array to numbers, not characters, or changing the if in order to compare to a character.
*If for some reason you can't do 1., when assigning the character to the number do - '0', so it looks like int ceva = arrayNum[RandIndex] - '0'. That will do the hack since, for '1' (unicode), you're doing 49 - 48, for '2' = 50 - 48, ...
| |
doc_3986
|
dict = {'Name': 'Tom', 'Age': 7, 'Class': 'First'}
type(dict)
then I deleted it with del, but it still exists and type is changed to "type"
del dict # delete entire dictionary
type(dict)
Why does del not work on the dict? Why is type changed?
A: If you really want to "abuse" the word "dict " in your scripts then you can use the word "dict " only like this "dict_" by using "_ " behind it.
>> Here << is pythons build-in list of words reserved for your scripts functionality by python.
In semantics context:
The word "reserved" means "to keep or set apart for some particular use or purpose in its functional/semantic context.".
Thus if your change those reserved words your script/code/program comes tumbling down like a house of cards and python starts spitting "traceback errors" when you run your code. Regardless of your free choice to change the wording of them into other lingo, you have to correct all those words written in your scripts/code to maintain its functionality in place by these "reserved" words. If not you have a bright "debugging" future ahead for all you scripts where you changed these "reserved" python wordings/ built-in functions.
A: When you name your dictionary dict there is a problem.
dict is a built-in function.
Rename the dictionary and try again:
dict1 = {'Name': 'Tom', 'Age': 7, 'Class': 'First'}
type(dict1)
del dict1
dict1
| |
doc_3987
|
How can I get text from MySQL db and set it on a text view using Volley?
I am using a list view.
Here's what I have so far.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CantosHimnario extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cantos_himnario);
populateListView();
}
private void populateListView() {
String[] cantosHimnario = {"1. Abre Tu Oido",
"2. A Cristo Quiero Servir"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.cantos_name, cantosHimnario);
ListView listView = (ListView)findViewById(R.id.listViewOne);
listView.setAdapter(adapter);
}
}
An example would be greatly appreciated!
A: Try this tutorial
https://www.simplifiedcoding.net/retrieve-data-from-mysql-database-in-android-using-volley/
I tried this and works for me
| |
doc_3988
|
How to skip the alphabets and only count the numbers?
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if(a[i]>='a'&&a[i]<='z')
{
continue;
}
else
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}
A: I switched your usage of scanf to use fgets. This works:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if (isdigit(a[i]))
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t = 0;
scanf("%d", &t);
while(t--)
{
char a[100001];
fgets(a, sizeof(a), stdin);
function(a);
puts("\n");
}
}
A: If the OP's intent was in fact to count up the groups of digits (in which the definition of 'number' is each contiguous run of digits), this will accomplish the goal:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int function(char a[])
{
size_t i = 0;
int cnt = 0;
// convert all non-digits to whitespace
printf("Converting\n");
for (char *p = a; *p != '\0'; ++p)
{
*p = isdigit(*p) ? *p : ' ';
}
printf("Found Groups: %s\n",a);
// note: strtok mutates the string it is given, it will not be usable after this:
for (char *gr = strtok(a," "); gr != NULL; gr = strtok(NULL, " "))
{
cnt++;
}
printf("Number of Groups: %d\n", cnt);
}
int main()
{
printf("Enter strings (Ctrl-C to end)\n");
while(1)
{
int result = 0;
char a[100001];
scanf("%s",a);
result = function(a);
printf("\n");
}
}
(I was not able to get the version using fgets to work, but how the string is gathered is not really in the scope of the question, the OP's original code in main is functional, I just made it an open-ended loop for my tests)
A: In your code continue statement is responsible for wrong answer. Because of it your code is not encountering the statement a[i] !='\0'. so suggest you to just avoid it and close your if statement without any code as like me. One more suggestion use also uppercase letters as user can also enter uppercase letters and using fgets() function you can also read white spaces.
Try out this
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if((a[i]>='a'&&a[i]<='z') || (a[i]>='A'&&a[i]<='Z'));
else
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}
| |
doc_3989
|
Here is my code for the in which I am syncing my data with the watch:
private void connectToWatchFace() {
Log.d(LOG_TAG, "connectToWatchFace()");
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
private void sendDataToWatchFace(double highTemperature, double lowTemperature, int weatherConditionId) {
Log.d(LOG_TAG, "sendDataToWatchFace()");
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/sunshine").setUrgent();
putDataMapRequest.getDataMap().putDouble("high_temperature", highTemperature);
putDataMapRequest.getDataMap().putDouble("low_temperature", lowTemperature);
putDataMapRequest.getDataMap().putLong("timestamp", new Date().getTime());
Log.d(LOG_TAG, "High Temperature: " + highTemperature + " " + "Low Temperature: " + lowTemperature);
int drawableResourceId = Utility.getIconResourceForWeatherCondition(weatherConditionId);
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), drawableResourceId);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
Asset asset = Asset.createFromBytes(byteArrayOutputStream.toByteArray());
putDataMapRequest.getDataMap().putAsset("icon", asset);
PutDataRequest putDataRequest = putDataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
@Override
public void onResult(@NonNull DataApi.DataItemResult dataItemResult) {
if (dataItemResult.getStatus().isSuccess()) {
Log.d(LOG_TAG, "dataItemResult.getStatus().isSuccess()");
} else {
Log.d(LOG_TAG, "NOT dataItemResult.getStatus().isSuccess()");
}
}
});
}
This is code in which I am receiving the data from phone.
@Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d(TAG, "onDataChanged()");
for (DataEvent dataEvent : dataEventBuffer) {
DataItem dataItem = dataEvent.getDataItem();
String path = dataItem.getUri().getPath();
Log.d(TAG, "path: " + path);
if (path.equals("/sunshine")) {
DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
mHighTemperature = dataMap.getDouble("high_temperature");
mLowTemperature = dataMap.getDouble("low_temperature");
Log.d(TAG, "high temperature: " + mHighTemperature + ", low temperature: " + mLowTemperature);
Asset iconAsset = dataMap.getAsset("icon");
if (iconAsset != null) {
new SunshineWatch.Engine.LoadBitmapAsyncTask().execute(iconAsset);
}
// Force UI update
invalidate();
}
}
}
private class LoadBitmapAsyncTask extends AsyncTask<Asset, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Asset... params) {
if (params.length > 0 && params[0] != null) {
Asset asset = params[0];
InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
mGoogleApiClient, asset).await().getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
return BitmapFactory.decodeStream(assetInputStream);
} else {
Log.e(TAG, "Asset must be non-null");
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
Log.d(TAG, "onPostExecute bitmap is NOT null");
mIconBitmap = Bitmap.createScaledBitmap(
bitmap,
getResources().getDimensionPixelSize(R.dimen.icon_width_height),
getResources().getDimensionPixelSize(R.dimen.icon_width_height),
false
);
invalidate();
} else {
Log.d(TAG, "onPostExecute bitmap is NULL");
}
}
}
}
I don't find any results in the LOGCAT too. I am using play services version 10.0.0
A: Please check and make sure that you already have the latest version of the Google Play services.
As mentioned in including the correct libraries, as part of the Project Wizard, the correct dependencies are imported for you in the appropriate module's build.gradle file.
To sync and send data between wearables and handhelds with the Wearable Data Layer APIs, you need the latest version of Google Play services. If you're not using these APIs, remove the dependency from both modules.
Furthermore, you also need to make sure that you have an established connection when syncing. Sometimes the emulator can be temperamental and either not sync all your content or randomly disconnect. This should be rare, but if it happens start the process again as stated in this article.
You may want to also check this tutorial for additional information:
*
*Android Wear Tutorial - A Comprehensive Introduction
A: Use compileSdkVersion 23 in gradle. Android Wear is compatible with API 23 for now.
A: By working on Android wearable app I faced with different situations when wearable can't reach handset. The list of questions below helps to identify root cause
*
*Are they paired via bluetooth?
*Does port forwarded on the device?
*Does wearable see the node?
*Does urgent flag turned on to sync immedeatly?
*Does data is cached on the device side and just doesn't sync not invalidated data?
*Does format of wearable uri you use to obtanin data from cache are match "wear://node_id/resource_path" ?
| |
doc_3990
|
anonymous F()
{
...
return new { a = 5, b = "some string" };
}
and then using it like this:
anonymous a = F();
but having static typing?
I mean, why isn't the compiler able to know statically which are the members of the anonymous object F method returns, and so give me intellisense?
A: What would you stop than from doing something like this:
anonymous F()
{
if (something) return new { a = 5 };
else return new { b = 1, z = "asdf" };
}
How is compiler supposed to know which type is returned then? Should it limit you at design time with error messages that those anonymous types are not the same? Is it worth the effort? You can use dynamic for such cases or create actual classes if needed - to make code clear.
| |
doc_3991
|
<root>
<name>
MyName
</name>
<subject>
newsubject
</subject>
<queries>
<sno>
1
</sno>
<query>
This is the query one
</query>
</queries>
<queries>
<sno>
2
</sno>
<query>
This is the query two
</query>
</queries>
<queries>
<sno>
3
</sno>
<query>
This is the query three
</query>
</queries>
</root>
I need to add this value to sql server table name member_info
my table design is
name --> varchar(50)
subject-->varchar(75)
sno-->int
queries-->varchar(150)
I tried some basic stuffs for finding the XML file on the specific folder, I don`t have idea how to implement by reading and inserting XML file, Please be gentle I am just beginner.
A: You have a few options:
*
*You can read the XML nodes before inserting into the database, and
insert normalized table column values.
*You can shred the XML in a stored procedure, by passing the XML
string as an input parameter. You can read up on how to shred the XML utilizing the nodes() method, here.
| |
doc_3992
|
check('name')
.trim()
.escape()
.notEmpty()
.withMessage('User name can not be empty!')
.bail()
.isLength({ min: 3 })
.withMessage('Minimum 3 characters required!')
.bail(),
Why there is a need to escape() after trim()?
A: Thanks to robertklep. Every sanitizer is described here:
Sanitizers
A: Interestingly, it replace <, >, &, ', " and / with HTML entities.
You may refer here: validatorjs
| |
doc_3993
|
I have knowledge of php and i do not mind editing code if neccessary.
A: There are three session variable that is used for manipulating current language in zencart
Default values :
[language] => english
[languages_id] => 1
[languages_code] => en
Above value update as per user language selection. You can write/update code in sidebox.
<?php
if($_SESSION['languages_code']=='en')
{
$image = 'your image path';
}
else if($_SESSION['languages_code']=='gr')
{
$image = 'your image path';
}
else
{
$image = 'your image path';
}
?>
A: Following is way that you can manage the ,
In your template file add the following
<form method="post" enctype="multipart/form-data"/>
<div id="language">
<img onclick="$('input[name=\'language_code\']').attr('value', 'en').submit(); $(this).parent().parent().submit();" title="English" alt="English" src="eng.png">
<img onclick="$('input[name=\'language_code\']').attr('value', 'es').submit(); $(this).parent().parent().submit();" title="Spanish" alt="Spanish" src="spanish.png">
<input type="hidden" value="" name="language_code">
</div>
</form>
following is the php code ,
<?php
if(isset($_POST['language_code']))
{
$_SESSION['lang'] = ($_POST['language_code']!="")?$_POST['language_code']:"";
}
$language = $_SESSION['lang'];
switch($language){
case "en":
//Your Image path
break;
default:
//Your Image path
break;
}
?>
| |
doc_3994
|
This is how we add and remove the rows:
methods: {
addRow: function() {
let lastRow = eval(`this.$parent.json${this.path}[this.$parent.json${this.path}.length - 1]`);
lastRow = Object.assign({}, lastRow);
eval(`this.$parent.json${this.path}.push(lastRow)`);
this.$forceUpdate();
},
removeRow: function(index) {
//eval(`this.$parent.json${this.path}.splice(index, 1)`);
eval(`Vue.delete(this.$parent.json${this.path}, index)`);
this.$forceUpdate();
}
https://jsfiddle.net/00e58as4/10/6
To recreate the issue, add a row. Then, change the text on the new row. Try removing the second-to-last row - notice how it doesn't get deleted, but the last one is. However, if you check the json-debug which is a live view of the backend data, you'll see that the proper row gets deleted!
Why does this happen? Why are the UI and the backend not in sync?
A: You should always use a key when iterating with v-for. Try adding one like this.
<div class = "well" v-for = "item, index in items" :key="item">
| |
doc_3995
|
A: Here are 3 steps to create a code snippet along with a shortcut.
1. Code -> Preferences -> Keyboard Shortcuts
2. Click on icon for keybindings.json file
3. Add JavaScript objects for Code Snippet/Shortcuts
For example i have created snippets for logging purposes as I mostly work with JavaScript Frameworks.
1.console.log('') with shortcut Control (or Ctrl) ⌃ + l
2.console.warn('') with Control (or Ctrl) ⌃ + w
3.console.error('') with Control (or Ctrl) ⌃ + e
Code:
{
"key": "ctrl+l",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.log('${TM_SELECTED_TEXT}$1')$2"
}
},
{
"key": "ctrl+w",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.warn('${TM_SELECTED_TEXT}$1')$2"
}
},
{
"key": "ctrl+e",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.error('${TM_SELECTED_TEXT}$1')$2"
}
}
A: Note that the line below will open a list of snippets defined for the language you are currently using (and you don't want that)
"args": { "snippet": "'$TM_SELECTED_TEXT'" }
Whereas with the below line the snippet given as argument will be executed right away
"args": { "name": "your_snippets_name" }
Here's how I defined a snippet for HTML where I wanted to select a text and when pressing CTRL+B the text to become enclosed in <strong></strong> tags:
"make_strong": {
"prefix": "strong",
"body": [
"<strong>$TM_SELECTED_TEXT${1:}</strong>"
],
"description": "Encloses selected text in <strong></strong> tags"
}
Note the ${1:} above - what this does is that it places the cursor there. This enables you to press CTRL+B at cursor and then have the cursor placed inside the <strong></strong> tags. When selecting a string and pressing CTRL+B, the string will enclosed in <strong> tags and the cursor will be placed before the closing </strong> tag. Pressing TAB at this point, will put your cursor after the closing </strong> tag.
And added in my keybindings.json the following:
{
"key": "ctrl+b",
"command": "editor.action.insertSnippet",
"args": { "name": "make_strong" }
}
UPDATE JUNE 2nd, 2021
Since this is getting lots of views, I am posting some of the snippets I use, maybe it will be useful to someone
{
"key": "ctrl+alt+u",
"command": "editor.action.transformToUppercase"
},
{
"key": "ctrl+alt+l",
"command": "editor.action.transformToLowercase"
},
{
"key": "ctrl+b",
"command": "editor.action.insertSnippet",
"args": { "name": "insert_strong" }
},
{
"key": "ctrl+i",
"command": "editor.action.insertSnippet",
"args": { "name": "insert_italic" }
},
{
"key": "ctrl+u",
"command": "editor.action.insertSnippet",
"args": { "name": "insert_underline" }
},
{
"key": "ctrl+alt+p",
"command": "editor.action.insertSnippet",
"args": { "name": "insert_paragraph" }
},
{
"key": "ctrl+shift+space",
"command": "editor.action.insertSnippet",
"args": { "name": "insert_nbsp" }
},
{
"key": "ctrl+enter",
"command": "editor.action.insertSnippet",
"args": { "name": "insert_br" }
},
A: It would seem that, as of version 1.9, Visual Studio Code can do what you are looking for, no other extensions necessary.
From https://code.visualstudio.com/updates/v1_9#_insert-snippets
"You can now bind your favorite snippets to key bindings. A sample that encloses a selection with single quotes looks like this:"
Add the snippet below to keybindings.json (open Keyboard Shortcuts editor and click on the For advanced customizations open and edit keybindings.json link)
{
"key": "cmd+k",
"command": "editor.action.insertSnippet",
"args": { "snippet": "'$TM_SELECTED_TEXT'" }
}
A: *
*Call Command Palette in View menu
*Hit "shortcuts json" and OK
*Then append under code blocks
{
"key": "shift+alt+l",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus && editorLangId == 'js'",
"args": {
"snippet": "console.log($1);$0",
}
},
{
"key": "shift+alt+l",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus && editorLangId == 'dart'",
"args": {
"snippet": "print($1);$0",
}
},
If you press Shift+Alt+L in JavaScript then
put "console.log();" to your editor,
And press Shift+Alt+L in Dart then
put "print();" to your editor,
with the same shortcut.
| |
doc_3996
|
Using transacted session to handle the failure if a message fails in processing.
On failure redirecting the message to another queue.
Tried to used the concurrency option but can't use it as my message processing need to pick messages in order.
To process around 5000 messages in queue its taking around 30mins.. Reading the message from queue and saving in DB.
Configuration:
<jms:listener-container container-type="default" connection-factory="connectionFactory" acknowledge="transacted">
<jms:listener destination="queueName" ref="processQueueMessage" method="onMessage" />
</jms:listener-container>
Looking for another alternative ways of processing the messages or any suggestion on improving existing process.
A: Updates:
Did some analysis on message consumption alone. So removed the persistence portion of processing as suggested by Stephane. Wrote a test case to test message consumption.
Result: To consume 5000 messages it took around 30-35 secs.
Next Steps:
Looking into DB persistence to see if I can find the bottleneck.
| |
doc_3997
|
My SSIS is generating error for time (DBTime) column in MySQL database. (cannot convert dbtime to dbtime2)
What datatype can i use in SQL server for time? I tired nvarchar, varchar and also tried data conversion task but i get same error.
A: You could use time or datetime.
EDIT:
Now that I see the type of data that MySQL uses for time what you probably want to do is to put the data into an nvarchar on the SQL Server side, and in SSIS you can invoke
TIME_FORMAT(timecol, '%H:%i:%S')
The SSIS tool lets you do specifications of how to manipulate individual columns before inserting into the other database using scripting.
| |
doc_3998
|
There are many ways to custom the button, but I need to display the file name once it has been uploaded.
I found one way to do it with this code :
<input type="file" class="custom-file-input">
<label class="custom-file-label" for="custom-file-input">Your file</label>
And this script :
<script>
$(".custom-file-input").on("change", function() {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>
It works, but with CF7, we use shortcode te create inputs.
And it gives something like :
<span class="wpcf7-form-control-wrap">
<input type="file" name="your-file" size="40" class="wpcf7-form-control wpcf7-file custom-file-input" id="your-file" accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx" aria-invalid="false">
</span>
<label class="custom-file-label" for="your-file">Your file</label></div>
And it doesn't work anymore.
JS seems ok with the CF7 code.
Maybe it doesn't work because of CF7's way of generating code ?
I don't know.. Do you have an idea ?
Thank in advance for your help :)
A: [file file-265 id:fileuploadfield class:fileuploadfield limit:120000 filetypes:.jpg .png 1/]
[text uploadtextfield id:uploadtextfield class:uploadtextfield]
<input type="button" id="uploadfile" value="select">
A: As CF7 wraps the field inside <span> first you need to look for the parent container (assuming .custom-file), and then look for the .custom-file-label.
$(".custom-file-input").on("change", function() {
var filename = $(this).val().split("\\").pop();
$(this).parents(".custom-file").find(".custom-file-label").addClass("selected").html(filename);
});
This is kind of a late answer, but I was having this same issue today and this question helped me find the solution.
| |
doc_3999
|
Parse.Cloud.define('followPush', function(request, response) {
send = function(request) {
var promise = new Parse.Promise();
var jsonBody = {
app_id: "XXX",
included_segments: ["All"],
contents: {en: "English Message"},
data: {foo: "bar"}
};
Parse.Cloud.httpRequest({
method: "POST",
url: "https://onesignal.com/api/v1/notifications",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic XXX"
},
body: JSON.stringify(jsonBody)
}).then(function (httpResponse) {
promise.resolve(httpResponse)
},
function (httpResponse) {
promise.reject(httpResponse);
});
return promise;
};
exports.send = send;
});
I get a "request timeout" on my server logs and a "JSON text did not start with..." on client side. If i send a push notification from the OneSignal website, it reaches the user. I had it working with Parse but do not understand with oneSignal.
A: It looks like you were able to get in touch with the OneSignal dev team to resolve this. (I help work on OneSignal)
For the benefit of other StackOverflow users, the solution was to change your httpRequest code to be as follows:
Parse.Cloud.httpRequest({
url: "https://onesignal.com/api/v1/notifications",
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Basic XXX"
},
body: JSON.stringify(jsonBody),
success: function(httpResponse) {
response.success("sent");
},
error: function(httpResponse) {
response.error('Failed with: ' + httpResponse.status);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.