Which Registry Editor Version to initiate reg file with when editing the Windows registry (if needed at all)?

Question: According to Microsoft knowledge base article 310516, one should initiate .reg files editing the Windows registry with either

Windows Registry Editor Version 5.00
for Windows 2000, Windows XP, and Windows Server 2003
or
REGEDIT4
for Windows 95, Windows 98 and Windows NT 4.0.

When on Windows 7, is it correct to initiate with Windows Registry Editor Version 5.00 or should one state version 6 instead?
Is it in fact needed at all when running a .bat file instead?
For current version click in Registry Editor in menu Help on menu item About Registry Editor.
Answer: There are used mainly two standard applications to process Windows registry from within a batch file:

reg.exe
regedit.exe

On Windows x64 both exist as 32-bit and as 64-bit applications whereby the 32-bit versions access the registry like 32-bit applications which means registry redirector is active and registry keys for 64-bit applications are not visible for 32-bit REG and REGEDIT.
It is in general better to use REG instead of REGEDIT for getting (read access) or setting (write access) just a few keys or values in batch files.
The usage of REGEDIT requires always administrator privileges since Windows Vista even when just used to export keys into a registry file (read access) or when importing data from a registry file (write access) to HKEY_CURRENT_USER (short: HKCU).
By using REG many operations like QUERY (read access) or ADD (write access) to HKCU don't need administrator privileges. Of course a write access to HKEY_LOCAL_MACHINE (short: HKLM) requires administrator privileges as also other not often used operations. Running in a command prompt window reg /? shows the available operations. reg query /? and reg add /? executed in a console window displays syntax and options to get (query) or set (add) data in Windows registry.
A *.reg file is interpreted on import only as file with valid registry data if the first line of the file contains

REGEDIT4
or
Windows Registry Editor Version 5.00

This is not the version of registry editor or the Windows version. It is a version information for format of the registry data in the file itself. So it is a registry file format version. The first line of a registry file must have one of those two strings.
An attempt importing a *.reg file without this header line results in an error.
Windows 2000 (has also regedt32.exe) and later versions of Windows support registry files in both format versions, 4 and 5.
Windows 95, 98, Millennium and NT4 support only registry files in format 4.
So it depends nowadays (year 2016) mainly on the data which format to use for a registry file.
The main difference is the supported encoding of text data.
Registry files in format REGEDIT4 can be only text files with 1 byte per character using the code page defined in Windows Locales and Languages settings for non Unicode aware applications which is Windows-1252 for North American and Western European countries. Therefore registry files in format REGEDIT4 cannot contain Unicode characters with a code value greater 255 (decimal, 0xFF hexadecimal).
Registry files in format Windows Registry Editor Version 5.00 support text encoded with more than 1 byte per character according to Unicode standard. Therefore *.reg files in format Windows Registry Editor Version 5.00 are created by REGEDIT as UTF-16 Little Endian encoded text files with Byte Order Mark (FF FE).
So it does not matter which file format to use if the data to import / export is binary or text using only ASCII characters (code value < decimal 128) as 99.99 % of all registry data.
For non ASCII characters it is already important to know which code page is used by Windows command interpreter as this is usually an OEM code page like code page 437 (US, Canada) or code page 850 (Western Europe) being different from GUI code page Windows-1252. Running in a command prompt window chcp or mode con outputs the default code page used on current computer by Windows command interpreter for console.
If it is really necessary to support also Unicode strings, it is necessary to use format Windows Registry Editor Version 5.00.
Let us look on a hypothetical Unicode example:
In Windows registry under key HKCU\RegFormat there are two Unicode strings defined:

A string of type REG_SZ with name Two Not Equal 3 with Unicode string value:
2 ≠ 3

A multi-line string of type REG_MULTI_SZ with name Formulas with Unicode string value:
2 µs × 3 = 6 µs
A = π × r²

See the Microsoft articles Registry Value Types, Distributing Registry Changes and Data Types in the Registry for details about registry value types.
Exporting key HKCU\RegFormat in format Windows Registry Editor Version 5.00 being the standard format since Windows 2000 results in a UTF-16 LE encoded text file with 596 bytes with content:
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\RegFormat]
"Two Not Equal 3"="2 ≠ 3"
"Formulas"=hex(7):32,00,20,00,b5,00,73,00,20,00,d7,00,20,00,33,00,20,00,3d,00,\
  20,00,36,00,20,00,b5,00,73,00,00,00,41,00,20,00,3d,00,20,00,c0,03,20,00,d7,\
  00,20,00,72,00,b2,00,00,00,00,00

The byte stream of this file is displayed in a hexadecimal viewer/editor as:
00000000h: FF FE 57 00 69 00 6E 00 64 00 6F 00 77 00 73 00 ; ÿþW.i.n.d.o.w.s.
00000010h: 20 00 52 00 65 00 67 00 69 00 73 00 74 00 72 00 ;  .R.e.g.i.s.t.r.
00000020h: 79 00 20 00 45 00 64 00 69 00 74 00 6F 00 72 00 ; y. .E.d.i.t.o.r.
00000030h: 20 00 56 00 65 00 72 00 73 00 69 00 6F 00 6E 00 ;  .V.e.r.s.i.o.n.
00000040h: 20 00 35 00 2E 00 30 00 30 00 0D 00 0A 00 0D 00 ;  .5...0.0.......
00000050h: 0A 00 5B 00 48 00 4B 00 45 00 59 00 5F 00 43 00 ; ..[.H.K.E.Y._.C.
00000060h: 55 00 52 00 52 00 45 00 4E 00 54 00 5F 00 55 00 ; U.R.R.E.N.T._.U.
00000070h: 53 00 45 00 52 00 5C 00 52 00 65 00 67 00 46 00 ; S.E.R.\.R.e.g.F.
00000080h: 6F 00 72 00 6D 00 61 00 74 00 5D 00 0D 00 0A 00 ; o.r.m.a.t.].....
00000090h: 22 00 54 00 77 00 6F 00 20 00 4E 00 6F 00 74 00 ; ".T.w.o. .N.o.t.
000000a0h: 20 00 45 00 71 00 75 00 61 00 6C 00 20 00 33 00 ;  .E.q.u.a.l. .3.
000000b0h: 22 00 3D 00 22 00 32 00 20 00 60 22 20 00 33 00 ; ".=.".2. .`" .3.
000000c0h: 22 00 0D 00 0A 00 22 00 46 00 6F 00 72 00 6D 00 ; ".....".F.o.r.m.
000000d0h: 75 00 6C 00 61 00 73 00 22 00 3D 00 68 00 65 00 ; u.l.a.s.".=.h.e.
000000e0h: 78 00 28 00 37 00 29 00 3A 00 33 00 32 00 2C 00 ; x.(.7.).:.3.2.,.
000000f0h: 30 00 30 00 2C 00 32 00 30 00 2C 00 30 00 30 00 ; 0.0.,.2.0.,.0.0.
00000100h: 2C 00 62 00 35 00 2C 00 30 00 30 00 2C 00 37 00 ; ,.b.5.,.0.0.,.7.
00000110h: 33 00 2C 00 30 00 30 00 2C 00 32 00 30 00 2C 00 ; 3.,.0.0.,.2.0.,.
00000120h: 30 00 30 00 2C 00 64 00 37 00 2C 00 30 00 30 00 ; 0.0.,.d.7.,.0.0.
00000130h: 2C 00 32 00 30 00 2C 00 30 00 30 00 2C 00 33 00 ; ,.2.0.,.0.0.,.3.
00000140h: 33 00 2C 00 30 00 30 00 2C 00 32 00 30 00 2C 00 ; 3.,.0.0.,.2.0.,.
00000150h: 30 00 30 00 2C 00 33 00 64 00 2C 00 30 00 30 00 ; 0.0.,.3.d.,.0.0.
00000160h: 2C 00 5C 00 0D 00 0A 00 20 00 20 00 32 00 30 00 ; ,.\..... . .2.0.
00000170h: 2C 00 30 00 30 00 2C 00 33 00 36 00 2C 00 30 00 ; ,.0.0.,.3.6.,.0.
00000180h: 30 00 2C 00 32 00 30 00 2C 00 30 00 30 00 2C 00 ; 0.,.2.0.,.0.0.,.
00000190h: 62 00 35 00 2C 00 30 00 30 00 2C 00 37 00 33 00 ; b.5.,.0.0.,.7.3.
000001a0h: 2C 00 30 00 30 00 2C 00 30 00 30 00 2C 00 30 00 ; ,.0.0.,.0.0.,.0.
000001b0h: 30 00 2C 00 34 00 31 00 2C 00 30 00 30 00 2C 00 ; 0.,.4.1.,.0.0.,.
000001c0h: 32 00 30 00 2C 00 30 00 30 00 2C 00 33 00 64 00 ; 2.0.,.0.0.,.3.d.
000001d0h: 2C 00 30 00 30 00 2C 00 32 00 30 00 2C 00 30 00 ; ,.0.0.,.2.0.,.0.
000001e0h: 30 00 2C 00 63 00 30 00 2C 00 30 00 33 00 2C 00 ; 0.,.c.0.,.0.3.,.
000001f0h: 32 00 30 00 2C 00 30 00 30 00 2C 00 64 00 37 00 ; 2.0.,.0.0.,.d.7.
00000200h: 2C 00 5C 00 0D 00 0A 00 20 00 20 00 30 00 30 00 ; ,.\..... . .0.0.
00000210h: 2C 00 32 00 30 00 2C 00 30 00 30 00 2C 00 37 00 ; ,.2.0.,.0.0.,.7.
00000220h: 32 00 2C 00 30 00 30 00 2C 00 62 00 32 00 2C 00 ; 2.,.0.0.,.b.2.,.
00000230h: 30 00 30 00 2C 00 30 00 30 00 2C 00 30 00 30 00 ; 0.0.,.0.0.,.0.0.
00000240h: 2C 00 30 00 30 00 2C 00 30 00 30 00 0D 00 0A 00 ; ,.0.0.,.0.0.....
00000250h: 0D 00 0A 00                                     ; ....

The first 2 bytes being displayed with code page Windows-1252 as ÿþ are the two bytes of the UTF-16 LE BOM which is not displayed by text editors in text editing mode.
But exporting key HKCU\RegFormat in format REGEDIT4 by clicking on file type drop down list in export dialog and selecting Win9x/NT4 registry files results in an ANSI (more precise: Windows-1252) encoded text file with just 180 bytes with content:
REGEDIT4

[HKEY_CURRENT_USER\RegFormat]
"Two Not Equal 3"="2 ? 3"
"Formulas"=hex(7):32,20,b5,73,20,d7,20,33,20,3d,20,36,20,b5,73,00,41,20,3d,20,\
  c0,20,d7,20,72,b2,00,00

The byte stream of this file is displayed in a hexadecimal viewer/editor as:
00000000h: 52 45 47 45 44 49 54 34 0D 0A 0D 0A 5B 48 4B 45 ; REGEDIT4....[HKE
00000010h: 59 5F 43 55 52 52 45 4E 54 5F 55 53 45 52 5C 52 ; Y_CURRENT_USER\R
00000020h: 65 67 46 6F 72 6D 61 74 5D 0D 0A 22 54 77 6F 20 ; egFormat].."Two
00000030h: 4E 6F 74 20 45 71 75 61 6C 20 33 22 3D 22 32 20 ; Not Equal 3"="2
00000040h: 3F 20 33 22 0D 0A 22 46 6F 72 6D 75 6C 61 73 22 ; ? 3".."Formulas"
00000050h: 3D 68 65 78 28 37 29 3A 33 32 2C 32 30 2C 62 35 ; =hex(7):32,20,b5
00000060h: 2C 37 33 2C 32 30 2C 64 37 2C 32 30 2C 33 33 2C ; ,73,20,d7,20,33,
00000070h: 32 30 2C 33 64 2C 32 30 2C 33 36 2C 32 30 2C 62 ; 20,3d,20,36,20,b
00000080h: 35 2C 37 33 2C 30 30 2C 34 31 2C 32 30 2C 33 64 ; 5,73,00,41,20,3d
00000090h: 2C 32 30 2C 5C 0D 0A 20 20 63 30 2C 32 30 2C 64 ; ,20,\..  c0,20,d
000000a0h: 37 2C 32 30 2C 37 32 2C 62 32 2C 30 30 2C 30 30 ; 7,20,72,b2,00,00
000000b0h: 0D 0A 0D 0A                                     ; ....

What are the differences?

REGEDIT first converted the string of type REG_SZ from Unicode to code page Windows-1252 and then exported the data. The result is character ? instead of not equal sign with Unicode value U+2260 in string of type REG_SZ because this character is not available in code page Windows-1252.

The multi-line string has just halve of the hexadecimal values (just 1 byte per character instead of 2 bytes per character).

The small PI with Unicode value U+03C0 is stored with value C0 (just low byte) and is therefore now the character À as this character has code value 0xC0 in code page Windows-1252.

Importing the data from file in format Windows Registry Editor Version 5.00 results in getting same data in Windows registry as before.
But importing the data from file in format REGEDIT4 results in:

A string of type REG_SZ with name Two Not Equal 3 with ANSI string value:
2 ? 3

A multi-line string of type REG_MULTI_SZ with name Formulas with Unicode string value:
2 µs × 3 = 6 µs
A = À × r²

The characters µ and × and ² have a code value < 255 (decimal) and can be therefore correct stored also in registry file of format REGEDIT4. But ≠ and π can't be correct encoded in format 4.
A registry file of format Windows Registry Editor Version 5.00 must not be itself a Unicode encoded text file. It is also possible to have a Windows-1252 encoded registry file with content:
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\RegFormat]
"Two Not Equal 3"=hex(1):32,00,60,22,33,00
"Formulas"=hex(7):32,00,20,00,b5,00,73,00,20,00,d7,00,20,00,33,00,20,00,3d,00,\
  20,00,36,00,20,00,b5,00,73,00,00,00,41,00,20,00,3d,00,20,00,c0,03,20,00,d7,\
  00,20,00,72,00,b2,00,00,00,00,00

being displayed in a hexadecimal viewer/editor as:
00000000h: 57 69 6E 64 6F 77 73 20 52 65 67 69 73 74 72 79 ; Windows Registry
00000010h: 20 45 64 69 74 6F 72 20 56 65 72 73 69 6F 6E 20 ;  Editor Version
00000020h: 35 2E 30 30 0D 0A 0D 0A 5B 48 4B 45 59 5F 43 55 ; 5.00....[HKEY_CU
00000030h: 52 52 45 4E 54 5F 55 53 45 52 5C 52 65 67 46 6F ; RRENT_USER\RegFo
00000040h: 72 6D 61 74 5D 0D 0A 22 54 77 6F 20 4E 6F 74 20 ; rmat].."Two Not
00000050h: 45 71 75 61 6C 20 33 22 3D 68 65 78 28 31 29 3A ; Equal 3"=hex(1):
00000060h: 33 32 2C 30 30 2C 36 30 2C 32 32 2C 33 33 2C 30 ; 32,00,60,22,33,0
00000070h: 30 0D 0A 22 46 6F 72 6D 75 6C 61 73 22 3D 68 65 ; 0.."Formulas"=he
00000080h: 78 28 37 29 3A 33 32 2C 30 30 2C 32 30 2C 30 30 ; x(7):32,00,20,00
00000090h: 2C 62 35 2C 30 30 2C 37 33 2C 30 30 2C 32 30 2C ; ,b5,00,73,00,20,
000000a0h: 30 30 2C 64 37 2C 30 30 2C 32 30 2C 30 30 2C 33 ; 00,d7,00,20,00,3
000000b0h: 33 2C 30 30 2C 32 30 2C 30 30 2C 33 64 2C 30 30 ; 3,00,20,00,3d,00
000000c0h: 2C 5C 0D 0A 20 20 32 30 2C 30 30 2C 33 36 2C 30 ; ,\..  20,00,36,0
000000d0h: 30 2C 32 30 2C 30 30 2C 62 35 2C 30 30 2C 37 33 ; 0,20,00,b5,00,73
000000e0h: 2C 30 30 2C 30 30 2C 30 30 2C 34 31 2C 30 30 2C ; ,00,00,00,41,00,
000000f0h: 32 30 2C 30 30 2C 33 64 2C 30 30 2C 32 30 2C 30 ; 20,00,3d,00,20,0
00000100h: 30 2C 63 30 2C 30 33 2C 32 30 2C 30 30 2C 64 37 ; 0,c0,03,20,00,d7
00000110h: 2C 5C 0D 0A 20 20 30 30 2C 32 30 2C 30 30 2C 37 ; ,\..  00,20,00,7
00000120h: 32 2C 30 30 2C 62 32 2C 30 30 2C 30 30 2C 30 30 ; 2,00,b2,00,00,00
00000130h: 2C 30 30 2C 30 30 0D 0A 0D 0A                   ; ,00,00....

Importing this registry file produces nevertheless in Windows registry the Unicode strings:
2 ≠ 3
2 µs × 3 = 6 µs
A = À × r²

Using binary representation hex(1) for a value of type REG_SZ is not standard. This example was created manually by me to demonstrate that it is possible to import a Unicode string of type REG_SZ also with a non Unicode encoded registry file which is easier to produce from within a batch file.
But if the name of a key or value contains itself a Unicode character with a code value greater U+00FF, it is really necessary to use registry file format Windows Registry Editor Version 5.00 with registry file being also Unicode encoded using 16-bit Unicode Transformation Format with little-endian format.
See function SHRegWriteUSValue for hex(?) ... REG_? registry type table.
By the way: I wrote once the UltraEdit script GetStringFromRegHex.js to get the hexadecimal values of type hex(2) ... REG_EXPAND_SZ and hex(7) ... REG_MULTI_SZ selected in a registry file opened in text editor UltraEdit displayed as text because the hexadecimal values are really hard to "read as text" for a human.
The command line
%SystemRoot%\System32\regedit.exe /a /e "%USERPROFILE%\Desktop\EntireWindowsRegistry.reg"

exports the entire Windows registry to Windows desktop in ANSI using registry file format 4.
The same command line without option /a results in an export of entire Windows registry in Unicode using registry file format 5.


Why is Wolfram giving me a different answer for standard deviation?

Question: I have the following set of data:
<code>Raw Scores   x-x̄        (x-x̄)²
-----------------------------
 7           -6            36
 8           -5            25
10           -3             9
14            1             1
26           13           169
-----------------------------
65            0           240
-----------------------------
</code>
From the raw scores we know that : $$ n=5 $$ and ∴ the mean, $$ x̄ = \frac{\sum}{n}  = \frac{65}{5}   =    13 $$
I then proceeded to complete the table above filling in $$ x-x̄ $$ & $$ (x-x̄ )² $$
I am now required to calculate the standard deviation & have the following  eqation.
$$
\sigma = \sqrt{\frac{\sum(x_i-\overline{x})^2}{n}}
= \sqrt{\frac{240}{5}} = 4 \sqrt{15} $$
However when I submit my data to wolfram and query standard deviatioin it returns the answer$$2\sqrt{15}$$
Maybe this is out of the scope of my learning but being curious I opened the step by step answer and I see that wolfram calculates the standard deviation by
$$
\sigma = \sqrt{\frac{\sum(x_i-\overline{x})^2}{n-1}}
$$
My textbook accessible here  and another textbook my teacher printed out have the eqation    , I find it hard to believe that My teacher and 2 other textbooks can be wrong however Im pretty sure the developers at wolfram couldn't have got it wrong either.
What am I missing?
Answer: The difference is that you are calculating the true standard deviation, and Wolfram|Alpha is calculating the sample standard deviation.
Here's the difference, if you use the formula
$$
\sigma = \sqrt{\frac{\sum(x_i-\overline{x})^2}{n}}
$$
then you are answering the question "how much on average does my data differ from its mean?"
If you use the formula
$$
\sigma_S = \sqrt{\frac{\sum(x_i-\overline{x})^2}{n-1}}
$$
you are answering the question "if my data is a representative sample of a population, what is my best estimate of how much the population differs from its mean on average?"
Comment: See http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for a short tutorial.
Comment: Thanks This satisfies my curiosity will definitely upvote when I have the rep to do so straying from the topic , how did you format your eqations?I tried editing yor post to see the code behind it I can see that code but where will I find more examples??


httpd.conf redirect / to 8080 and redirect /index.html to /app/index.html

Question: How can create this conf on httpd.conf:
user access http://site and see content from http://site:8080
but
when they access http://site/index.html, it should redirect to http://site/app/index.html
which is the content from http://site:8080/app/index.html
and when user access http://site:8080/index.html it should keep the acess like that. Do not redirect to http://site:8080/app/index.html
I tried this conf on httpd.conf:
Redirect "/index.html" "/app/index.html"

ProxyRequests Off
ProxyPreserveHost on

ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
RewriteEngine On

But the index.html to app/index.html is not working.
Can it be done with httpd.conf?
the 8080 is on tomcat and the 80 is on httpd.
Answer: Found the answer:
RewriteRule ^/index\.html$ /app/index.html [L,R]


Do capos exist that can be disabled without removing them from the guitar?

Question: There's a song I want to play (in C) where the verse sounds best played on regular 1st-fret chords and the chorus sounds great using chords around the 8th fret - I can't barre them all reliably enough so would normally capo on fret 8 and transpose the chords from C to E.
But playing alone, I can't switch the capo fast enough. So I wondered if capos exist which can be placed on the desired fret without actually pressing the strings, so you can "turn the capo on/off" without actually moving it? I can see in my mind that it's mechanically possible but have no idea if it exists, or what it would be called so I can search for it.
Anyone know?
Comment: Even when you can barre well enough a capo will give a different timbre to those chords, particularly on acoustic.
Comment: Years ago I saw a device that screwed to the headstock and could be folded over to mute the strings by resting a pad on them, generally behind the first fret.  Note it was ONLY a string mute for tapping, not a capo. Perhaps something like this could be built, but it would need a very long lever arm to reach the 8th fret!  Another possibility is a doubleneck but that would be a slow changeover... or a 2nd guitar on an upright stand (in playing position)?
Comment: A capo will generally affect the tuning as well. You'd be better off improving your barre technique, or having your guitar's action seen to if it is too high.
Comment: While being able to play barre chords perfectly is always worth aiming for, playing an entire song using exclusively full barre chords is something that's _very_ hard to achieve. And as @Tim says it still won't sound the same. In addition if you capo, you can play voicings that are simply impossible with a barre.
Answer: Yes. You can use a spider capo for this kind of things.

Generally, it is used for alternate tunings. Like if you only want to capo 2 or 3 strings, but you can capo all 6 of them and then remove all of them.
Here is a video review:

spidercapo.com
Comment: @Mr.Boy Depending on how that thing is constructed exactly, could you perhaps glue the tumblers together in your preferred setting so you can easily switch them all at once?
Comment: That's very cool but not exactly what I'm after - I want the ability to leave the capo in place but toggle all strings at once. I suppose you can toggle all 'fingers' at once on the Spider but I'm not sure that's perfect.
Answer: Amalgamating the answers and comments. Play standard in open chord form at the nut end of the fingerboard, with a Spider capo fixed on the 8th fret. With it there, but none of the cams operational, all the 'open' chords will still work. At chorus time, flick all the cams on, and assume 'barre' chords, which will be E and A shape, I guess, with the capo being the 'nut'.
As suggested by Pepijn, a bar across the fingers of the capo would make the flick easier. Maybe Spider can come up with an adaptor. But it shouldn't be too difficult to fashion a small bar to join all the fingers of the Spider. Then it's just familiarization. There may be one or two tuning issues with it - often capos detune (untune?) a little.
Comment: Sounds like it should be workable. As well as the standard A & E chords (which as pointed out could be played as barred F & C on 8th fret) I play an open B chord 2 frets up from the capo to give my G and an open C#m 4 frets up to give Am - these cannot be played without a capo, only the fully barred versions.


New IIS7 virtual directory does not show on FTP client. What needs to happen?

Question: First, I might have to do this maybe once a year, so my memory is failing me as what exactly I did before to get this work because I've been able to do this times prior.  We are using an ISS 7 ftp server to recieve internal file transfers from an AIX server we have in house.  The only difference between then and now is that the existing virtual directories were migrated from a Windows 2003 (IIS 6) server to a Windows 2008 server.
All permisions from the existing directories are exactly the same as the new directory, yet the new virtual directory will not show in the any of the FTP clients I'm testing.  I do have FTP Directory Browsing turned on for the Default Site which is where all Virtual Directories reside.  The only thing I haven't done is stop/start IIS (which I don't remeber doing in the past), but I didn't want to needlessly restart IIS on a production server to only end up in the same place I am now.  What do I need to do to get this working?
UPDATE
Ok, had some down time to give IIS a restart, but no avail.  I am still not able to browse or view my newly created virtual directory on any FTP client.
Answer: Ok, figured it out.  We have a login script for all machines that maps a network drive.  It just so happens that the server I was working is the source of the mapped drive, the share on the server gets mapped as a drive.  Instead of using the actual path to directory I was trying to use for the virtural directory, I discovered I accidentally chose the mapped drive instead.  Once I reset virtual directory to the physical location on the drive, the directory appeared.
Answer: You mentioned that the folder were migrated from IIS/2003. I suggest that you verify the permissions the directories to make sure that the App Pool Identity that your FTP site is running on have permission to them. What authentication method are you using? Does IIS log indicate whether connections from the client are established successfully?


how to add another language in my app?

Question: In preview tab in android studio for XML files,I want to see my project in other language (in Persian), but i don't know, how to add Persian to Language (there is only English as default).
would you please help me?
Comment: Could you post your code through editing this question? Please show us what you tried to do.
Answer: first make values-fa directory and make strings.xml file in this directory.
Then in preview tab new language add automatically.
فایل مربوط به زبان فارسی رو ایجاد کن به صورت خودکار زبان به تب نمایش اضافه میشه.
Comment: perfect that is ok

how to add another language in my app?


Clustered JBoss Messaging, XA-recovery: JMSSecurityException

Question: I'm trying to set up clustered jboss-messaging with XA-recovery on a basic non-clustered, default server config (we only want clustered messaging, the rest is stateless with failover only) on JBoss EAP 4.3 (CP04).
When I add XA-recovery I get the following errors in the log:
09:05:07,558 ERROR [ExceptionUtil] ConnectionFactoryEndpoint[jboss.messaging.connectionfactory:service=ConnectionFactory] createFailoverConnectionDelegate [s-ar10uuuf-1-k1eztuuf-z44sla-t6avs4]
javax.jms.JMSSecurityException: User null is NOT authenticated

[... stacktrace removed for readablity ...]

09:05:07,559 ERROR [MessagingXAResourceWrapper] ********************************Failed to connect to server
javax.jms.JMSSecurityException: User null is NOT authenticated

Looks like I'm missing some security config - but I cannot figure out where.
I have double and tripple checked my config for errors and I'm using the following docs:
http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/messaging/JBoss_Messaging_User_Guide/html/recovery.html

The same config works like a charm in production config (Update: Not true anymore, see below)
Has anyone done this before? Got any ideas what I'm doing wrong?
Update:
The error depends on which datasource I use (DefaultDS vs. MyOwnDS) in the messaging config (*-presistence-service.xml). I have tried the following scenarios:

DefaultDS/HSQLDB: Works (of course this is the standard config...but who wants to use this config in production?)
DefaultDS/MySQL: Works (this is an acceptable work around)
MyOwnDS/MySQL: Does NOT work

It cant be that messaging depends on the datasource being named 'DefaultDS', so I guess there is some configuration associated with DefaultDS that goes missing when I use my own DS. But I cannot figure out what...
There is an entry (HsqlDbRealm) in login-config.xml that uses 'DefaultDS' but it doesn't look like it's used by messaging?
What am I missing?
Answer: Datasource used for authentication is specified in messaging-jboss-beans.xml.


Como inserir uma Toolbar no ActionBarDrawerToggle?

Question: Quero inserir um ícone como Toolbar mas o meu Android Studio denuncia um erro de conversão para Toolbar...
esse é o código do qual ele denuncia o erro:
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
                        R.mipmap.ic_launcher, R.string.drawer_open, DesR.string.drawer_close) {
    ...
    ...
};

ele dá erro na inserção do " R.mipmap.ic_launcher
Comment: como eu completo o meu método então?
actionBarDrawerToggle = new ActionBarDrawerToggle (this, drawerLayout, "O QUE INSERIR AQUI??", R.string.drawer_open, R.string.drawer_close) { ... };
Answer: Julgo que a razão é por estar a utilizar a support.v7.app.
Isto por si não é problema, a questão é que o construtor da classe ActionBarDrawerToggle da support.v7 é diferente da support.v4.
O construtor da classe  na v7 não tem o parâmetro drawerImageRes
No seu código não inclua o parâmetro R.mipmap.ic_launcher ao chamar o construtor:
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
                        R.string.drawer_open, R.string.drawer_close)


Build a new matrix made of some source matrix rows given a row index vector

Question: I want to build a new matrix made of some source matrix rows given a vector of non consecutive indexes.
Namely, I'd like a row() function which take a list of indexes and returns the list of rows stored in a new matrix :
  VectorXi v = VectorXi::LinSpaced( 4, 10, 13);
  MatrixXi m = v.rowwise().replicate( 4 );
  VectorXi r1 ( ( VectorXi(3) <<  0,  3, 1 ).finished() );

  // Here is some pseudo code to create the desired matrix N :
  MatrixXi N = m.row(r1);

  cout << "m = " << m << endl;
  cout << "r1 = " << r1 << endl;
  cout << "N = " << N << endl;

Desired output :
m =

10 10 10 10
11 11 11 11
12 12 12 12
13 13 13 13

r1 =
0
3
1

N =
10 10 10 10
13 13 13 13
11 11 11 11

Thanks a lot for helping.
Sylvain
Answer: With the development branch and (at least) C++11 enabled, you can write:
Eigen::MatrixXi N = m(r1,Eigen::all);

This is similar to the Matlab syntax:
N = m(r1, :);

You can also pass {x,...}-lists directly, or anything that behaves like an std::vector<int> (must provide a size() function and an operator[] and return an integral type), e.g.:
std::vector<int> c2{{3,0}};
std::cout << "m({2,1},c2) = \n" << m({2,1}, c2) << '\n';

These expressions are writable (assuming m itself is writable):
m({2,1}, c2) = Eigen::Matrix2i{{1,2},{3,4}};
std::cout << m << '\n';

Godbolt demo: https://godbolt.org/z/cjacOY
Comment: In general, the development branch should be save to use, but I would not dare to give any sort of promise or guarantee. Naturally, if your code is important you must make sure that **your code** is thoroughly and regularly unit-tested, especially every time you update your Eigen version (which you don't need to do that often). Even if Eigen was bug-free, there are plenty of ways it can be misused (and not everything is covered by assertions).
Comment: Got it ! Sorry for the disturbance : https://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html
Comment: Hi chtz, many thanks for this comprehensive and very pedagogical answer. I've seen indeed that v. 3.3.90 offered very nice facilities (
https://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html). Though, I've been developping a code which must be very reliable because it will be embedded into an important scientific system. Do you think it could be hazardous to base my software on the Eigen development branch ?.... Cheers. Sylvain
Comment: Hi chtz ! Do you know wether it exists some online Eigen dev versio documentation where what you described above is addressed ? Cheers !


acessing a subnetwork from within a vm

Question: I have a pc running windows 7.
I have vmwareplayer running RHEL5
I have 1 physical ethernet connection.
this ethernet connection is wired to a hub.
there is another device on that hub that needs to be in a certain subnetwork (192.168.0.xxx)(lets call him device X)
but the general network is 192.168.1.xxx
How can I configure the network adapters so that I can ping device X from RHEL5 in the vm.
Originally I could ping google from both windows and rhel (I was in the .1 network) but not device X since he is on a different subnetwork address.  Now that I have put it on the .0 I can ping device X from windows but not from rhel5 and cannot access the web. I did this by manually setting the IP address.
Answer: This question's been asked to death, basically use bridged networking.
Comment: No problem, though in future you may find that any questions you have may have been answered on here before, worth searching if you can.
Comment: tried that didn't work.
Comment: doesn't mean it's not right though - give us LOTS more detail and then we might be able to add more to our answers.
Comment: I was finally able to get it to work,  thanks for mentionning it had to be bridged even though there were other details involved I ended up being able to get it to work

acessing a subnetwork from within a vm


Remove user permission from content after creation

Question: We have a business case where it is needed to remove user permission for a specific content type after submission.
Think of it something like submitting an application.
If there is better workflow suited than removing user permission, please let me know.
Comment: Each content type has different permissions set allow user View/Create/Edit/Delete. in order to allow the user only create the application you need to give him a create permission, and after creation, he won't be able to edit it.
Answer: Are you asking because you only want a user to be able to create 1 (and only 1) node of a specific type? Or (as Ziftman suggests) do you just want to prevent the person the person from editing content after they have created it? If its the former, you could do something like this:
Create a custom module with a hook_form_alter that checks if the user has created content of that type and, if so, hide the form or redirect or whatever. D7 code below, but similar works for D8) Ex:
<code>function my_module_form_node_form_alter(&$form, $form_state) {
  global $user;

  // do a query to find out if the user has created a node of this type before
  $already_created = db_query("SELECT count(*) as count FROM {node} WHERE type='application' and uid=%uid", array('%uid' => $user->uid))->;

  if ($already_created->count) {
    $form['#access'] = FALSE;
    drupal_set_message("You cant do this");
    drupal_goto('some/other/path');
  }
}
</code>
Comment: Thanks. I'll try this one. This looks like better approach than Ziftman's in regard to our case.


drupal_static array losing values

Question: I have a module that i created for the sole purpose of integrating it with sitecatalyst.  If you are unaware of what sitecatalyst is, it is an api that helps create reports based on statistics of your website. EX: Pageviews, Visitors, etc.  Im aware there already is a module for omniture sitecatalyst but is not something i can really use.  I need to track many different variables as well as make it track when certain events fire.  EX: User Login, Create New Account, Comment Submitted, Search for something, etc.  Below i have code that fires everytime in preprocess_page, whenever a user logs in successfully, the properties i need set, and the setting of a static array with all the values i need to create the javascript code needed in order to track everything correctly.
My problem:
I used mymodule_user_login and launches as soon as a user logs in successfully.  I set all the properties and then set all those variables inside my static array.  However, the code in the preprocess_page gets launched everytime and therefore would overwrite the static array created when the mymodule_user_login function was called.  Can someone please help me how to figure out how to do this.  Ive been racking my brain.
Thank you in advance for any help
function mymodule_preprocess_page(&$variables) {
    if (arg(0) == 'admin') {
       return;
    }

    $props = retrieve_props();
    foreach ($props as $key => $data){
        mymodule_set_variable($key.'=', $data);
    }

    //CODE TO CREATE JAVASCRIPT CODE GOES HERE FOR SITE CATALYST
}

function mymodule_user_login(&$edit, &$account) {
    $props = retrieve_props();
    foreach ($props as $key => $data){
        mymodule_set_variable($key.'=', $data);
    }
    mymodule_set_variable('s.events=', 'event13');
}

function retrieve_props(){
    $props = array();

    /*Program Properties*/
    if (isset($_COOKIE['tsource']))
        $tsource = $_COOKIE['tsource'];
    else
        $tsource = 'Organic';
    $props['s.campaign'] = $tsource;

    $server = $_SERVER['COMPUTERNAME'];
    $props['s.server'] = $server;

    $header = drupal_get_http_header();
    if(isset($header['status'])){
        $pageType = 'errorPage';
    }
    else{
        $pageType = null;
    }
    $props['s.pageType'] = $pageType;

    $rel = getNodeRelation();
    $deg_level = null;
    $cat = null;
    $sub_cat = null;

    if (isset($rel['level']))
        $deg_level = $rel['level']['val'];

    if (isset($rel['category']))
        $cat = $rel['category']['val'];

    if (isset($rel['subject']))
        $sub_cat = $rel['subject']['val'];

    $props['s.prop1'] = $deg_level;
    $props['s.prop2'] = $cat;
    $props['s.prop3'] = $sub_cat;

    $schoolName = null;
    $program = null;
    $channel = null;
    $pageType = null;

    if(arg(0) == 'node'){
        $currentURL = drupal_get_path_alias($_GET['q']);
        $arrURL = explode('/',$currentURL);
        $channel = $arrURL[0];

        if ($variables['node']->type == 'school') {
            if (count($arrURL) > 1)
                $schoolName = $arrURL[1];
        }
     }
     else if (arg(0) == 'online-degree'){
         $program = arg(1).'-'.arg(4);
         $pagetype = 'program';
     }
     $props['s.prop4'] = $schoolName;
     $props['s.prop5'] = $program;

     $searchTerm = null;
     if (isset($_GET['textsearch']))
         $searchTerm = $_GET['textsearch'];

     $props['s.prop6'] = $searchTerm;

     return $props;
}

function mymodule_set_variable($name = NULL, $value = NULL) {
  $variables = &drupal_static(__FUNCTION__, array(), FALSE);

  if (empty($name)) {
     return $variables;
  }
  else {
     $variables['variables'][$name] = $value;
  }
}

function mymodule_get_variables() {
  return mymodule_set_variable();
}

Answer: If you look at the code for the form submission handler used for the user login form (user_login_submit()), you will notice that it executes the following code.
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);

user_login_finalize() is the function that invokes the hook_user_login() implementations.
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array('login' => $user->login))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);

Effectively, the user is redirected after hook_user_login() is invoked, which means a new page is being served, and Drupal is bootstrapping once again. The content returned from drupal_static() is then reset.
The solution is saving the value in a session variable, for example using functions like ctools_object_cache_get(), and ctools_object_cache_set(), which are already available if you are using the Views module on your site, as it requires the Chaos tool suite, on Drupal 7.
Answer: static variables will only persist for the length of a page view.  if you need something longer than that, you will either need to cache them in the database or use a $_SESSION variable.
Comment: the static variables are set during one page view.  However, the variable i set when the user logs in, disappears when the preprocess page function gets called.  Any clue as to why? thanks
Comment: I am thinking after you login you are actually redirected to a page, and hence, a new view...

drupal_static array losing values


App crashes when build release with React Native 0.60: Unhandled JS Exception: null is not an object (evaluating 'n.apply')

Question: I'm building an app with React Native 0.60.0. I tried to build to my real device and my app was crashed right at the launching.

I did not implement any code with API so I think it came from some 3rd libraries or RN 0.60.0
Answer: Oop! I found the reason of my issue. It came from Reactotron library. I will close this topic from now.


ionic 4 - Set background image for full page

Question: I am trying to set background image for full page with footer content
<ion-content class='background' fullscreen>
</ion-content>
<ion-footer no-border>
    <ion-row>
        <ion-col><ion-button size="large" fill='outline' expand="block" color="primary" (click)="goSearch()">English</ion-button></ion-col>
        <ion-col><ion-button size="large" fill='outline' expand="block" color="secondary" (click)="goSearch()">العربية</ion-button></ion-col>
    </ion-row>
</ion-footer>

Above code is not setting the background image to full page and displays the page as,

I tried to set ion-row transparent and it is not working as expected.
ion-row {
  --background: transparent;
  --ion-color-base: transparent !important;
}

But if I remove  or  in the footer, it works as expected.
<ion-footer no-border>
    <ion-button size="large" fill='outline' expand="block" color="primary" (click)="goSearch()">English</ion-button>
    <ion-button size="large" fill='outline' expand="block" color="secondary" (click)="goSearch()">العربية</ion-button>
</ion-footer>

As need to add some more controls, is there any way to make elements in the footer transparent?
Version:
"dependencies": {
    "@angular/common": "^7.2.2",
    "@angular/core": "^7.2.2",
    "@ionic-native/core": "^5.0.0",
    "@ionic/angular": "^4.1.0",
}

Thanks.
Answer: .background {
  --background: url("/assets/icon/background.jpg") 0 0/100% 100% no-repeat
 }

Answer: <ion-header translucent="true" no-border>
    <ion-toolbar>
       <ion-buttons color="secondary" slot="start">
          <ion-back-button color="secondary" text="" icon="arrow-round-back"></ion-back-button>
       </ion-buttons>
    <ion-title></ion-title>
</ion-toolbar>

<ion-content fullscreen="true" class="background">

</ion-content>


How to select a jenkins agent for a build based on github branch?

Question: Our project is written in java and deployed on to a Solaris environment in production. But , most of our test and dev machines are in Linux and so are our most Jenkins agents.
I'm looking for a way to run the Jenkins build in a Solaris agent only when the branch is master/release_branch and choose a Linux agent when the branch is something else.
Idea is to ensure we haven't introduced any compatibility issues in Solaris.
I'm looking for a declarative pipeline approach something like this, but will also select linux agent when condition is  not met.
stage('build') {
  steps {
    mvn clean
  }

  when {
    branch comparator: 'EQUALS', pattern: 'master'
    beforeAgent true
  }

  agent {
    label 'Solaris'
  }
}

Answer: I don't think when can do that. If you don't mind a bit of scripting you can do it like this
pipeline {
    agent none
    stages {
        stage('build') {
            agent {
                label env.GIT_BRANCH == 'master' ? 'Solaris' : 'Linux'
            }
            steps {
                sh 'hostname'
            }
        }
    }
}

Assuming you are storing the pipeline in git. I'm sure Bitbucket has a similar env variable.
Comment: I think this will work for me. I'm storing the pipeline file on git. Thank you


Exception while IsOneWay is True

Question: I am new to WCF. I have a small question to ask.
Let's assume IsOneWay=true is set in for one of the OperationContracts in my service contract. Let's say when client calls this method and some exception occurs in the method what happens.
Besically I want to know when this property is set to true how the exception behaves.
Please reply.
Thanks in Advance
Sudhanshu
Answer: Depends on the type of error:

if it's an error in your actual service code, then nothing will happen, since the server cannot communicate back anything - the service operation just won't happen. The client channel will be in a faulted state for any future non-one-way call, i.e. unusable for future operations, so you'll have to recreate it to use it again
if it's a security or timeout error, the exception on the client will still happen - those aren't affected by the IsOneWay=true setting

Does that answer your question? If not: what do you need to know?
Comment: It answered my doubts, I was wondering whether I should put a `try catch` block in my one-way method (which is non-critical, so it's ok to fail), even though I decided to log it.

Exception while IsOneWay is True


How to preselect facebook friends while sending message

Question: I am using : FacebookDialog.MessageDialogBuilder  and I am trying to add friends' ids which i get from facebook sdk.Or how can I preselect names before opening facebook message dialog.
<code>private void showFacebookMessageDialog() {
        try {
            FacebookDialog.MessageDialogBuilder builder =
                    new FacebookDialog.MessageDialogBuilder(this)
            .setLink("https://developers.facebook.com/docs/android/share/")
            .setName("Message Dialog Tutorial")
            .setCaption("Build great social apps that engage your friends.")
            .setPicture("http://i.imgur.com/g3Qc1HN.png")
            .setDescription("Allow your users to message links from your app using the Android SDK.")
            .setFriends(Arrays.asList("111","123"));
            ;
            builder.build().present();
        } catch (FacebookException ex) {
            // error handling
        }
    }
</code>
Answer: It's not supported. The setFriends method only supports tagging a friend (in pictures or status updates), and is not used for preselction. We will update the docs accordingly.


Estou tantando colocar o titulo da imagem em minha galeria Wordpress

Question: Olá, estou tentando chamar o o titulo da imagem, para ser exibido na galeria, mas é chamado somente o titulo da primeira fotos e todas as outras estão com o mesmo titulo, será que poderiam me ajudar?
Segue meu código:
<?php

        $imagens_ids = $product->get_gallery_attachment_ids();

        $imagens = array();

        $imagens[] = get_the_post_thumbnail_url();

        foreach ($imagens_ids as $imagem_id) {

            $imagens[] = wp_get_attachment_url($imagem_id);
          $title = get_post(get_post_thumbnail_id())->post_title;
      }

        echo '
';

            echo '
';

                foreach ($imagens as $imagem) {

                    echo '
';

                        echo '
';

                            echo '';

                                echo '';

                            echo '';

                        echo'
';

                        echo '
';

                            echo '
'.$title.'
';

                        echo'
';

                    echo'
';

                }

            echo'
';

        echo'
';

        ?>

Answer: Se você tem os ids das imagens, tente isso:
get_the_title($imagem_id)


Como obter objetos de um Array de Json usando JsonArray no java?

Question: Estou com uma pequena dificuldade em obter informações de um Array de Json, pois esta dando  o erro:

Exception in thread "main" json.org.JSONException: JSONArray initial value should be a string or collection or array.

A saida do json é:
{"status":"OK","data":[{"worker":"kappauni1","time":1523537400,"lastSeen":1523537364,"reportedHashrate":113223366,"currentHashrate":102500000,"validShares":89,"invalidShares":0,"staleShares":5,"averageHashrate":68804012.34567899},{"worker":"kappauni2","time":1523537400,"lastSeen":1523537351,"reportedHashrate":108686214,"currentHashrate":110277777.77777778,"validShares":96,"invalidShares":0,"staleShares":5,"averageHashrate":62395061.72839507},{"worker":"kappauni3","time":1523537400,"lastSeen":1523537396,"reportedHashrate":211388916,"currentHashrate":175388888.8888889,"validShares":152,"invalidShares":0,"staleShares":9,"averageHashrate":120002314.8148148}]}

Seguem as classes, agradeceria muito se dessem uma luz.
CLASSE MAIN
public class Main {

    public static void main(String[]args){

        Conection conection = new Conection();

        Convert convert = new Convert();
        convert.convertJsonForObject(conection.getJson());

    }

}

Classe responsável por fazer conexão e gerar um return em StringBuilder.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

 class Conection
{

   private StringBuilder resultado = new StringBuilder();

    StringBuilder getJson()
    {

        String address = "https://api.ethermine.org/miner/0x0940f5fAEF2bba7e1e6288E4bc4E9c75ee334b97/workers";

        try {
            URL url = new URL(address);

            try {
                URLConnection connect = url.openConnection();

                connect.setRequestProperty("User-Agent", "Mozilla/4.0");
                InputStream in = connect.getInputStream();
                InputStreamReader inRead = new InputStreamReader(in);

                BufferedReader reader = new BufferedReader(inRead);

                String result;

                while((result = reader.readLine())!=null){

                    this.resultado = resultado.append(result);

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

            return resultado;
    }

}

Classe responsável por converter Json em objeto, aqui que não consigo obter corretamente os dados do Array de Json.
import json.org.JSONArray;
import json.org.JSONObject;

 class Convert {

     void convertJsonForObject(StringBuilder json){

        System.out.println(json);

         JSONObject obj = new JSONObject(json);
         JSONArray jArray = obj.getJSONArray("data");

        for(int i = 0; i < jArray.length(); i++){

            obj = jArray.getJSONObject(i);

            System.out.print(obj.toString());
        }

    }
}

A saida do erro é :
{"status":"OK","data":[{"worker":"kappauni1","time":1523548800,"lastSeen":1523548743,"reportedHashrate":113155830,"currentHashrate":95833333.33333333,"validShares":83,"invalidShares":0,"staleShares":5,"averageHashrate":69709876.54320988},{"worker":"kappauni2","time":1523548800,"lastSeen":1523548779,"reportedHashrate":108667905,"currentHashrate":86944444.44444445,"validShares":75,"invalidShares":0,"staleShares":5,"averageHashrate":64443672.83950619},{"worker":"kappauni3","time":1523548800,"lastSeen":1523548783,"reportedHashrate":213519635,"currentHashrate":167611111.1111111,"validShares":145,"invalidShares":0,"staleShares":9,"averageHashrate":123407407.40740736}]}

Exception in thread "main" json.org.JSONException: JSONObject["data"] not found.
    at json.org.JSONObject.get(JSONObject.java:566)
    at json.org.JSONObject.getJSONArray(JSONObject.java:760)
    at Convert.convertJsonForObject(Convert.java:11)
    at Main.main(Main.java:10)

Process finished with exit code 1

Comment: Em qual linha é disparada a exceção?
Comment: O construtor do JSONArray espera uma string, e você está passando uma instância de StringBuilder. Tente : `jArray = new JSONArray(json.toString());`
Comment: Atualizei nesse momento, se puder dar uma olhadinha.
Answer: Você precisa pegar o array que está dentro do objeto...
Tente desta forma:
package br.com.uniondata.projetodetestes;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Nilson
 */
public class Json {
    public static void main(String[] args) {
        Conection conection = new Conection();

        //StringBuilder json=new StringBuilder("{'status':'OK','data':[{'worker':'kappauni1','time':1523537400,'lastSeen':1523537364,'reportedHashrate':113223366,'currentHashrate':102500000,'validShares':89,'invalidShares':0,'staleShares':5,'averageHashrate':68804012.34567899},{'worker':'kappauni2','time':1523537400,'lastSeen':1523537351,'reportedHashrate':108686214,'currentHashrate':110277777.77777778,'validShares':96,'invalidShares':0,'staleShares':5,'averageHashrate':62395061.72839507},{'worker':'kappauni3','time':1523537400,'lastSeen':1523537396,'reportedHashrate':211388916,'currentHashrate':175388888.8888889,'validShares':152,'invalidShares':0,'staleShares':9,'averageHashrate':120002314.8148148}]}");
        StringBuilder json=conection.getJson();
        JSONObject obj=null;
        try{
            obj=new JSONObject(json.toString());
            System.out.println(obj.toString());
            JSONArray jArray = obj.getJSONArray("data");
            for(int i = 0; i < jArray.length(); i++){
                JSONObject o = jArray.getJSONObject(i);
                System.out.println(o.toString());
            }
        }catch(JSONException e){
            e.printStackTrace();
        }
    }
}

Saída:
--- exec-maven-plugin:1.2.1:exec (default-cli) @ ProjetoDeTestes ---
{"data":[{"validShares":86,"staleShares":5,"lastSeen":1523551133,"currentHashrate":9.916666666666667E7,"averageHashrate":7.309104938271604E7,"invalidShares":0,"time":1523551200,"worker":"kappauni1","reportedHashrate":113159753},{"validShares":103,"staleShares":7,"lastSeen":1523551162,"currentHashrate":119500000,"averageHashrate":6.799305555555557E7,"invalidShares":0,"time":1523551200,"worker":"kappauni2","reportedHashrate":108694107},{"validShares":179,"staleShares":12,"lastSeen":1523551195,"currentHashrate":2.0755555555555555E8,"averageHashrate":1.3074074074074067E8,"invalidShares":0,"time":1523551200,"worker":"kappauni3","reportedHashrate":213535092}],"status":"OK"}
{"validShares":86,"staleShares":5,"lastSeen":1523551133,"currentHashrate":9.916666666666667E7,"averageHashrate":7.309104938271604E7,"invalidShares":0,"time":1523551200,"worker":"kappauni1","reportedHashrate":113159753}
{"validShares":103,"staleShares":7,"lastSeen":1523551162,"currentHashrate":119500000,"averageHashrate":6.799305555555557E7,"invalidShares":0,"time":1523551200,"worker":"kappauni2","reportedHashrate":108694107}
{"validShares":179,"staleShares":12,"lastSeen":1523551195,"currentHashrate":2.0755555555555555E8,"averageHashrate":1.3074074074074067E8,"invalidShares":0,"time":1523551200,"worker":"kappauni3","reportedHashrate":213535092}
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.569s
Finished at: Thu Apr 12 13:50:44 BRT 2018
Final Memory: 5M/123M
------------------------------------------------------------------------

Comment: Perceba que a resposta apresenta uma dependência diferente da utilizada na pergunta, uma vez que na resposta se utiliza: `org.json.*`, enquanto a pergunta faz uso da: `json.org.*`
Comment: Fiz isso porém não acha o objeto "data". Atualizei o código e o erro.
Comment: Eu vi que vc está recebendo um `StringBuilder`. Então vc precisa convertê-lo com o toString(). No entanto, ele não achar o objeto "data" é estranho. Coloque o System.out.println, conforme meu exemplo, para confirmar que o json está chegando corretamente.
Comment: Fiz as alterações e coloquei a saída e o erro em seguida falando que não encontrou o objeto.
Comment: Cara, tem algum gato ai... Veja que eu refiz meu teste usando a mesma classe `Conection`, ou seja, o mesmo json e está rodando ok.
Comment: Bem observado WeslleyTavares. Diego, você pode utilizar a mesma biblioteca que eu usei ou a que você está usando é um requisito do projeto?
Comment: Posso usar, chegando em casa vou testar dessa forma, porém mesmo assim já me ajudaram bastante, agradeço a todos. Vou dar como resolvido.


Create a view which shows related staff members based on taxonomy

Question: I wish to show relevant staff members when users a viewing a particular page. For example when certain pages about membership are being viewed i wish to show the staff members designated as a 'Member Relations Officer'. I have a taxonomy called 'selected job roles', in which 'Member Relations Officer' is a taxonomy term. At the moment I have set up the staff members as users on the site, therefore they are not a distinct content type. I have added a 'selected job roles' term reference to the user fields within Account Settings.
I also added the 'selected job roles' term reference to the basic page content type. I have created a view block called 'selected job roles' in which I am trying (and failing) to set up a contextual filter correctly to show the staff members. I have a basic page with 'selected job roles' set as 'Member Relations Officer' and also a user with 'selected job roles' set as 'Member Relations Officer'. I have been trying to get it to work by doing things like setting up the contextual filter get the 'taxonomy term from url' when the 'Filter Value is not available'. However none of the contextual filter settings i have tried work.
Could somebody please advise me what settings i should using in the contextual filter? Was setting up the staff as users a mistake that is stopping this from working properly? Thank you in advance.
Answer: I have now got this to work! While I don't fully understand what is going on I thought I'd share it here in case it helps somebody else.
I created a content type 'staff profile' to work with rather than using users. The staff profile content type has the field 'selected job roles' added to it.
In views I made a new view with a display of block. I added a new contextual filter for 'Content: Nid' and set 'when filter is not available' to 'provide default value' and selected the 'content ID from URL' for the type.
Then I added three relationships.
The first was 'Content: Taxonomy terms on node', selecting my vocabulary 'Selected Job Roles' and ticked the 'require this relationship' checkbox.
The second relationship I added was '(term) Taxonomy term: Content using Selected Job Roles' and ticked the 'require this relationship' checkbox.
The third and final relationship I added was the field itself '(field_selected_job_roles) Field: Selected Job Roles'.
I then added a filter criteria 'Content: Type (=Staff Member Profile)' so that only staff member profiles would be displayed.
Now, having done all of this i clicked on the contextual filter for 'Content: Nid' that I set up earlier. I think that because of the relationships that were added there is now an extra option here that was not there before. This new option is a Relationship drop down. I changed this from 'do not use a relationship' to 'field_selected_job_roles'.
The 'auto preview' at the bottom of the page did not return any results when I added an appropriate contextual filter. However going to my test page everything was working correctly!
I would appreciate it if anyone can provide an explanation on why this works. However in the mean time I am just happy to have resolved the issue.
Answer: First you have to do this step by step.
You limit your view to the page being viewed. Set up a view of content and a contextual filter on Content:Nid to Provide default value:Content ID from URL.
Then relate the view to the Taxomony terms. Create a relationship on Taxonomy Term:field_job_roles and make it required.
Now relate the terms to the users. Create a second relationship on Taxonomy term: User using Job Roles. Set it to  use the *term from field_job_roles* relationship and make it required.
This type of query tends to produce duplicates, to under Other > Query settings select Distinct.
Now select the fields you want to display. Remove the default Content: Title and add the field User: Name.
When this view is displayed on the page it will display a list of users with the Job Roles corresponding to those of the page.
Comment: Thanks Triskelion. Unfortunately I am getting stuck at the step:

"Then relate the view to the Taxomony terms..."

I cannot find Taxonomy Term:field_job_roles

When I go to add relationship and search for 'tax' the options i have are:
1. Content: Taxonomy terms on node
2. Content: Adviser Name for Taxonomy
3.Field: Staff Member Name for Taxonomy
4. User: Staff Member Name for Taxonomy.

I have been trying by selecting 'Content: Taxonomy terms on node' and selected it and then choose 'Selected Job Roles', identifier 'term', but this returns the fields for the page currently being viewed.
Comment: If you have added the job_roles (or whatever name you use) term reference field to the content type, when you go to add the relationship, there should be a filter item on the list called 'Taxonomy term'. Filter the list and you should find it.


Uploading picture with Angular, Express, Mongoose

Question: I'm trying to upload and store picture with Mongoose, Express and Angular. I've picked here the next solution:
.directive('fileModel', ['$parse', function ($parse) {
        return {
           restrict: 'A',
           link: function(scope, element, attrs) {
              element.bind('change', function(){
              $parse(attrs.fileModel).assign(scope,element[0].files)
                 scope.$apply();
              });
           }
        };
     }])

And the next function in controller:
$scope.uploadFile=function(){
   var fd = new FormData();
   angular.forEach($scope.files,function(file){
               fd.append('file',file);
           });

           $http.post('http://' + host + ':3000/users/' + $scope.selectedTask._id,fd,
              {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
              }).success(function(d){
                  console.log('yes');
              })
            }

And html:
 <input type = "file" file-model="files" multiple/>
 <button ng-click = "uploadFile()">upload me</button>

{{file.name}}

But for some reason all I'm getting in my endpoint is an empty request object. I'm checking it with the following code in express.js:
user.route('/users/:id')
.post(function (req, res, next) {
    console.log(req.body);
})

I think the problem is that I don't know how to store something that is larger then 16MB.
Comment: why don't you use multer a node package which helps you store any kind of file . If you want I can show you  how to use it.
Comment: @sacDahal It's a first time I hear about it, I'm new with node. I'll be glad if you show me how I can upload picture. But I want to store it in mongodb because I have a userbase there and I want to store pictures together with other user's data.
Answer: In this example you will see how to store the file you are sending in to your server directory and then pick them up from there and save them. You can also directly save them.
First you pick up the file using angular, if you want you can
check here for more details.
Here is my small example the code is in jade.
input(type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)")
button(ng-click='savePhoto()') Save

In your angular controller
 $scope.savePhoto = function () {
 var fd = new FormData();
  fd.append("file", $scope.files[0]);
  )) ;
$http.post("/xxx/photos", fd, {
        withCredentials: true,
        headers: { 'Content-Type': undefined },
        transformRequest: angular.identity
      }).success(function (data) {
        $scope.image = data; // If you want to render the image after successfully uploading in your db
      });
    };

Install multer  using npm in your back end. And then in app.js you can set up a middleware to collect the files you are sending in. Just do console.log(req) here to check if you are getting the files till here. Multer does the magic here.
  app.use(multer({
  dest: path.join(__dirname, 'public/assets/img/profile'),
  rename: function (fieldname, filename, req, res) {
      console.log(req)// you will see your image url etc.
    if(req.session.user) return req.session.user.id;
  }
}));

So here the image will be stored in this path (public/assets/img/profile) in your server.
Now you pick up the file from this server and add to your db.
var path = require('path');
  var imgPath =path.join(__dirname, '../public/assets/img/profile/' + id + '.jpg'); // this is the path to your server where multer already has stored your image
      console.log(imgPath);
      var a ;

      a = fs.readFileSync(imgPath);
      YourSchema.findByIdAndUpdate( id, {
            $set:
            {'img.data' : a,
              'img.contentType' : 'image/png' }
          }, function(err, doc) {
            if (err)console.log("oi");

          }
      );

   //In case you want to send back the stored image from the db.
      yourSchema.findById(id, function (err, doc) {
        if (err)console.log(err);

        var base64 = doc.img.data.toString('base64');
        res.send('data:'+doc.img.contentType+';base64,' + base64);

      });

In your schema store the image in type Buffer
img: { data: Buffer}

Comment: Thanks for answer. I'm trying to make it work right now, hower I have some difficulties. Since I don't have jade file I just added this:

Save
to my view. However, I'm getting error: Uncaught TypeError: angular.element(...).scope(...).selectFile is not a function
Comment: You can use html , you don't need jade I was to lazy to type so I copied the existing jade file. ITs just
Comment: Sorry, I'm a bit dump. I'm getting this error now:(index):48 Uncaught SyntaxError: missing ) after argument list Don't know where it's from
Comment: fd.append("file", $scope.files[0]);
  )) ;// remove the )) I guess in angular controller
Comment: try to console.log and see where exactly its breaking.
Comment: The problem is in html, because function `savePhoto` isn't called, and browser highlights the very end of input string,
Comment: In your example console says `angular.element(...).scope(...).selectFile is not a function` and when i put it in my code i get this one too


How to get a form to submit:

Question: a possibly stupid question. Why won't this form submit?
$form['foo'] = array(
    '#type' => 'textfield',
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
);

if I add the following
$form['#submit'][] = 'my_form_submit';

and a submit function:
function my_form_submit($form, &$form_state){
  dd('Submit ran');
}

The debug statement is never called. What am I doing wrong?
Comment: I assume there is not a my_form_validate function that is not passing?
Answer: Actually the submit handler name should be the form function name with _submit.
So in this case: my_form() returns the form, and my_form_submit($form, &$form_state) is automatically the submit handler. This also works for _validate.
See the Examples project for some working code. It has a submodule called form_example.
Answer: I think the standard way to do it is to put it in an 'actions' container and then add the '#submit' to that. try this snippet instead of your code above.
$form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 5,
    '#submit' => array('my_form_submit'),
  );

notice how the button gets the #submit... not the form. Forms do have a default submit handler, which I think is myformname_submit but I always do it explicitly anyway. Also, I've seen DD fail on occasion due to random permissions problems. Maybe try DPM, watchdog, KPM or something that writes to the screen rather than a  log file.
Comment: Hmm.. I changed the form to this. http://pastebin.com/hR2L3dX2
It still doesn't submit..
:/
Comment: Adding the submit button to the actions container doesn't influence if the #submit is called or not. Also be aware that adding the submit handler to the button alters the functionality (in case more submit buttons are added later on)
Comment: Right, so in the case of multiple buttons this puts the submit handlers with the buttons. I like to do it that way so I can easily see each button's submit. @starsinmypockets there's no reason that shouldn't run, your code looks fine to me. Can you try using `dpm($form)` in your handler? Is there any other code you're not showing us? Maybe there is more to $form we're not seeing? Sometimes accidentally override stuff in PHP arrays.
Answer: The code you have pasted looks fine, so why doesn't it work? It's hard to say exactly, but some possibilities are:

The submit handler is called but you are tracking the wrong file or there is an error with the dd function.
The form is not loaded on the page that is rendered on display.
The submit handler is in a include file not loaded when the form is processed.
Typos in the actual code (mis name of function names).

This is some guesses, like I said what you have looks fine. One comment though. You don't have to add the submit handler if you name it FORM_NAME_submit, Drupal will by default add those to the functions called on submit.
Answer: The problem here isn't the array, but the way that I invoke the form. I just needed to call my form callback using drupal_get_form('my_form_callback'); Thanks to all for the help!
Comment: also please see http://drupal.stackexchange.com/questions/19353
Answer: I had a lot of issues getting this working. I tried all suggestions in here, including swapping from drupal_build_form to drupal_get_form, using $form['submit']['#submit'] vs $form['#submit'], and even just using a link that linked to current_path() as a #markup element. All of these attempts failed.
What did work was the following:
  $reset_button_text = t('Reset filters');
  // Before building the form check the query parameters for the reset op and use a goto to stop the form and "reset" it.
  $query_params = drupal_get_query_parameters();
  if (isset($query_params['op']) && $query_params['op'] == $reset_button_text) {
    drupal_goto(current_path());
  }

  // Form declaration goes here..
  // ....
  // ....
  $form['#method'] = 'get';
  // Reset button just resets the filters.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['reset'] =  array('#type' => 'submit', '#value' => $reset_button_text);
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Apply filters'));

This seems like a massive hack and only works because I have the form as a sort of filter form for a custom EntityFieldQuery (which outputs some other markup) on the same page. However, it works a charm for me :)

How to get a form to submit:


Cannot debug Service Fabric

Question: I have a statesless Service Fabric service
I am deploying it within my application into a  1 node dev cluster
None of my breakpoints ever get hit
I have rebuilt, restarted, updated visual studio and I am now really out of ideas
Has anyone ever seen this?
The strange thing is that my breakpoints stay active
I know my logic is being executed as messages are shown in the console
Paul
Comment: does this answer help? https://stackoverflow.com/a/42118286/5946937
Comment: Yep thanks seems to work ok now
Answer: Linking the answer in the comments
https://stackoverflow.com/a/42118286/5946937

Close all Visual Studio windows.
Restart the Service Fabric service: Type services.msc in the windows run tool. Find Microsoft Service Fabric Host Service. Right Click + Restart.
Reset the local cluster: Look at the Service Fabric Local Cluster Manager Icon in the notification area in the right side of the task bar. Right Click + Reset Local Cluster.
Open the problematic solution in Visual Studio.
Clean and Rebuild solution.
Finally run your solution (press F5).
Answer: There is one other thing that I noticed. After pressing an F5, on the process tab, keep an eye on the process id (this is just a sample reference, not from a service fabric process), in my case, there were no processes attached at all. In such a case, go to Debug -> Attach to Process -> Choose the process you need to debug.

One thing to keep in mind is that sometimes you may have to select the show process from all users checkbox because visual studio may be running in admin  mode but the application process maybe running in normal user mode.

You can also understand that the right process has not been attached when you see something like this  in front of the breakpoint. This is also an indication that the right process has not been attached. If the right process has been attached, the debugging should be successful!

Cannot debug Service Fabric


Função jquery não funciona

Question: CSS:
.nav {
    width: 15%;
    height: 800px;
    background-color: #421;
    margin-top: 55px;
    float: left;
}
.nav-min {
    width: 5% !important;
    background-color: #ccc !important;
}

JS:

HTML:

    <button class="btn btn-menu" id="btn">Menu</button>

Aqui tem testes que fiz e funcionaram
http://jsfiddle.net/ukpm1uey/3/
porém não rodou no localhost, alguém sabe o que pode ser?, já verifiquei se esta salvando, mas mesmo assim não funciona de maneira alguma
Comment: No jsFiddle ele está funcionando! Qual é o seu objetivo ou que está tentando fazer para dizer que ele não está a funcionar?
Comment: Matheus, ainda esta muito difícil de entender qual e o seu problema, você poderia editar a sua pergunta adicionando mais informações? Quando tiver um tempo da uma lida aqui -> http://pt.stackoverflow.com/help/mcve
Comment: Então, eu queria fazer um menu que diminui ao clicar no botão, mas no meu código não esta funcionando :/, eu que montei o código do jsFiddle porém ele não funciona no meu código sendo que ele está praticamente limpo
Comment: tem certeza que vc colocou um tag link com o css inicial lá ? no jsfiddle, é só por na janela, mas no localhost precisa de um tag incluindo o css
Answer: No localhost deve ter colocado na mesma ordem que fez a pergunta.
Isso quer dizer.:

Está primeiro do que.:

   <button class="btn btn-menu" id="btn">Menu</button>

Por isso não está a funcionar.
2 maneiras de ultrapassar

Colocar o script no fim da pasta
Alterar para.:

Comment: Muito obrigado a todos que ajudaram, deu certo :P

Função jquery não funciona


Modifying page title with THEME_preprocess_page_title

Question: I'm running Drupal 8.2.6, and an Adaptive subtheme and I am trying to modify the page title. I have created the following function in THEME.theme
function THEME_preprocess_page_title(&$variables) {
  $color_title = str_ireplace('some text', 'Some TEXT', $variables['title']);
  $variables['title'] = $color_title;
}

unfortunately, it's not working, at all. I've even tried just
$variables['title'] = 'Hello World';

to see if it would work, but no dice.
EDIT
So the hunt goes on!
Apparently AdaptiveTheme doesn't use the page title block, it writes it into node.html.twig via field--node--title.html.twig
so far, I have edited THEME_preprocess_field__node__title(&$variables) with no luck, but THEME_preprocess_node() seems to work. kind of. if i do
$variables['title'] = 'hello world';

it works, but it still won't let me put the span tags in. I have found the reason for that, titles aren't allowed to have code because of XSS threats.
OK. Fine. Fair enough.
There is options in the code to allow you to to allow certain tags (i found documentation, then i lost it ... argghh)
I will keep this question updated as I go
Answer: I think you are looking in wrong place. As far as i remember, in Drupal 8 title is rendered trough block called page_title_block
function MODULE_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'page_title_block') {
    $color_title = str_ireplace('some text', 'Some TEXT', $variables['content']['#title']);
    $variables['content']['#title'] = $color_title;
  }
}

Answer: Not sure it is still relevant after more than 2 years of inactivity, but I just wanted to point out that your approach isn't working most likely because the title is not a string but a Markup object which can't be modified.
You need to create a new one and then assign it to the title variable.
Your function should be something like this:
function THEME_preprocess_page_title(&$variables) {
  $color_title = str_ireplace('some text', 'Some TEXT', $variables['title']);
  $variables['title'] = Drupal\Core\Render\Markup::create($color_title);
}

Further reading here.


What's the difference between superscripts and subscripts on fields?

Question: $P_2$ vs $\mathbb{R}^3$
$P_2$ represents the set of polynomials equal to or less than degree 2.
$\mathbb{R}^3$ represents (I think) a vector with 3 elements.
Is there any difference if the number is placed as superscript or subscription?
Comment: Good thing that they are written differently because $P_2$ has dimension *3*.
Comment: By the way, neither of those objects are fields themselves. They can be constructed from fields but they are only vector spaces over the fields.
Comment: @lhf and R3 has dim of 3, right?
Comment: @macdonjo, yes.
Answer: These are notational conventions. Sometimes they are compatible, sometimes not.
If $F$ is a field, $F^k$ denotes the vector space of $k$-tuples of elements of $F$.  Such is the case with $\mathbb{R}^3$.  Since this set also the $k$-fold Cartesian product of $F$ with itself, the superscript notation agrees with that for powers.
Other times a construction will depend on a number like degree, and it's typical to put that in the subscript.
A good author will define his or her notation at the outset, as in, "Let $P_2$ be the vector space of polynomials of degree $\leq 2$ over $\mathbb{R}$." Then there is no ambiguity.


Variational Inference: Ising Model

Question: I am self learning Variational Inference. Currently I am reading the chapter 21 book from Murphy 1 and trying to understand the Ising model (21.3.2).
The Ising model here is used as denoising technique to turn a gray valued image into a binary image.
The model is described as follows: assuming a latent variable $x_i \in \{-1, +1\}$, the joint model form is $p(\textbf{x}, \textbf{y}) = p(\textbf{x})p(\textbf{y}|\textbf{x})$, where $\textbf{y}$ denotes the gray values of the image and $\textbf{x}$ denotes the binary values of the corresponding pixels. The prior is
$$p(\textbf{x}) \propto \exp(E_0(\textbf{x})),$$
$$E_0(\textbf{x}) = -\sum_{i=1}^{D}\sum_{j\in Nb(i)}W_{i,j}x_ix_j,$$
where $W$ is a weighting matrix (usually positive), and $Nb(i)$ denotes the first-degree hidden neighbors of pixel $i$.
Then, the author goes on and defines the likelihood as
$$p(\textbf{y}|\textbf{x}) = \prod_{i}p(y_i|x_i) = \exp(\sum_{i}-L_i(x_i)).$$
Finally, the posterior is presented as
$$p(\textbf{x}|\textbf{y}) \propto \exp(-E(\textbf{x})),$$
$$E(\textbf{x}) = E_0(\textbf{x}) - \sum_{i}L(x_i).$$
I do not follow what $L(\cdot)$ here represents, how the author arrived to the likelihood in that form, and how the posterior is determined since it should be intractable.
Answer:
I do not follow what $L(\cdot)$ here represents

$L_i$ represents the log-likelihood of observing grayscale value $y_i$ if the binary value is $x_i$:
$$L_i(x_i) = \log p(y_i|x_i)$$
You can easily verify that taking exponential of sum of log-likelihoods equals taking product of likelihoods.

How the posterior is determined since it should be intractable

There is nothing intractable about writing down the posterior formula. Computing the posterior is intractable: you cannot compute it without evaluating all the possible values of $\mathbf{x}$, which are needed to compute the normalizer $Z$ in (21.40). That is why we need to use the approximate variational inference.

This IPython notebook might also provide you more insight.
Comment: Thanks for your answer. I did a mistake in copying the likelihood, the sum goes over the exponent and not as I put it before. I have corrected it.
Comment: @mgbacher No, the sum is **inside** the exponential (check (21.39) in the book). I corrected that for you in the question text, but I see you reverted it again...
Comment: @mgbacher Product is converted to sum of powers $\exp(a+b)=\exp(a) \exp (b)$.
Comment: No problem. Just for the reference, I corrected the equation in the question text once again.
Answer: The notation for this section is pretty bad. The $L(.)$ is first used to refer to the objective function to be maximized (ELBO). Then, as the accepted answer states, it is all of a sudden used for the log-likelihood.
It also doesn't help that the formula in the book (at least in my version, and it seems the original poster's as well) is incorrect and has the equation as:
$$
p(\textbf{y}|\textbf{x}) = \prod_{i}p(y_i|x_i) = \sum_{i}\exp(-L_i(x_i)).
$$

Variational Inference: Ising Model


Graphql Subscriptions field must return Async Iterable. Received: { pubsub

Question: I'm trying go use subscriptions in graphql, but I'm receiving this weird error:
subscription {
  notification {
    type
     message
  }
}

I'm using import { PubSub } from "graphql-subscriptions";
import { Inject } from "@nestjs/common";
import { Resolver, Subscription } from "@nestjs/graphql";
import { PubSub } from "graphql-subscriptions";
import { Notification } from "./models/notification";

@Resolver(() => Notification)
export class NotificationResolver {
  constructor(@Inject('PUB_SUB') private pubSub: PubSub) {}

  @Subscription(() => Notification, {
    resolve: (payload) => payload?.notification || {}
  })
  notification() {
    return this.pubSub.asyncIterator('notification');
  }
}

Error:
{ "error": { "message": "Subscription field must return Async Iterable. Received: { pubsub: { ee: [Object], subscriptions: {}, subIdCounter: 0 }, pullQueue: [], pushQueue: [], running: true, allSubscribed: null, eventsArray: [\"notification\"] }." } }
I tryied to use, but the error was the same:
subscriptions: {
    'graphql-ws': true
  },

Answer: For people who are still experiencing this problem. My problem was caused by the global interceptor:  ClassSerializerInterceptor.
When you disable that in main.ts:
// app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));


EHX Mainframe - dynamic hi/low pass

Question: I'm seeking to confirm whether it's possible to have granular control of when I engage the hi/low pass filters on the EHX mainframe "bit crusher" guitar pedal. I've digested about 5 youtube videos on the product but there are so many features/knobs/dials on this pedal that it's not practical to cover everything. None of them seem to touch on the exact use case I have in mind.

It seems that the filter settings are controlled via switch, so that leads me to believe that expression pedal control of the hi/low filter isn't possible. Maybe I could try to use a volume pedal before the mainframe with my desired filter and bit depth dialed in, then maybe I'd have the granular control I'm after.
Question
Can anyone with some hands-on experience with this product recommend or comment on a practical signal path / gear configuration if I want to have control over when I engage the hi/low filter?
If it helps, the items I have:

Boss volume pedal
2 expression pedals
Comment: @piiperiReinstateMonica I think it's actually a matter of taste and good usage of it...
Comment: Can you add a link to the manufacturer's page or manual?
Comment: What genre is this for? I think bit crusher is one of the most awful sounds.
Comment: @piiperiReinstateMonica currently trying some guitar dub-step sounds, but also wanted to try some futuristic sounding riffs. Not sure if you've ever played the 90s space fighter game descent 2, but that OST has some awesome riffs that have a tone thats part distortion part robot
Answer: Yes, this appears to be definitely possible. Not only does the product page advertize than any knob can be mapped from the expression pedal, the tips&tricks section also explicitly mentions this use case:

BPF – This is the previous two filters combined, providing some
of the benefits of each. This can also be used for a wah-like sound
when using an expression pedal, or a cocked-wah sound without
an expression pedal.
Comment: The knobs can be mapped to an expression pedal, but the hi/low filter is just a flip switch (not a knob), which would be different, as I read it
Comment: No, the filter (-cutoff) is a potentiometer like everything else. Of course, there's a flip switch that selects _what kind of filter_ this is. There's no such thing as continuously switching between different kinds of filter (other than _mixing_ between them, which would cause phase problems). But tweaking the cutoff of a bandpass filter is essentially equivalent to morphing it between a lowpass- and highpass filter.

EHX Mainframe - dynamic hi/low pass


Shorthand name for Ab6(no3)/Eb?

Question: I'm an amateur songwriter with limited music theory knowledge. I have this chord progression in Eb:
Cm - Ab/C - Eb - Ab6(no3)/Eb Ddim
Played on a keyboard, the Ab6(no3)/Eb (Eb,F,Ab) transitions nicely to Ddim (D,F,Ab) (similar to the transition from Cm to Ab/C).
But Ab6(no3)/Eb is so ugly to write that way. This isn't the first time I've encountered this shape while writing--is there a standard shorthand or better way to write it? Or should I just make up my own shorthand?
Comment: Chord symbols are a shorthand and intentionally inexact. To specify an exact voicing of specific notes, use standard notation.
Answer: I would call it Fm7/Eb. The missing C note, the perfect fifth, is actually commonly omitted in 7th and more extended chords.
Answer: The chord progression you've written suggests that the E-flat is a suspension in the bass. That is to say, the "real" chord is the D diminished chord (which implies an incomplete Bb7 chord, if we're going back to E-flat, or perhaps a B-diminished 7th chord, if we're going on to C minor) and the E-flat in the bass is a dissonance that is held over from the previous chord and then resolves to the D. What you've written is actually very similar to a super common introductory chord sequence in the Baroque and Classical periods!
Chord symbols of the sort you're using are not that well suited to notating suspensions, especially suspensions in the bass. (Classical musicians have a whole different notation system for this sort of thing, figured bass.[^1])
Fm7/Eb, as suggested by another user, is possible. You could also consider Bb7sus4/Eb. The difference is basically whether there is a C in the chord, or instead a Bb. (You can listen and compare for yourself which sounds closer to what you have in mind. You might also find that you like the sound of Bb7/D better than D diminished, or not.) You could even consider something like writing Ddim, then add a verbal note something like: bass: Eb->D susp..
[^1]: In figured bass, you would write an E-flat in staff notation, then put a 4/2 underneath it to indicate that the fourth and second should be played. However, the 4/2 figure is usually taken to imply the 6th (C) as well.
Comment: Interesting analysis! Perhaps it explains the voice motion better... although in Fm7, the 7th, Eb, has also some tendency to resolve downwards, so perhaps what I proposed is not _that_ bad? e.g. an improviser would understand what's going on?
Comment: Absolutely, what you proposed works too. 7ths work a lot like suspensions (dissonances that typically resolve downwards) and historically evolved out of them. So it's really like two different ways of looking at the same thing.
Comment: Thanks for the detailed answer! I went with `Fm7/Eb` mainly for the simplicity. I actually do think the added Bb sounds better (for my song) than the added C, but in either case I feel like it's sort of a flavor note that isn't necessarily essential to the song.
Answer: Another possibility, in addition to the other answers, is Ebsus2,4. This also implies a Bb, but it might get you close enough to what you need. It also makes Eb the root, which may or may not communicate better what you're thinking here.
Technically, the F and Ab aren't really suspensions, since it's the Eb that resolves downward, but in common pop/jazz notation, that detail is usually ignored.

Shorthand name for Ab6(no3)/Eb?


ORA-01031: insufficient privileges even though it has been granted the rights

Question: I have a user named BT_MASTER when connected to SYSTEM, and granted BT_MASTER the role MAIN_ADMIN_ROLE:
select * from dba_role_privs where grantee = 'BT_MASTER';

GRANTEE
GRANTED_ROLE
ADMIN_OPTION
DELEGATE_OPTION
DEFAULT_ROLE
COMMON
INHERITED

BT_MASTER
MAIN_ADMIN_ROLE
NO
NO
YES
NO
NO

This role, again using SYSTEM to GRANT, has the privilege to CREATE USER:
select * from role_sys_privs

ROLE
PRIVILEGE
ADMIN_OPTION
COMMON
INHERITED

MAIN_ADMIN_ROLE
CREATE USER
NO
NO
NO

However, when trying something simple like this, connected to the DB as BT_MASTER:
CREATE USER new_user_example;
I get this error:

Error starting at line : 1 in command -
CREATE USER new_user_example
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
the necessary privileges.
*Action:   Ask your database administrator or designated security
administrator to grant you the necessary privileges

I am using Oracle XE 18c, the slim version (gvenzl/oracle-xe:18-slim)
Does anyone know if this is a limitation of this version, or if I am doing something incorrect?
Comment: Is the role activated by default for the user, or do you need to turn it on explicitly with `SET ROLE MAIN_ADMIN_ROLE;` in your session?
Comment: I use SYSTEM to grant the role to BT_MASTER. Then, connecting as TB_MASTER, try and execute. create role.
Comment: Are you running the CREATE USER command inside a stored procedure by any chance?
Comment: I have also tried SET ROLE MAIN_ADMIN_ROLE, but no difference, still get the error
Comment: No, not inside a stored procedure. Just as is.
Comment: Try running `select * from user_role_privs` as BT_MASTER to make sure you have the role. And [see this similar question](https://stackoverflow.com/questions/43301204/oracle-ora-01031-insufficient-privileges-while-creating-user) - your role and grant aren't `common`, so they only apply to the container that they were granted from.
Comment: I have ran that query when connected as BT_MASTER,  it tells me something similar to role_sys_privs, that MAIN_ADMIN_ROLE has been granted. I have tried to run GRANT CREATE ROLE to TB_MASTER container=all; using SYSTEM user, and the grant was successful, but still the same error when trying to create a user with BT_MASTER
Answer: I'm on 21XE, but that shouldn't matter:
SQL> select banner from v$version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 21c Express Edition Release 184.108.40.206.0 - Production

SQL>

It usually helps if you post everything you did, step-by-step - then we can replicate it and (hopefully) spot the error. As you didn't do it, I tried to simulate the process. Have a look.
Connected as SYS, I'll create the bt_master user and a role (and grant appropriate privileges):
SQL> connect sys/pwd@pdb1 as sysdba
    Connected.
SQL> create user bt_master identified by bt_master
  2  default tablespace users
  3  temporary tablespace temp
  4  quota unlimited on users;

User created.

SQL> grant create session to bt_master;

Grant succeeded.

SQL> create role main_admin_role;

Role created.

SQL> grant create user to main_admin_role;

Grant succeeded.

SQL> grant main_admin_role to bt_master;

Grant succeeded.

It's all set; now, connect as bt_master and try to create a new user:
SQL> connect bt_master/bt_master@pdb1
Connected.
SQL> create user bt_test identified by bt_test;

User created.

SQL>

As you can see, everything went just fine. Can you find the error in your steps? If not, do as instructed - post the whole process, just like I did.
Comment: I did the following connected as SYSTEM:

`create user bt_master identified by bt_master
default tablespace users
temporary tablespace temp
quota unlimited on users;

grant create session to bt_master;

create role main_admin_role;`

`grant create user to main_admin_role;`

`grant main_admin_role to bt_master;`

And then connected as bt_master, and still get the ORA-01031: insufficient privileges error.
Comment: Just to add, I use SQLDeveloper, and have tried the same as you when connecting as SYS, changing the role to SYSDBA, and executing what you have. I get the same result, ORA-01031: insufficient privileges. Could this be a lite issue?
Answer: I managed to get around this issue by connecting as SYSTEM and doing the following:
grant DBA to BT_MASTER with admin option;


Do CDN providers run their own DNS servers?

Question: In order to have efficient CDN, it needs to direct requests to the server nearest to the requester.
How do they do that? Do they run their own DNS server that, when asked to resolve an address, it the geo lookup of the requester IP and returns the proper server IP? Does DNS caching affect that (sounds like it shouldn't, and my ISP's cache is going to cache the nearest server and then serve it to me)
Answer: There are two basic mechanisms to route requests to topologically proximate servers:

Split-view DNS… like you said.
Anycast routing: BGP is used to tell an ISP's router to route traffic for an IP address to an optimally located host.

Of the two techniques, split-view DNS is simpler to implement.  However, anycast routing has the advantage that it works even if the client is using a DNS server other than the ISP's.
Answer: Yes, that's exactly how most CDNs work.  In addition, many have servers that are co-located in ISPs' datacenters for direct access.


Trying to do an assignment but stuck at ORA-00906: missing left parenthesis

Question: Im doing a course on DB, this is one of the first assignments, I'm about to be done, but there is an issue somewhere in my REL_CURSOS_ALUMNOS query which ends up with the ORA-00906 error.
REL_CURSOS_ALUMNOS is a relationship table for "one to many"  1 ' CURSOS(Id_Curso) to many ALUMNOS(NIF_Alumno).
This is my query till now:
CREATE TABLE PROFESORES(
  NIF_Profesor VARCHAR2(15) CONSTRAINT Prof_NIF_PK PRIMARY KEY,
  Nombre VARCHAR2(30),
  Apellido1 VARCHAR2(30),
  Apellido2 VARCHAR2(30),
  Direccion VARCHAR2(4000),
  Titulacion VARCHAR2(500),
  Salario FLOAT(10) CONSTRAINT Prof_sal_NN NOT NULL
);

CREATE TABLE ALUMNOS(
    NIF_Alumno VARCHAR2(15) CONSTRAINT Alum_NIF_PK PRIMARY KEY,
    Nombre VARCHAR2(30),
    Apellido1 VARCHAR2(30),
    Apellido2 VARCHAR2(30),
    Direccion VARCHAR2(4000),
    Sexo CHAR(1),
    Fecha_Nacimiento DATE
    );

CREATE TABLE CURSOS (
    Id_Curso VARCHAR2(15) CONSTRAINT Curs_Id_PK PRIMARY KEY,
    Nombre VARCHAR2(400) UNIQUE,
    NIF_Profesor VARCHAR2(15) REFERENCES PROFESORES (NIF_Profesor),
    Max_Alumnos NUMBER(5),
    Inicio_Fecha DATE,
    Final_Fecha DATE,
    Num_Horas NUMBER(10) NOT NULL,
    CONSTRAINT Curs_FechasIncorrectas CHECK (Final_Fecha > Inicio_Fecha));

CREATE TABLE REL_CURSOS_ALUMNOS (
  Id_Curso VARCHAR2(15) REFERENCES CURSOS(Id_Cursos),
  NIF_Alumno VARCHAR2(15) REFERENCES ALUMNOS(NIF_Alumno) CONSTRAINT RCA_NIFAlum_UQ UNIQUE,
UNIQUE KEY (Id_Curso, NIF_Alumno));

Thank you.
Answer: You have a couple of small errors in the final table definition:
CREATE TABLE REL_CURSOS_ALUMNOS (
  Id_Curso VARCHAR2(15) REFERENCES CURSOS(Id_Curso),
  NIF_Alumno VARCHAR2(15) REFERENCES ALUMNOS(NIF_Alumno) CONSTRAINT RCA_NIFAlum_UQ UNIQUE,
  UNIQUE (Id_Curso, NIF_Alumno)
);

Your specific problem is caused by KEY.  That is not needed for a unique constraint definition.  Further, the reference for CURSOS is id_curso, not id_cursos.
I left both unique definitions.  But if NIF_Alumno is unique, then the pair (Id_Curso, NIF_Alumno) is also unique, so that constraint is redundant.


Compare numeric values two arrays

Question: i hace this issue whit two arrays
one array is given by a json like this
array1( [0] => 6, [1] => 1)

and making a query i got this other
array2( [0] => 1, [1] => 1)

I want to compare both arrays and use "if" when numeric values of array1 are less than or equal to array2. Is that possible? like this?
if($array1 <= $array2){do something}

Grettings!
Comment: What if one array has key 0 <= other but key 1 is > other?
Comment: What if they are [1,4] and [2,3] ? Which one should be greater? Is the number of elements in arrays always the same?
Comment: maybe this will be ok for you `if(array_sum($array1) <= array_sum($array2)) { ... `
Comment: I suppose that you are trying to compare the sum, if not, can you explain it better?
Comment: If you don't compare sums like these other suggestions, you'll need to look through array2 and find if any of them are greater than the values in array1 (do they correspond or do you check all values in array1?)
Comment: the json sends me something like this 'Array([0] => Array([sku] => 014633368987 [quantity] => 5) [1] => Array ([sku] => 885370145717 [quantity] => 1))' the i sorted and extract the quantity and sku values to new arrays the sku values is what i use to do the query and give the array like first but with quantity values on my db
Answer: This really depends on what your expected behaviour is, and also the expectations of your two arrays.  For the sake of these examples, I'm going to assume that each array is guaranteed to be the same size and you are compairing paired elements (elements from each array at the same index).

If you want to exit the first time a number from array1 is less than its paired element from array2:
for ($i = 0; $i < sizeof($array1); $i++) {
    if ($array1[$i] <= $array2[$i]) {
        ...do something
    }
}

If you want to do something if all values of array1 are less than their paired elements from array2:
// Keep track of a flag so we know if we meet our condition once done
$allValuesLessThan = true;

// Check each individual array1 element and its 'paired element' from array2
for ($i = 0; $i < sizeof($array1); $i++) {
    // If we break our condition, set our flag and break out of our loop, since we no longer need to check subsequent elements
    if ($array1[$i] > $array2[$i]) {
        $allValuesLessThan = false;
        break;
    }
}

// Finally, only do our 'something' if our condition was met
if ($allValuesLessThan) {
    ...do something
}

Comment: Thanks a lot thats exactly what i want to do!

Compare numeric values two arrays


Assessing spatial autocorrelation in structural equation models

Question: I have a SEM built with lavaan and I would like to assess spatial autocorrelation. I found this code written by Jarrett Byrnes that does exactly that:
http://www.imachordata.com/space-and-sems-2/
However in this page there is warning that as of 2016/10/1 lavaan is not producing correct errors. I browsed lavaan's development page and it seems the bug has not been fixed. Jarrett Byrnes recommends that users calculate the errors by hand.
Does anyone know of an alternative way of assessing spatial autocorrelation? Alternatively, how can I calculate the errors by hand?
Thanks
Comment: This is not a bug, according to the lavaan github page.
Answer: Here's a possible workaround that might work for some datasets:
https://groups.google.com/forum/#!topic/lavaan/ftvD1Nxb4Iw