text:
Q: npx create-react-app my-app command gives an error I want to start my react app so I write this command:
npx create-react-app my-app

but it gives this type of error...
npm ERR! Unexpected end of JSON input while parsing near '...sion":"6.1.0","depend'
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Dobriya\AppData\Roaming\npm-cache\_logs\2020-04-27T13_19_55_877Z-debug.log
Install for [ 'create-react-app@latest' ] failed with code 1

my versions:
node: 12.16.2
npm: 6.14.4

Here is that log file :
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   'create-react-app@latest',
1 verbose cli   '--global',
1 verbose cli   '--prefix',
1 verbose cli   'C:\\Users\\Dobriya\\AppData\\Roaming\\npm-cache\\_npx\\17096',
1 verbose cli   '--loglevel',
1 verbose cli   'error',
1 verbose cli   '--json'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v12.16.2
4 verbose npm-session 1196e2875ad9fe18
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 200 https://registry.npmjs.org/create-react-app 13280ms
8 http fetch GET 200 https://registry.npmjs.org/create-react-app/-/create-react-app-3.4.1.tgz 1448ms
9 silly pacote tag manifest for create-react-app@latest fetched in 14785ms
10 timing stage:loadCurrentTree Completed in 14810ms
11 silly install loadIdealTree
12 silly install cloneCurrentTreeToIdealTree
13 timing stage:loadIdealTree:cloneCurrentTree Completed in 1ms
14 silly install loadShrinkwrap
15 timing stage:loadIdealTree:loadShrinkwrap Completed in 4ms
16 silly install loadAllDepsIntoIdealTree
17 silly resolveWithNewModule create-react-app@3.4.1 checking installable status
18 http fetch GET 200 https://registry.npmjs.org/chalk 276ms
19 http fetch GET 200 https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz 93ms
20 silly pacote version manifest for chalk@3.0.0 fetched in 397ms
21 silly resolveWithNewModule chalk@3.0.0 checking installable status
22 http fetch GET 200 https://registry.npmjs.org/commander 459ms
23 http fetch GET 200 https://registry.npmjs.org/hyperquest 516ms
24 http fetch GET 200 https://registry.npmjs.org/semver 514ms
25 http fetch GET 200 https://registry.npmjs.org/fs-extra 525ms
26 http fetch GET 200 https://registry.npmjs.org/tar-pack 515ms
27 http fetch GET 200 https://registry.npmjs.org/tmp 515ms
28 http fetch GET 200 https://registry.npmjs.org/envinfo 531ms
29 http fetch GET 200 https://registry.npmjs.org/validate-npm-package-name 208ms
30 http fetch GET 200 https://registry.npmjs.org/cross-spawn 700ms
31 http fetch GET 200 https://registry.npmjs.org/inquirer 689ms
32 http fetch GET 200 https://registry.npmjs.org/commander/-/commander-4.1.0.tgz 365ms
33 http fetch GET 200 https://registry.npmjs.org/hyperquest/-/hyperquest-2.1.3.tgz 293ms
34 http fetch GET 200 https://registry.npmjs.org/tmp/-/tmp-0.1.0.tgz 292ms
35 http fetch GET 200 https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz 298ms
36 http fetch GET 200 https://registry.npmjs.org/semver/-/semver-6.3.0.tgz 300ms
37 http fetch GET 200 https://registry.npmjs.org/tar-pack/-/tar-pack-3.4.1.tgz 297ms
38 silly pacote version manifest for commander@4.1.0 fetched in 848ms
39 silly resolveWithNewModule commander@4.1.0 checking installable status
40 silly pacote version manifest for hyperquest@2.1.3 fetched in 834ms
41 silly resolveWithNewModule hyperquest@2.1.3 checking installable status
42 silly pacote version manifest for tmp@0.1.0 fetched in 855ms
43 silly resolveWithNewModule tmp@0.1.0 checking installable status
44 silly pacote version manifest for fs-extra@8.1.0 fetched in 875ms
45 silly resolveWithNewModule fs-extra@8.1.0 checking installable status
46 silly pacote version manifest for semver@6.3.0 fetched in 866ms
47 silly resolveWithNewModule semver@6.3.0 checking installable status
48 silly pacote version manifest for tar-pack@3.4.1 fetched in 869ms
49 silly resolveWithNewModule tar-pack@3.4.1 checking installable status
50 http fetch GET 200 https://registry.npmjs.org/envinfo/-/envinfo-7.5.0.tgz 347ms
51 silly pacote version manifest for envinfo@7.5.0 fetched in 894ms
52 silly resolveWithNewModule envinfo@7.5.0 checking installable status
53 http fetch GET 200 https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz 573ms
54 http fetch GET 200 https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz 479ms
55 http fetch GET 200 https://registry.npmjs.org/inquirer/-/inquirer-7.0.4.tgz 476ms
56 silly pacote version manifest for validate-npm-package-name@3.0.0 fetched in 797ms
57 silly resolveWithNewModule validate-npm-package-name@3.0.0 checking installable status
58 silly pacote version manifest for cross-spawn@7.0.1 fetched in 1193ms
59 silly resolveWithNewModule cross-spawn@7.0.1 checking installable status
60 silly pacote version manifest for inquirer@7.0.4 fetched in 1181ms
61 silly resolveWithNewModule inquirer@7.0.4 checking installable status
62 http fetch GET 200 https://registry.npmjs.org/ansi-styles 462ms
63 http fetch GET 200 https://registry.npmjs.org/supports-color 467ms
64 http fetch GET 200 https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz 99ms
65 http fetch GET 200 https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz 95ms
66 silly pacote range manifest for ansi-styles@^4.1.0 fetched in 585ms
67 silly resolveWithNewModule ansi-styles@4.2.1 checking installable status
68 silly pacote range manifest for supports-color@^7.1.0 fetched in 584ms
69 silly resolveWithNewModule supports-color@7.1.0 checking installable status
70 http fetch GET 200 https://registry.npmjs.org/@types%2fcolor-name 232ms
71 http fetch GET 200 https://registry.npmjs.org/color-convert 239ms
72 http fetch GET 200 https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz 2256ms
73 http fetch GET 200 https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz 2257ms
74 silly pacote range manifest for @types/color-name@^1.1.1 fetched in 2513ms
75 silly resolveWithNewModule @types/color-name@1.1.1 checking installable status
76 silly pacote range manifest for color-convert@^2.0.1 fetched in 2519ms
77 silly resolveWithNewModule color-convert@2.0.1 checking installable status
78 http fetch GET 200 https://registry.npmjs.org/color-name 998ms
79 http fetch GET 200 https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz 2789ms
80 silly pacote range manifest for color-name@~1.1.4 fetched in 3806ms
81 silly resolveWithNewModule color-name@1.1.4 checking installable status
82 http fetch GET 200 https://registry.npmjs.org/has-flag 1350ms
83 http fetch GET 200 https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz 253ms
84 silly pacote range manifest for has-flag@^4.0.0 fetched in 1621ms
85 silly resolveWithNewModule has-flag@4.0.0 checking installable status
86 http fetch GET 200 https://registry.npmjs.org/path-key 296ms
87 http fetch GET 200 https://registry.npmjs.org/which 375ms
88 http fetch GET 200 https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz 290ms
89 silly pacote range manifest for path-key@^3.1.0 fetched in 606ms
90 silly resolveWithNewModule path-key@3.1.1 checking installable status
91 http fetch GET 200 https://registry.npmjs.org/shebang-command 1895ms
92 http fetch GET 200 https://registry.npmjs.org/which/-/which-2.0.2.tgz 1522ms
93 silly pacote range manifest for which@^2.0.1 fetched in 1916ms
94 silly resolveWithNewModule which@2.0.2 checking installable status
95 http fetch GET 200 https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz 1575ms
96 silly pacote range manifest for shebang-command@^2.0.0 fetched in 3488ms
97 silly resolveWithNewModule shebang-command@2.0.0 checking installable status
98 http fetch GET 200 https://registry.npmjs.org/shebang-regex 1831ms
99 http fetch GET 200 https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz 118ms
100 silly pacote range manifest for shebang-regex@^3.0.0 fetched in 1974ms
101 silly resolveWithNewModule shebang-regex@3.0.0 checking installable status
102 http fetch GET 200 https://registry.npmjs.org/isexe 1053ms
103 http fetch GET 200 https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz 540ms
104 silly pacote range manifest for isexe@^2.0.0 fetched in 1610ms
105 silly resolveWithNewModule isexe@2.0.0 checking installable status
106 http fetch GET 200 https://registry.npmjs.org/jsonfile 465ms
107 http fetch GET 200 https://registry.npmjs.org/universalify 789ms
108 http fetch GET 200 https://registry.npmjs.org/graceful-fs 809ms
109 http fetch GET 200 https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz 563ms
110 silly pacote range manifest for jsonfile@^4.0.0 fetched in 1046ms
111 silly resolveWithNewModule jsonfile@4.0.0 checking installable status
112 http fetch GET 200 https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz 704ms
113 http fetch GET 200 https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz 699ms
114 silly pacote range manifest for universalify@^0.1.0 fetched in 1519ms
115 silly resolveWithNewModule universalify@0.1.2 checking installable status
116 silly pacote range manifest for graceful-fs@^4.2.0 fetched in 1531ms
117 silly resolveWithNewModule graceful-fs@4.2.3 checking installable status
118 http fetch GET 200 https://registry.npmjs.org/buffer-from 2077ms
119 http fetch GET 200 https://registry.npmjs.org/through2 2518ms
120 http fetch GET 200 https://registry.npmjs.org/duplexer2 2634ms
121 http fetch GET 200 https://registry.npmjs.org/buffer-from/-/buffer-from-0.1.2.tgz 1421ms
122 silly pacote range manifest for buffer-from@^0.1.1 fetched in 3518ms
123 silly resolveWithNewModule buffer-from@0.1.2 checking installable status
124 http fetch GET 200 https://registry.npmjs.org/duplexer2/-/duplexer2-0.0.2.tgz 1272ms
125 silly pacote range manifest for duplexer2@~0.0.2 fetched in 3926ms
126 silly resolveWithNewModule duplexer2@0.0.2 checking installable status
127 http fetch GET 200 https://registry.npmjs.org/through2/-/through2-0.6.5.tgz 1737ms
128 silly pacote range manifest for through2@~0.6.3 fetched in 4279ms
129 silly resolveWithNewModule through2@0.6.5 checking installable status
130 http fetch GET 200 https://registry.npmjs.org/readable-stream 737ms
131 http fetch GET 200 https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz 1299ms
132 silly pacote range manifest for readable-stream@~1.1.9 fetched in 2062ms
133 silly resolveWithNewModule readable-stream@1.1.14 checking installable status
134 http fetch GET 200 https://registry.npmjs.org/inherits 409ms
135 http fetch GET 200 https://registry.npmjs.org/string_decoder 414ms
136 http fetch GET 200 https://registry.npmjs.org/isarray 418ms
137 http fetch GET 200 https://registry.npmjs.org/core-util-is 456ms
138 http fetch GET 200 https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz 190ms
139 http fetch GET 200 https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz 194ms
140 silly pacote range manifest for inherits@~2.0.1 fetched in 620ms
141 silly resolveWithNewModule inherits@2.0.4 checking installable status
142 silly pacote range manifest for string_decoder@~0.10.x fetched in 629ms
143 silly resolveWithNewModule string_decoder@0.10.31 checking installable status
144 http fetch GET 200 https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz 209ms
145 http fetch GET 200 https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz 181ms
146 silly pacote version manifest for isarray@0.0.1 fetched in 1875ms
147 silly resolveWithNewModule isarray@0.0.1 checking installable status
148 silly pacote range manifest for core-util-is@~1.0.0 fetched in 1882ms
149 silly resolveWithNewModule core-util-is@1.0.2 checking installable status
150 http fetch GET 200 https://registry.npmjs.org/xtend 129ms
151 http fetch GET 200 https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz 125ms
152 silly pacote range manifest for readable-stream@>=1.0.33-1 <1.1.0-0 fetched in 152ms
153 silly resolveWithNewModule readable-stream@1.0.34 checking installable status
154 http fetch GET 200 https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz 490ms
155 silly pacote range manifest for xtend@>=4.0.0 <4.1.0-0 fetched in 644ms
156 silly resolveWithNewModule xtend@4.0.2 checking installable status
157 http fetch GET 200 https://registry.npmjs.org/cli-cursor 413ms
158 http fetch GET 200 https://registry.npmjs.org/ansi-escapes 424ms
159 http fetch GET 200 https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz 1669ms
160 http fetch GET 200 https://registry.npmjs.org/figures 1692ms
161 http fetch GET 200 https://registry.npmjs.org/run-async 1691ms
162 http fetch GET 200 https://registry.npmjs.org/external-editor 1698ms
163 http fetch GET 200 https://registry.npmjs.org/cli-width 1706ms
164 http fetch GET 200 https://registry.npmjs.org/mute-stream 1704ms
165 http fetch GET 200 https://registry.npmjs.org/lodash 1712ms
166 silly pacote range manifest for chalk@^2.4.2 fetched in 1748ms
167 silly resolveWithNewModule chalk@2.4.2 checking installable status
168 http fetch GET 200 https://registry.npmjs.org/rxjs 11500ms
169 silly fetchPackageMetaData error for rxjs@^6.5.3 Unexpected end of JSON input while parsing near '...sion":"6.1.0","depend'
170 silly fetchPackageMetaData error for strip-ansi@^5.1.0 request to https://registry.npmjs.org/strip-ansi failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
171 silly fetchPackageMetaData error for through@^2.3.6 request to https://registry.npmjs.org/through failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
172 silly fetchPackageMetaData error for ansi-escapes@^4.2.1 request to https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.1.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
173 silly fetchPackageMetaData error for cli-cursor@^3.1.0 request to https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
174 silly fetchPackageMetaData error for figures@^3.0.0 request to https://registry.npmjs.org/figures/-/figures-3.2.0.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
175 silly fetchPackageMetaData error for mute-stream@0.0.8 request to https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
176 silly fetchPackageMetaData error for external-editor@^3.0.3 request to https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
177 silly fetchPackageMetaData error for run-async@^2.2.0 request to https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
178 silly fetchPackageMetaData error for cli-width@^2.0.0 request to https://registry.npmjs.org/cli-width/-/cli-width-2.2.1.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
179 silly fetchPackageMetaData error for lodash@^4.17.15 request to https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
180 silly fetchPackageMetaData error for string-width@^4.1.0 request to https://registry.npmjs.org/string-width failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
181 timing stage:rollbackFailedOptional Completed in 2ms
182 timing stage:runTopLevelLifecycles Completed in 64346ms
183 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...sion":"6.1.0","depend'
183 verbose stack     at JSON.parse (<anonymous>)
183 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)
183 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50
183 verbose stack     at runMicrotasks (<anonymous>)
183 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
184 verbose cwd E:\Files\Sem6\WT\react
185 verbose Windows_NT 10.0.18363
186 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "create-react-app@latest" "--global" "--prefix" "C:\\Users\\Dobriya\\AppData\\Roaming\\npm-cache\\_npx\\17096" "--loglevel" "error" "--json"
187 verbose node v12.16.2
188 verbose npm  v6.14.4
189 error Unexpected end of JSON input while parsing near '...sion":"6.1.0","depend'
190 verbose exit [ 1, true ]

A: If running cleaning the npm cache does not work by itself (which it didn´t do for me). Try this:

*

*Go to your npm-cache directory. On windows this is C:/Users/{your user}/AppData/Roaming/npm-cache. (When running npm cache clean --force the folder there called _cacache gets cleaned, but the _npx folder does not).

*Enter the _npx folder and delete all it´s contents. After that, go to your terminal and run npm cache clean --force again.

*Run npx create-react-app my-app again.
I haven´t found this answer anywhere else, and was stuck on this annoying issue for several weeks. This solved it for me.
I have also seen some people facing timeout issues while trying to create a new react app. I faced this as well, and solved it by going to my .npmrc (located in C:/Users/{your user}/.npmrc and adding the line timeout=240000, which can be increased even more if you have a really slow network or a vpn making life a living hell for you.

A: Try the below steps:
Clear npm cache
npm cache clean

Now create react app as below
 `npx create-react-app my-app`

Note: if still not working do npm cache clean --force and then run npx command

If you've previously installed create-react-app globally via npm
  install -g create-react-app, then you uninstall the package
  using npm uninstall -g create-react-app to ensure that npx always uses
  the latest version.
Also, npx create-react-app my-app is a command to create a react app not to start the app, to start app run npm start in the project directory

A: Please try this:
npm cache verify
This worked for me

A: I was using npm install -g create-react-app to create react app.
then create-react-app hello-react was failing with error
module not found package.json react
Cannot find module '/usr/local/lib/node_modules/create-react-app/node_modules/builtins/builtins.json'. Please verify that the package.json has a valid "main" entry...

it was always failing to create the app
node --version
v14.15.4
npm --version
6.14.10

As advised, I used the following commands which helped to resolve this issue.
npm cache clean --force
npx create-react-app hello-react

Thank you so much for sharing the details.


text:
Q: Conducting Diffie Hellman between Java and Crypto++ (C++) I want to encrypt some data between a c++ client and a java server. Searching the web I found crypto++ to use on the client and on the java side to use the KeyAgreement built in java class(btw, I already have bouncycastle jar in my project, I can use it if it's somehow better than the built in one).
I was able to perform DH on on every side with itself as an example, but due to key sizes I cannot make them to agree on a secret key.
My C++ code:
// g++ -g3 -ggdb -O0 -I. -I/usr/include/cryptopp dh-agree.cpp -o dh-agree.exe -lcryptopp -lpthread
// g++ -g -O2 -I. -I/usr/include/cryptopp dh-agree.cpp -o dh-agree.exe -lcryptopp -lpthread

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;

#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <string>
using std::string;

#include <stdexcept>
using std::runtime_error;

#include "osrng.h"
using CryptoPP::AutoSeededRandomPool;

#include "integer.h"
using CryptoPP::Integer;

#include "nbtheory.h"
using CryptoPP::ModularExponentiation;

#include "dh.h"
using CryptoPP::DH;

#include "secblock.h"
using CryptoPP::SecByteBlock;

#include <hex.h>
using CryptoPP::HexEncoder;

#include <filters.h>
using CryptoPP::StringSink;
int main(int argc, char** argv)
{
    try
    {
        // RFC 5114, 1024-bit MODP Group with 160-bit Prime Order Subgroup
        // http://tools.ietf.org/html/rfc5114#section-2.1
        Integer p("0xB10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C6"
            "9A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C0"
            "13ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD70"
            "98488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0"
            "A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708"
            "DF1FB2BC2E4A4371");

        Integer g("0xA4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507F"
            "D6406CFF14266D31266FEA1E5C41564B777E690F5504F213"
            "160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1"
            "909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28A"
            "D662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24"
            "855E6EEB22B3B2E5");

        Integer q("0xF518AA8781A8DF278ABA4E7D64B7CB9D49462353");

        // Schnorr Group primes are of the form p = rq + 1, p and q prime. They
        // provide a subgroup order. In the case of 1024-bit MODP Group, the
        // security level is 80 bits (based on the 160-bit prime order subgroup).

        // For a compare/contrast of using the maximum security level, see
        // dh-agree.zip. Also see http://www.cryptopp.com/wiki/Diffie-Hellman
        // and http://www.cryptopp.com/wiki/Security_level .

        DH dh;
        AutoSeededRandomPool rnd;

        dh.AccessGroupParameters().Initialize(p, q, g);

        if(!dh.GetGroupParameters().ValidateGroup(rnd, 3))
            throw runtime_error("Failed to validate prime and generator");

        size_t count = 0;

        p = dh.GetGroupParameters().GetModulus();
        q = dh.GetGroupParameters().GetSubgroupOrder();
        g = dh.GetGroupParameters().GetGenerator();

        // http://groups.google.com/group/sci.crypt/browse_thread/thread/7dc7eeb04a09f0ce
        Integer v = ModularExponentiation(g, q, p);
        if(v != Integer::One())
            throw runtime_error("Failed to verify order of the subgroup");

        //////////////////////////////////////////////////////////////

        SecByteBlock priv(dh.PrivateKeyLength());
        SecByteBlock pub(dh.PublicKeyLength());
        dh.GenerateKeyPair(rnd, priv, pub);
        printf("lengths: %d %d\n",dh.PrivateKeyLength(),dh.PublicKeyLength());
        byte* pubData = pub.data();
        for(int j = 0; j < pub.size()-1; j++)
            printf("%02X:", pubData[j]);
        printf("%02X\n", pubData[pub.size()-1]);
        // Send pub to Java
        sendData(pub.data(),pub.size());
        // Read pubB from Java
        byte pubBbytes[10000];
        int n = readData(pubBbytes,sizeof(pubBbytes));
        SecByteBlock pubB(pubBbytes,n);
        //////////////////////////////////////////////////////////////

        SecByteBlock sharedA(dh.AgreedValueLength());

        if(!dh.Agree(sharedA, priv, pubB))
            throw runtime_error("Failed to reach shared secret (1A)");

        //////////////////////////////////////////////////////////////

        Integer a;

        a.Decode(sharedA.BytePtr(), sharedA.SizeInBytes());
        cout << "Shared secret (A): " << std::hex << a << endl;
    }

    catch(const CryptoPP::Exception& e)
    {
        cerr << e.what() << endl;
        return -2;
    }

    catch(const std::exception& e)
    {
        cerr << e.what() << endl;
        return -1;
    }

    return 0;
}

Server code in Java:
package test;
/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.KeyAgreement;
import javax.crypto.spec.DHParameterSpec;

/**
 * This program executes the Diffie-Hellman key agreement protocol
 * between 2 parties: Alice and Bob.
 *
 * By default, preconfigured parameters (1024-bit prime modulus and base
 * generator used by SKIP) are used.
 * If this program is called with the "-gen" option, a new set of
 * parameters is created.
 */

public class DHKeyAgreement2 {

    private DHKeyAgreement2() {}

    public final static String sP = "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C6" +
            "9A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C0" +
            "13ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD70" +
            "98488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0" +
            "A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708" +
            "DF1FB2BC2E4A4371";

    public final static String sG = "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507F" +
            "D6406CFF14266D31266FEA1E5C41564B777E690F5504F213" +
            "160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1" +
            "909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28A" +
            "D662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24" +
            "855E6EEB22B3B2E5";

    public static void main(String argv[]) {
        try {
            DHKeyAgreement2 keyAgree = new DHKeyAgreement2();
            keyAgree.run();
        } catch (Exception e) {
            System.err.println("Error: " + e);
            System.exit(1);
        }
    }

    private void run() throws Exception {

        DHParameterSpec dhSkipParamSpec;

        // use some pre-generated, default DH parameters
        System.out.println("Using SKIP Diffie-Hellman parameters");
        BigInteger p = new BigInteger(sP,16);
        BigInteger g = new BigInteger(sG,16);
        System.out.println("P " + sP.length() + " is: " + toHexString(p.toByteArray()));
        System.out.println("G " + sG.length() + " is: " + toHexString(g.toByteArray()));
        dhSkipParamSpec = new DHParameterSpec(p,g);
        /*
         * Alice creates her own DH key pair, using the DH parameters from
         * above
         */
        System.out.println("ALICE: Generate DH keypair ...");
        KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
        aliceKpairGen.initialize(dhSkipParamSpec);
        KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

        // Alice creates and initializes her DH KeyAgreement object
        System.out.println("ALICE: Initialization ...");
        KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
        aliceKeyAgree.init(aliceKpair.getPrivate());

        // Alice encodes her public key, and sends it over to Bob.
        byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
        byte[] alicePrivKeyEnc = aliceKpair.getPrivate().getEncoded();
        System.out.println("Alice pub key size: " + alicePubKeyEnc.length);
        System.out.println("Alice pub key: " + toHexString(alicePubKeyEnc));
        System.out.println("Alice priv key size: " + alicePrivKeyEnc.length);
        System.out.println("Alice priv key: " + toHexString(alicePrivKeyEnc));
        ServerSocket ss = new ServerSocket(5454);
        Socket accept = ss.accept();
        byte[] bobPubKeyEnc = readByteArrayFromSocket(accept);
        System.out.println("Read bob's pubkey: " + toHexString(bobPubKeyEnc));
        sendByteArrayToBob(alicePubKeyEnc);
        System.out.println("Sent Alice's pubkey");

        /*
         * Alice uses Bob's public key for the first (and only) phase
         * of her version of the DH
         * protocol.
         * Before she can do so, she has to instantiate a DH public key
         * from Bob's encoded key material.
         */
        KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
        PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
        System.out.println("ALICE: Execute PHASE1 ...");
        aliceKeyAgree.doPhase(bobPubKey, true);

        /*
         * At this stage, both Alice and Bob have completed the DH key
         * agreement protocol.
         * Both generate the (same) shared secret.
         */
        byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
        int aliceLen = aliceSharedSecret.length;

        System.out.println("Alice secret: " +
          toHexString(aliceSharedSecret));
    }
}

My output from C++:
lengths: 20 128
77:61:FD:93:D9:23:38:41:6D:B0:9B:F8:7A:FB:CE:CA:0E:DF:7D:0A:95:F6:B4:55:FF:64:32:03:2C:B5:9C:47:05:06:FF:1B:72:F3:C6:8A:91:68:13:98:DE:56:0C:D6:02:30:C2:4B:DB:AD:0A:B3:7D:2A:7E:DD:13:A8:7C:97:4A:46:79:6A:85:C7:5B:79:29:D8:E5:2B:F4:59:21:B3:29:EA:6A:2F:FB:70:A1:C8:FD:5C:31:E1:92:A9:B0:67:74:65:3D:C1:1B:33:4B:DE:1C:EB:1E:A1:3A:36:29:0F:DF:A2:FA:5D:DA:69:DC:6D:00:D7:76:95:3A:FD:7D:76
sent 128 bytes, remaining 0
Failed to reach shared secret (1A)

And output from Java:
Using SKIP Diffie-Hellman parameters
P 256 is: 00:B1:0B:8F:96:A0:80:E0:1D:DE:92:DE:5E:AE:5D:54:EC:52:C9:9F:BC:FB:06:A3:C6:9A:6A:9D:CA:52:D2:3B:61:60:73:E2:86:75:A2:3D:18:98:38:EF:1E:2E:E6:52:C0:13:EC:B4:AE:A9:06:11:23:24:97:5C:3C:D4:9B:83:BF:AC:CB:DD:7D:90:C4:BD:70:98:48:8E:9C:21:9A:73:72:4E:FF:D6:FA:E5:64:47:38:FA:A3:1A:4F:F5:5B:CC:C0:A1:51:AF:5F:0D:C8:B4:BD:45:BF:37:DF:36:5C:1A:65:E6:8C:FD:A7:6D:4D:A7:08:DF:1F:B2:BC:2E:4A:43:71
G 256 is: 00:A4:D1:CB:D5:C3:FD:34:12:67:65:A4:42:EF:B9:99:05:F8:10:4D:D2:58:AC:50:7F:D6:40:6C:FF:14:26:6D:31:26:6F:EA:1E:5C:41:56:4B:77:7E:69:0F:55:04:F2:13:16:02:17:B4:B0:1B:88:6A:5E:91:54:7F:9E:27:49:F4:D7:FB:D7:D3:B9:A9:2E:E1:90:9D:0D:22:63:F8:0A:76:A6:A2:4C:08:7A:09:1F:53:1D:BF:0A:01:69:B6:A2:8A:D6:62:A4:D1:8E:73:AF:A3:2D:77:9D:59:18:D0:8B:C8:85:8F:4D:CE:F9:7C:2A:24:85:5E:6E:EB:22:B3:B2:E5
ALICE: Generate DH keypair ...
ALICE: Initialization ...
Alice pub key size: 426
Alice pub key: 30:82:01:A6:30:82:01:1B:06:09:2A:86:48:86:F7:0D:01:03:01:30:82:01:0C:02:81:81:00:B1:0B:8F:96:A0:80:E0:1D:DE:92:DE:5E:AE:5D:54:EC:52:C9:9F:BC:FB:06:A3:C6:9A:6A:9D:CA:52:D2:3B:61:60:73:E2:86:75:A2:3D:18:98:38:EF:1E:2E:E6:52:C0:13:EC:B4:AE:A9:06:11:23:24:97:5C:3C:D4:9B:83:BF:AC:CB:DD:7D:90:C4:BD:70:98:48:8E:9C:21:9A:73:72:4E:FF:D6:FA:E5:64:47:38:FA:A3:1A:4F:F5:5B:CC:C0:A1:51:AF:5F:0D:C8:B4:BD:45:BF:37:DF:36:5C:1A:65:E6:8C:FD:A7:6D:4D:A7:08:DF:1F:B2:BC:2E:4A:43:71:02:81:81:00:A4:D1:CB:D5:C3:FD:34:12:67:65:A4:42:EF:B9:99:05:F8:10:4D:D2:58:AC:50:7F:D6:40:6C:FF:14:26:6D:31:26:6F:EA:1E:5C:41:56:4B:77:7E:69:0F:55:04:F2:13:16:02:17:B4:B0:1B:88:6A:5E:91:54:7F:9E:27:49:F4:D7:FB:D7:D3:B9:A9:2E:E1:90:9D:0D:22:63:F8:0A:76:A6:A2:4C:08:7A:09:1F:53:1D:BF:0A:01:69:B6:A2:8A:D6:62:A4:D1:8E:73:AF:A3:2D:77:9D:59:18:D0:8B:C8:85:8F:4D:CE:F9:7C:2A:24:85:5E:6E:EB:22:B3:B2:E5:02:02:02:00:03:81:84:00:02:81:80:25:E7:BD:24:57:C9:59:EE:E0:EC:7A:F3:D6:22:1C:84:68:52:D9:19:40:5F:1B:C6:CB:A9:3A:42:BF:AB:3C:C2:EC:6F:BC:F9:F9:B2:70:AC:A2:E5:CE:36:FC:06:4F:2D:B3:4F:B5:25:D9:59:AD:D6:AD:B6:17:FA:09:76:AE:89:99:91:52:9B:E0:10:1D:9F:AC:50:AF:02:6D:25:F6:E8:DD:B8:6C:51:17:44:59:98:52:4B:E9:75:E1:D1:26:FE:EA:73:EF:C7:89:7F:70:A8:ED:6F:57:28:A4:0F:1B:F8:21:7D:A5:A2:59:B9:74:42:42:45:BA:EC:E2:53:B3:C4
Alice priv key size: 362
Alice priv key: 30:82:01:66:02:01:00:30:82:01:1B:06:09:2A:86:48:86:F7:0D:01:03:01:30:82:01:0C:02:81:81:00:B1:0B:8F:96:A0:80:E0:1D:DE:92:DE:5E:AE:5D:54:EC:52:C9:9F:BC:FB:06:A3:C6:9A:6A:9D:CA:52:D2:3B:61:60:73:E2:86:75:A2:3D:18:98:38:EF:1E:2E:E6:52:C0:13:EC:B4:AE:A9:06:11:23:24:97:5C:3C:D4:9B:83:BF:AC:CB:DD:7D:90:C4:BD:70:98:48:8E:9C:21:9A:73:72:4E:FF:D6:FA:E5:64:47:38:FA:A3:1A:4F:F5:5B:CC:C0:A1:51:AF:5F:0D:C8:B4:BD:45:BF:37:DF:36:5C:1A:65:E6:8C:FD:A7:6D:4D:A7:08:DF:1F:B2:BC:2E:4A:43:71:02:81:81:00:A4:D1:CB:D5:C3:FD:34:12:67:65:A4:42:EF:B9:99:05:F8:10:4D:D2:58:AC:50:7F:D6:40:6C:FF:14:26:6D:31:26:6F:EA:1E:5C:41:56:4B:77:7E:69:0F:55:04:F2:13:16:02:17:B4:B0:1B:88:6A:5E:91:54:7F:9E:27:49:F4:D7:FB:D7:D3:B9:A9:2E:E1:90:9D:0D:22:63:F8:0A:76:A6:A2:4C:08:7A:09:1F:53:1D:BF:0A:01:69:B6:A2:8A:D6:62:A4:D1:8E:73:AF:A3:2D:77:9D:59:18:D0:8B:C8:85:8F:4D:CE:F9:7C:2A:24:85:5E:6E:EB:22:B3:B2:E5:02:02:02:00:04:42:02:40:3C:16:B6:8F:73:CD:9D:0F:19:D5:A7:54:61:FC:A9:AF:3E:79:78:B8:5E:3E:3D:58:52:2F:95:5E:0D:3F:E0:19:92:17:22:B4:06:9A:E4:ED:9D:55:54:3F:1F:DE:20:36:31:5A:AC:58:FB:A3:C2:7E:65:31:A4:F0:43:37:A2:37
Read 128 bytes
Read bob's pubkey: 77:61:FD:93:D9:23:38:41:6D:B0:9B:F8:7A:FB:CE:CA:0E:DF:7D:0A:95:F6:B4:55:FF:64:32:03:2C:B5:9C:47:05:06:FF:1B:72:F3:C6:8A:91:68:13:98:DE:56:0C:D6:02:30:C2:4B:DB:AD:0A:B3:7D:2A:7E:DD:13:A8:7C:97:4A:46:79:6A:85:C7:5B:79:29:D8:E5:2B:F4:59:21:B3:29:EA:6A:2F:FB:70:A1:C8:FD:5C:31:E1:92:A9:B0:67:74:65:3D:C1:1B:33:4B:DE:1C:EB:1E:A1:3A:36:29:0F:DF:A2:FA:5D:DA:69:DC:6D:00:D7:76:95:3A:FD:7D:76
Sent Alice's pubkey
Error: java.security.spec.InvalidKeySpecException: Inappropriate key specification

Seems like altough I use the same G and P in both programs, the keys generated in C++ are 128\20 byte long (public\private) while in java they are 426\362 byte long. I was wondering where I can set the desired key length in crypto++ but yet to discover that. Also I removed some helper function from the codes above, so I guess copy-paste and trying to compile them won't work. If anyone will actually want to do that I will submit my complete code.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I insert an umlaut on the u in ubuntu in a Web Text Input? I have read this post: How do I insert an umlaut on the u in ubuntu? and i managed to get the Umlaute:
Activate the Compose Key like described above in Tweaks. (i have chosen Right Alt) and then enter in the text editor:
AltGr + a

and then "
for ä
But how do i get it work in the Web text input like in Stackoverflow? Pressing the combination in the Webinterface just prints out a


text:
Q: Custom Query pagination 404 Error I am struggling with the pagination of a custom loop in WordPress …
The Links are displayer correctly, but when I click on the next page I get a 404 Error.
The Link seems to be correct http://…/page/2/
Did I miss something while creating the query?
Do I have to add an additional function in the functions.php file?
This is my query:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wu_media_query = new WP_Query( );
$wu_media_query->query('showposts=5&post_type=wu_media&paged=' . $paged);

Would be grateful any hint :-)
Dominik

A: First, go to Settings >> Permalinks and hit Save Changes button. Sometime you need to regenerate you .htaccess file to make the pagination work.
Make sure you've called wp_reset_query() after ending the while loop or after the default WordPress loop. Sometimes it make this kinda trouble.
Pass 'paged' => $paged with the query arguments array to the WP_Query
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$query_args = array(
  'post_type' => 'post',
  'category_name' => 'tutorials',
  'posts_per_page' => 5,
  'paged' => $paged // Like this.
);

Remember, for custom pages that are NOT static home pages, the $paged variable changes to this:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

Hope the above helps you.


text:
Q: RecyclerView SnapHelper - how to change background of snapped and unsnapped items? I'm using recyclerview with horizontal LinearLayoutManager. I want to change recyclerview item color, when item is snapped in a middle.
So i used LinearSnapHelper.
At the moment, each items, which were previously snapped stays with snapped background color. So What i did, I made global variable snappedPosition and set it to 0, so first item of the recyclerview will be snapped by default.
Then I called that snappedPosition in onBindViewHolder of my adapter and changed color of item to default for every item in recyclerview except one with same position as position of snapped item. But at notifyItemChanged(position) ive got:

java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling android.support.v7.widget.RecyclerView

code inside fragment:
val snapHelper: LinearSnapHelper = LinearSnapHelper()
var snappedPosition: Int = 0

        addressRecyclerView = view.findViewById<RecyclerView>(R.id.address_recycler_view).apply {

            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter

        }

        snapHelper.attachToRecyclerView(addressRecyclerView)
        addressRecyclerView.onFlingListener = snapHelper
        itemOffsetDecoration = ItemOffsetDecoration(context, R.dimen.address_recyclerview_padding)
        addressRecyclerView.addItemDecoration(itemOffsetDecoration)

        addressRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    val centerView = snapHelper.findSnapView(viewManager)
                    if (centerView != null) {

                        snappedPosition = addressRecyclerView.getChildAdapterPosition(centerView)
                    }
                }
            }
        })

code inside onBindViewHolder
addressList[position].let {

                if (position == fragment.snappedPosition){
                    holder.itemViewLayout.setBackgroundResource(R.drawable.payment_button_active)
                    notifyItemChanged(position)
                } else {
                    holder.itemViewLayout.setBackgroundResource(R.drawable.payment_button_inactive)
                    notifyItemChanged(position)
                }

            }

What i want to achieve is similar to this image example:

Update: Code example for color change variant (still not working):
addressRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    val centerView = snapHelper.findSnapView(addressRecyclerView.layoutManager)
                    if (centerView != null) {
                        for(item in 0 until addressRecyclerView.layoutManager.childCount){
                            val holder: RecyclerView.ViewHolder = addressRecyclerView.findViewHolderForAdapterPosition(item)
                            holder.itemView.setBackgroundResource(R.drawable.payment_button_inactive)
                        }
                        centerView.setBackgroundResource(R.drawable.payment_button_active)

                    }
                }
            }
        })

A: Try the following to track the current snapped view, set the appropriate background and clearing it upon movement of the RecyclerView. This avoids making modifications to the adapter.
    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                View view = mSnapHelper.findSnapView(recyclerView.getLayoutManager());
                view.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
                mLastSnappedView = view;
            } else if (mLastSnappedView != null) {
                mLastSnappedView.setBackgroundColor(getResources().getColor(android.R.color.white));
                mLastSnappedView = null;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        }
    });


text:
Q: rxjs observable doesn't subscribe with async pipe I have the following pipeline and html template, but the app always displays #noMatch and doesn't logs "in the pipe" in the reduce function. I feel it's a matter of timing but I'm not able to fix it.
ts
user$: Observable<User> = new Observable<User>();
matches$: Observable<User[]> = this.user$.pipe(
  switchMap((user: User) => {
    this.type= user.type;
    return of([user, user, user]);
  }),
  distinctUntilChanged(),
);
filteredMatches$: Observable<{ type1: User[]; type2: User[] }>;

ngOnInit(): void {
  this.user$ = this.authService.user$;

  this.filteredMatches$ = this.matches$.pipe(
    reduce((acc: any, curr: User[]) => {
      if (!acc.type1) acc.type1= [];
      if (!acc.type2) acc.type2= [];
      console.log('in the pipe');

      this.networkingService.decideType(this.type, curr.type)
        ? acc.type1.push(curr)
        : acc.type2.push(curr);
      return acc;
    }),
  );
}

html
<ng-template *ngIf="(filteredMatches$ | async) as matches; else noMatch">
  <app-child *ngFor="let user of matches.type1" [user]="user">
  <app-child *ngFor="let user of matches.type2" [user]="user">
</ng-template>

<ng-template #noMatch>
    <app-no-match></app-no-match>
</ng-template>

A: Ah found it. You do this:
user$: Observable<User> = new Observable<User>();
matches$: Observable<User[]> = this.user$.pipe(
  switchMap((user: User) => {
    this.type= user.type;
    return of([user, user, user]);
  }),
  distinctUntilChanged(),
);

mathes$ listens to user$ which is a new Observable.
Then, on ngInit you do this:
this.user$ = this.authService.user$;

You replace the value of user$ with the authService's user$. But mathes$ is still subscribed to the first Observable, which is not doing anything.
I suggest you replace
 user$: Observable<User> = new Observable<User>();
 //by
 user$: Observable<User> = this.authService.user$;

Or better yet, directly use the authService's user$ instead of creating a property for it.
EDIT: In my opinion, there is no reason to use the ngOnInit here, you could simply have the observable set at the beggining...
matches$: Observable<User[]> = this.authService.user$.pipe(
  switchMap((user: User) => {
    this.type= user.type;
    return of([user, user, user]);
  }),
  distinctUntilChanged(),
);
filteredMatches$: Observable<{ type1: User[]; type2: User[] }> = this.matches$.pipe(
    reduce((acc: any, curr: User[]) => {
      if (!acc.type1) acc.type1= [];
      if (!acc.type2) acc.type2= [];
      console.log('in the pipe');

      this.networkingService.decideType(this.type, curr.type)
        ? acc.type1.push(curr)
        : acc.type2.push(curr);
      return acc;
    }),
  );

A: @Salketer's answer is correct - the reason and the solution. Further: if, for some reason or another, the source observable isn't available yet in the constructor (it depends on some inputs, for example), you could do something like this
user$: Observable<User> = new Subject<User>();
matches$: Observable<User[]> // no changes here

ngOnInit(): void {
  this.authService.user$.subscribe(this.users$);

(A Subject is both an observable and an observer).


text:
Q: Program that clicks 3 buttons in a web app in a specified order I was wondering if i can write a program that clicks some buttons in a specified order in a web app or a web site. For example click Autos then weather then sports in http://www.bbc.co.uk/ with that order.
I have made some search but i didn't find anything about that.
I don't know even in what language i can write it or how to start.

A: It is possible. Here are 2 possible ways you can take:

*

*Java with Robot class

*Python with pywin32 or see example from stackoverflow
Java example:
Robot r=new Robot();
r.mouseMove(x,y);
r.mousePress(InputEvent.BUTTON1_MASK);


text:
Q: How to read D3 node label text into a div/paragraph element? I'm working with a force labelled graph layout in D3 and one of my project requirements is that the text associated with each node should show up in a div/p element that occupies a fixed position on the web page instead of showing up directly adjacent to the concerned node (currently it activates on mouse hover). So every time a user hovers on any node, the corresponding text should show up in the div tag and not right next to the node in the graph.
The following code snippets show how I'm currently working with my nodes and labels:
var node = vis.selectAll(".node")
        .data(nodes)
        .enter().append("g")
        .attr("class", "node")
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .call(force.drag);

    node.append("text")
        .text("");

force.on("tick", function() {
        nodes[0].x = w / 2;
        nodes[0].y = h / 2;

        link.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

node.on("mouseover", function(d){
        node.classed("node-active", function(o) {
            thisOpacity = isConnected(d, o) ? true : false;
            this.setAttribute('fill-opacity', thisOpacity);
            return thisOpacity;
        });

        link.classed("link-active", function(o) {
            return o.source === d || o.target === d ? true : false;
        });

        d3.select(this).classed("node-active", true);
        d3.select(this).select("circle").transition()
            .duration(500)
            .attr("r", 20);
        d3.select(this).select("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function(d) { return d.label; });
        d3.select(this).select("circle")
            .on("click", function(d){
                var win = window.open(d.label, '_blank');
                win.focus();
            });
    })

    .on("mouseout", function(d){
        node.classed("node-active", false);
        link.classed("link-active", false);

        d3.select(this).select("circle").transition()
            .duration(750)
            .attr("r", 10);
        d3.select(this).select("text")
            .text("");
    });

I have a div tag with id = 'nodeLabel' that will be used to print the node's label. I hope the attached code helps. I tried using document.getElementById('nodeLabel') to set it's value but I'm not sure if this is the right approach or where would this line of code go?
How do I achieve the desired effect?

A: In your mouseover handler, simply add something like this:
$("#nodeLabel").text(d.label);

Building on your code, this would result in:
node.on("mouseover", function(d){
    node.classed("node-active", function(o) {
        thisOpacity = isConnected(d, o) ? true : false;
        this.setAttribute('fill-opacity', thisOpacity);
        return thisOpacity;
    });

    link.classed("link-active", function(o) {
        return o.source === d || o.target === d ? true : false;
    });

    d3.select(this).classed("node-active", true);
    d3.select(this).select("circle").transition()
        .duration(500)
        .attr("r", 20);
    d3.select(this).select("circle")
        .on("click", function(d){
            var win = window.open(d.label, '_blank');
            win.focus();
        });

    $("#nodeLabel").text(d.label);
})

A: I would go about it probably by

*

*At the beginning, when you create the nodes, you call .each() and pass it a function that sets a member variable of each of the nodes to the value you want to display.

*In the onClick handler, you can get the element, on which the event occured, by d3.select(this) so I would take from it the value you stored in step 1 and set the div's text accordingly. Which would be something like d3.select("#nodeLabel").text(nodeText)

A: Ok, I found a way to do it.
I stored the value of d.label into a variable and then simply set the innerHTML of the 'p' tag in the mouseOver handle.
Here's the updated code snippet:
node.on("mouseover", function(d){
        node.classed("node-active", function(o) {
            thisOpacity = isConnected(d, o) ? true : false;
            this.setAttribute('fill-opacity', thisOpacity);
            return thisOpacity;
        });

        link.classed("link-active", function(o) {
            return o.source === d || o.target === d ? true : false;
        });

        var nodeText;
        d3.select(this).classed("node-active", true);
        d3.select(this).select("circle").transition()
            .duration(500)
            .attr("r", 20);
        d3.select(this).select("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function(d) { nodeText = d.label; return d.label; });
        d3.select("#nodeLabel").text(nodeText)
        d3.select(this).select("circle")
            .on("click", function(d){
                var win = window.open(d.label, '_blank');
                win.focus();
            });
        console.log(nodeText);
        document.getElementById('nodeLabel').innerHTML = "Node selected: "+nodeText;
    })

If there's a simpler/better solution, I would definitely still like to hear it and learn!


text:
Q: knitr: python engine output not in .md or .html When I process my .Rmd file, there is no matplotlib img displayed. Is there a chunk option, or a different matplotlib method that is needed?
---
title: "Viz Examples"
output:
  html_document:
    keep_md: true
---

```{r testplot, engine="python"}
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)

# You can provide either a single color or an array. To demonstrate this,
# the first bar of each set will be colored cyan.
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.print()

```

A: instead of plt.print() or plt.show() use
plt.savefig("somefilename.ext")

with ext being png or jpg or other supported output format, and any other savefig options, like transparent, then use the figure using a standard knitr mechanism.
```{r showfig,include=TRUE,echo=FALSE, results='asis'}
cat("!(./threedee.png)")
```


text:
Q: i am getting error while mingw is compiling opencv for c++? okay i was trying setup an environment for human detection program.. programming language i will use is c++ and compiler is code blocks..
i have downloaded opencv 4.1
also downloaded CMake
and mingw
i have also added path in environment setting..
i extracted opencv in c:\opencv\sources folder
and by using cmake i have configured and generated build files in c:\opencv\build
after this i open C:\opencv\source\opencv\build this folder and right click on it and open powershell and typed mingw32-make commnd.
so that Mingw will start compiling OpenCV
but after 5% error popout there...
PS C:\opencv\source\opencv\build> mingw32-make

[  2%] Built target zlib
[  2%] Building C object 3rdparty/libjpeg-turbo/CMakeFiles/libjpeg-turbo.dir/src/jmemmgr.c.obj
C:\opencv\source\opencv\sources\3rdparty\libjpeg-turbo\src\jmemmgr.c: In function 'realize_virt_arrays':
C:\opencv\source\opencv\sources\3rdparty\libjpeg-turbo\src\jmemmgr.c:662:11: error: 'SIZE_MAX' undeclared (first use in this function)
       if (SIZE_MAX - maximum_space < new_space)
           ^~~~~~~~
C:\opencv\source\opencv\sources\3rdparty\libjpeg-turbo\src\jmemmgr.c:662:11: note: each undeclared identifier is reported only once for each function it appears in
3rdparty\libjpeg-turbo\CMakeFiles\libjpeg-turbo.dir\build.make:678: recipe for target '3rdparty/libjpeg-turbo/CMakeFiles/libjpeg-turbo.dir/src/jmemmgr.c.obj' failed
mingw32-make[2]: * [3rdparty/libjpeg-turbo/CMakeFiles/libjpeg-turbo.dir/src/jmemmgr.c.obj] Error 1
CMakeFiles\Makefile2:312: recipe for target '3rdparty/libjpeg-turbo/CMakeFiles/libjpeg-turbo.dir/all' failed
mingw32-make[1]: * [3rdparty/libjpeg-turbo/CMakeFiles/libjpeg-turbo.dir/all] Error 2
Makefile:161: recipe for target 'all' failed
mingw32-make: *** [all] Error 2

A: Actually it is possible to compile opencv 3.4.3 by mingw32 (i have used 5.3.0 for the instance). Follow this guide. It is little bit old but works even for opencv 3.4.3
Steps to build:

*

*Download last Opencv version from the official github repo (let suppose you have downloaded opencv into "opencv" directory somewhere on your disk)

*Go to opencv/modules/videoio/src, open cap_dshow.hpp, paste #define NO_DSHOW_STRSAFE (right on top of all other), save file to commit changes

*Install CMake (I have used 3.5.1)

*Open CMake, point Opencv3.4.3 sources location also point where you want to build them (let suppose for the instance it would be "build" directory sonwhere on your disk), press "Configure button"

*Select from the dialog "Mingw Makefiles" and wait utill sources will be preprocessed

*All options are red is normal, check "Grouped" in right top region of the CMake window, now we should check some flags:
in group CMAKE: for option CMAKE_BUILD_TYPE write Release (to build release version of opencv), also here you can specify where you want Opencv binaries will be installed after build
in group ENABLE: check ENABLE_CXX11 and uncheck ENABLE_PRECOMPILED_HEADERS
in group WITH: uncheck WITH_MSMF

*Press "Configure" button, whait untill processing will be complited, now all options should become white

*Press "Generate" button and wait (in your build directory Makefile should be created, you can close CMake after this step)

*Make shure your mingw toolchain location is known for your system (look if system environment variable PATH contains path to mingw toolchain)

*Open cmd.exe, change directory to your opencv's build idrectory

*Let's build opencv (-j[uint] - option specifies number of threads to use)
.../build> mingw32-make -j4

*Let's install opencv
.../build> mingw32-make install

*Done


text:
Q: how to change Android reside menu item's textsize? I used Android reside menu. But this menu items are very big for my application, I want to set smaller item. How can i do this. Thanks for you attention!

A: Get the source of the Reside menu
Edit the  ResideMenuItem (ImageView iv_icon,TextView tv_title) object to your respective shape  & size


text:
Q: "Invalid object name 'OpenIddictAuthorizations'." - OpenIddict/.Net Core Identity Error I am new to .Net Core 2.0 and Identity framework. I am trying to use OpenIddict in the project.
References:
OpenIddict (2.0.0-rc1-final)
OpenIddict.EntityFrameworkCore(2.0.0-rc1-final)
Microsoft.AspNetCore.Identity.EntityFrameworkCore (2.0.1)
I keep on getting the following runtime error:
Invalid object name 'OpenIddictAuthorizations'.
Here is the stack trace:
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)

--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()

--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__32.MoveNext()

It looks like a SQL exception but I am not sure why it is looking for an object called OpenIddictAuthorizations in the database. Any help is highly appreciated.

A: Because you need this Table in your Db beside other tables
dbo.OpenIddictApplications
dbo.OpenIddictAuthorizations
dbo.OpenIddictScopes
dbo.OpenIddictTokens

So, OpenId can store the tokens and verify them.


text:
Q: Semantic drift: are the words "can", "could", etc becoming contranyms? There have been questions on ELU about the pronunciation of can and can't in American English. This question is about the usage of the word, not simply its pronunciation.
Here are a couple of examples found on google:

*

*"Can help but to revert ...";

*"Could care less" (admittedly, this phrase also has other plausible reasons for being);

If contraction 't (apostrophe-t) was simply missed occasionally, it could simply be excused as poor proof-reading. However, the omission seems to be more widespread in popular usage. The root word (e.g. can) still retains its original, positive meaning, so a sentence such as "I can do that" is now at risk of being ambiguous - can is then its own antonym.
My question: is there a semantic drift occurring with words such as can and could, turning them into contranyms?

A: Can help (but) is a Negative Polarity Item,
and so was could care less until it caught negation by association,
like (could) give a damn.

An NPI is a word (e.g, ever), phrase (in weeks/months/years), or grammatical oddity (would care to) that only occurs grammatically inside the scope of a negative word. There are a lot of negative triggers.

*

**She said she would care to have a gin fizz.

*She said she would not care to have a gin fizz.

**She said she had tasted a gin fizz in years.

*She said she hadn't tasted a gin fizz in years.

**She has ever been to Chicago.

*She has not ever been to Chicago.

No, there's nothing sinister going on with can and could that isn't going on with all the other modals, too. This is what you should expect with a modal and a negative in the same sentence. Negation and Modality are plenty complicated individually, plus modals and negatives always interact, in unpredictable ways.


text:
Q: CCL Cocoa bridge "hello world" not working? I'm trying to run the "hello world" script provided by Clozure for the CCL-Cocoa bridge:
https://trac.clozure.com/ccl/wiki/CocoaBridge

Load the file containing these forms, evaluate (show-red-window), and you'll see a red window.

red-window.ccl
(in-package "CL-USER")

(require "COCOA")

(defclass red-view (ns:ns-view)
  ()
  (:metaclass ns:+ns-object))

(objc:defmethod (#/drawRect: :void) ((self red-view) (rect :<NSR>ect))
  (#/set (#/redColor ns:ns-color))
  (#_NSRectFill (#/bounds self)))

(defun show-red-window ()
  (ccl::with-autorelease-pool
   (let* ((rect (ns:make-ns-rect 0 0 300 300))
      (w (make-instance 'ns:ns-window
                :with-content-rect rect
                :style-mask (logior #$NSTitledWindowMask
                           #$NSClosableWindowMask
                           #$NSMiniaturizableWindowMask)
                :backing #$NSBackingStoreBuffered
                :defer t)))
     (#/setTitle: w #@"Red")
     (#/setContentView: w (#/autorelease (make-instance 'red-view)))
     (#/center w)
     (#/orderFront: w nil)
     (#/contentView w))))

But when I run ccl64 and type
(load "red-window.ccl")
(show-red-window)

I just get this output on the terminal:
#<RED-VIEW <RedView: 0x4cd530> (#x4CD530)>

and nothing else appears to happen.
Am I missing something? I'm new to both CL and Cocoa.

A: Try
(gui:execute-in-gui #'(lambda () (show-red-window)))

The page with the red window example was last updated 10 years ago. One of the other examples from  was last modified 13 days ago to include gui:execute-in-gui.


text:
Q: JavaScript ONLY li text slider I'm looking for a JavaScript ONLY css slider. My previous one used jQuery but sadly my site doesn't really function when I use jQuery on it and the slider was in a iframe, and now I want to have my site without frames (they slow down the site).
My previous one looked like this with jQuery:

My code looked like this:

Hallo

Some more fading text

Add as many as you like

and I want to have it exactly the same but only with JavaScript.
Does someone know a site like this? The sliders on Google are pretty much all with jquery..

A: Try this out.
Markup:

1

2

3

CSS:
p {
  position: absolute;
  transition: opacity .5s ease-in;
}

p + p { opacity: 0; }

JS:
var current = 0,
    slides = document.getElementsByTagName("p");

setInterval(function() {
  for (var i = 0; i < slides.length; i++) {
    slides[i].style.opacity = 0;
  }
  current = (current != slides.length - 1) ? current + 1 : 0;
  slides[current].style.opacity = 1;
}, 1000);

fiddle

A: Vanilla Javascript Slider. Great for your use case. I hope it helps.
http://meandmax.github.io/lory/


text:
Q: Python pandas combine the second row if the first row IDs are the same We are using Python 2.7
We have a simple table below:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo polar bear'.split(),
               'B': '1 1 2 3 2 2 1 3 4 5'.split()})
print(df)

It generates
       A  B
0    foo  1
1    bar  1
2    foo  2
3    bar  3
4    foo  2
5    bar  2
6    foo  1
7    foo  3

Is there any Pandas way to match the ID in the column A?  For example, if the ID in the column A is the same, then concatenate the second row into a dictionary or a list.  For example:
{'foo,12213','bar,132'}

Thank you!

A: Your desired output is a little vague -- you mention dictionaries and lists, and then give a set containing strings -- but if you just care about the matched information and not the format it's in, then IIUC, you could use groupby.  If B consists of strings (as it does in your example frame), it's easy:
>>> df.groupby("A")["B"].sum()
A
bar        132
bear         5
foo      12213
polar        4
Name: B, dtype: object
>>> dict(df.groupby("A")["B"].sum())
{'polar': '4', 'bar': '132', 'foo': '12213', 'bear': '5'}

If B is made up of integers instead, we'd have to convert them to strings, maybe using something like
>>> df["B"].astype(str).groupby(df["A"]).sum()
A
bar        132
bear         5
foo      12213
polar        4
Name: B, dtype: object
>>> dict(df["B"].astype(str).groupby(df["A"]).sum())
{'polar': '4', 'bar': '132', 'foo': '12213', 'bear': '5'}

I recommend reading the documentation on the split-apply-combine pattern.

A: You could groupby aggregate to list and join the list as below.
df
Out[7]:
     A  B
0  foo  1
1  bar  1
2  foo  2
3  bar  3
4  foo  2
5  bar  2
6  foo  1
7  foo  3

df.groupby("A")["B"].apply(list)
Out[10]:
A
bar          [1, 3, 2]
foo    [1, 2, 2, 1, 3]

new_df = df.groupby("A")["B"].apply(list).reset_index()

new_df['B'] = new_df['B'].map(lambda x: ''.join([str(i) for i in x]))

     A      B
0  bar    132
1  foo  12213

new_df.set_index("A").to_dict()
Out[34]: {'B': {'bar': '132', 'foo': '12213'}}


text:
Q: What is the good strategy to backup mongodb's data without locking it (fsync & lock)? We have a mongodb running on only one AWS EC2 (no master-slave, no replica sets). The data files are stored in a separate EBS volume. So, what is the best way to backup and restore the data without locking it from writing (sync & lock)? Or we must have master-slave to achieve it?

A: As long as you have journaling enabled (the default in MongoDB 2.0+), you can take advantage of EBS snapshots to get a consistent dump of the data files without the need for fSyncLock().
This is covered in more detail in the  EC2 Backup & Restore documentation on the MongoDB site.

A: At MongoDirector.com we use LVM snapshotos to backup our MongoDB databases. As your DB size gets larger it really is the only option. If you use MongoDump and try to restore using MongoRestore it might take hours. In 2.0+ the fsyncLock() is optional but we do it anyways.


text:
Q: Angular 2 Custom Validator I did upgrade of my project and my validators does not working anymore.
My validator:
import {Directive, Provider, forwardRef, Input} from '@angular/core';
import {NG_VALIDATORS, Validator, FormControl} from '@angular/forms';

const ANO_MES_CC_VALIDATOR = { provide: NG_VALIDATORS, useExisting:       forwardRef(() => AnoMesCcValidator), multi: true };

declare var jQuery: JQueryStatic;

@Directive({
    selector: '[ano-mes-cc-validator]',
    providers: [ANO_MES_CC_VALIDATOR]
})
export class AnoMesCcValidator implements Validator {

    constructor() { }

    validate(c: FormControl): { [key: string]: any } {

        if (c.value == undefined || c.value == "") {
            //return null;
            return { 'anoMesccValidation': 'Validade Inválida.' };
        }

        var mes = c.value.substring(0, 2);
        var ano = c.value.substring(3, 7);

        //Verifica se o ano está correto
        if (ano.length == 4 && ano > 1900 && ano < 2100 && mes > 0 && mes <     13 ) {
            //valid
            return null;
        }
        else {
            return { 'anoMesccValidation': 'Validade Inválida.' };
        }
    }
}

My Typescript
import {AnoMesCcValidator} from '../../validators/index';

this.formCartaoDeCredito = new FormGroup({
        anoMesCartaoDeCreditoControl: new FormControl('anoMesCartaoDeCreditoControl', [Validators.required])
    });

My Template:
<form [formGroup]="formCartaoDeCredito" role="form">

        VencimentoEXP
        <input class="form-control"
               placeholder="MM / YYYY"
               autocomplete="cc-exp"
               onkeyup="formataMesAno(event)"
               maxlength="7"
               ano-mes-cc-validator
               formControlName="anoMesCartaoDeCreditoControl"
               [(ngModel)]="cartaoCredito.Validade" />

So, does not work, the error is 'Cannot read property 'valid' of undefined', i've already set #anoMesCartaoDeCreditoControl


text:
Q: WPF GUI object sharing (PRISM/MEF) I have created a prism project consisting of two modules (dll's). The two modules are loaded within a shell and build up following the MVVM pattern.
Module1 receives data which should be transferred (as fast as possible) to Module2. This data could be stored in an observablecollection for example. Which means that if this observablecollection is updated it should update the view in module2. It is a lot of data, so I would not use the eventaggregator for that.
I read something about dependency injection but I'm not sure how to do it. I found several examples where a submit button was pushed to transfer data between two modules. I guess what I need would be somehow a reference of the observablecollection(module1) within the module2. Shared services is another keyword I found.
What would be a good solution to solve this?
An example with an mvvm pattern would be great. I'm new to prism so please be kind.

A: There is nothing wrong with using events for such task. It is a common practice to have some interface:
interface IDataReciever<TData>
{
    event Action<TData> DataRecieved;
    //some other methods, such as, for example:
    //void Open();
    //void Close();
}

hinding all the interactions with serial port. You can then pass this interface to your viewmodel constructor, subscribe to event and add data to observable collection (converting it to some model if needed) in the event handler.


text:
Q: Trouble implementing priority queue Java I currently have an issue with my priority queue. When i'm testing my methods the I get an error saying my Queue isn't returning the highest priority. I have stepped through and I can't see why the Poll or Offer method is causing this issue. Any help would be appreciated. Thanks
public class HeapArrayQueue <E extends Comparable<? super E> > extends AbstractQueue <E> {

@SuppressWarnings("unchecked")
private E[] data = (E[])(new Comparable[7]);
private int count = 0;
private int front = 0;
public int size() {
    return count;
}

public boolean isEmpty() {
    return size() == 0;
}

public E poll() {
     if (isEmpty())
        return null;
    else {
        E ans = data[front ];
        front = (front+1);
        return ans;
    }
}

public boolean offer(E element) {
    if (element == null)return false;
    else {
        ensureCapacity();
        data[count] = element;
        bubbleUpFromIndex(count);
        count++;
        return true;
    }
}

private void bubbleUpFromIndex(int nodeIndex) {
     if (nodeIndex != 0){
         int parent = (nodeIndex -1) / 2;
         if (data[nodeIndex].compareTo(data[parent]) > 0){
             swap(nodeIndex, parent);
             bubbleUpFromIndex(parent);
         }
    }
}

private void swap(int from, int to) {
    E temp = data[from];
    data[from] = data[to];
    data[to] = temp;
}

private void ensureCapacity() {
    if (count == data.length) {
        @SuppressWarnings("unchecked")
        E[] newData = (E[])new Comparable[data.length * 2];

        for (int loop = 0; loop < count; loop++) {
            newData[loop] = data[loop];
        }
        data = newData;
    }
    return;
}

public Iterator<E> iterator() {
    return null;
}
}

Failing test
@Test
public void QueueRespectsPriority() {
    nonEmptyQueue.offer(t1);
    assertEquals("Queue should return element with highest priority", t1, nonEmptyQueue.poll());
}

A: Doing comp103 at vic I take it? looks very similar to what I'm doing at the moment.
The first thing I can see is that you're not preserving the correct priority in poll. Here (in pseudocode is my method)
public E poll(){
if (count = 0) return null
E item = root   // We are returning the root node so store it as a var
root = end      // place the end item in root position
end = null      // set end item to null
count--         // subtract count
sinkDown(0)     // Call sink down to restore ordering
return item     // return item
}

A: In your bubbleUpFromIndex method, your greater-than symbol > needs to be a less-than symbol <. And you should use the poll method in the other answer, then it will work.


text:
Q: Kafka consumer java code not working I have Just started with Kafka, I am able to produce and consume data through command prompt and also produce data through Java code even from remote server.
But I am trying this simple consumer Java code it is not working.
public class Simpleconsumer {

    private final ConsumerConnector consumer;
    private final String topic;

    public Simpleconsumer(String topic) {
        Properties props = new Properties();
        props.put("zookeeper.connect", "127.0.0.1:2181");
        props.put("group.id", "topic1");
        props.put("auto.offset.reset", "smallest");

        consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(props));
        this.topic = topic;
    }

    public void testConsumer() {
        try{
        Map<String, Integer> topicCount = new HashMap<String, Integer>();
        topicCount.put(topic, 1);

        Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumer.createMessageStreams(topicCount);
        List<KafkaStream<byte[], byte[]>> streams = consumerStreams.get(topic);
        System.out.println("start.......");
        for (final KafkaStream stream : streams) {
            ConsumerIterator<byte[], byte[]> it = stream.iterator();
            System.out.println("iterate.......");
            while (it.hasNext()) {
                System.out.println("Message from Single Topic: " + new String(it.next().message()));
            }
        }
        System.out.println("end.......");
        if (consumer != null) {
            consumer.shutdown();
        }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        // String topic = args[0];
        Simpleconsumer simpleHLConsumer = new Simpleconsumer("topic1");
        simpleHLConsumer.testConsumer();
    }

}

Output is :-
log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
log4j:WARN Please initialize the log4j system properly.
start.......
iterate.......

There is no error, the programme doesn't terminate or give any output!!
Log of zookeeper
2016-02-18 17:31:31,790 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@197] - Accepted socket connection from /127.0.0.1:33338
2016-02-18 17:31:31,793 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:ZooKeeperServer@868] - Client attempting to establish new session at /127.0.0.1:33338
2016-02-18 17:31:31,821 [myid:] - INFO  [SyncThread:0:ZooKeeperServer@617] - Established session 0x152f4265b0b0009 with negotiated timeout 6000 for client /127.0.0.1:33338
2016-02-18 17:31:31,891 [myid:] - INFO  [ProcessThread(sid:0 cport:-1)::PrepRequestProcessor@645] - Got user-level KeeperException when processing sessionid:0x152f4265b0b0009 type:create cxid:0x1 zxid:0x718 txntype:-1 reqpath:n/a Error Path:/consumers Error:KeeperErrorCode = NodeExists for /consumers
2016-02-18 17:31:31,892 [myid:] - INFO  [ProcessThread(sid:0 cport:-1)::PrepRequestProcessor@645] - Got user-level KeeperException when processing sessionid:0x152f4265b0b0009 type:create cxid:0x2 zxid:0x719 txntype:-1 reqpath:n/a Error Path:/consumers/artinew Error:KeeperErrorCode = NodeExists for /consumers/artinew
2016-02-18 17:31:31,892 [myid:] - INFO  [ProcessThread(sid:0 cport:-1)::PrepRequestProcessor@645] - Got user-level KeeperException when processing sessionid:0x152f4265b0b0009 type:create cxid:0x3 zxid:0x71a txntype:-1 reqpath:n/a Error Path:/consumers/artinew/ids Error:KeeperErrorCode = NodeExists for /consumers/artinew/ids
2016-02-18 17:31:32,000 [myid:] - INFO  [SessionTracker:ZooKeeperServer@347] - Expiring session 0x152f4265b0b0008, timeout of 6000ms exceeded
2016-02-18 17:31:32,000 [myid:] - INFO  [ProcessThread(sid:0 cport:-1)::PrepRequestProcessor@494] - Processed session termination for sessionid: 0x152f4265b0b0008
2016-02-18 17:31:32,002 [myid:] - INFO  [SyncThread:0:NIOServerCnxn@1007] - Closed socket connection for client /127.0.0.1:33337 which had sessionid 0x152f4265b0b0

I am getting this in Kafka console in infinite loop. please explain
[2016-02-17 20:50:08,594] INFO Closing socket connection to /xx.xx.xx.xx. (kafka.network.Processor)
[2016-02-17 20:50:08,174] INFO Closing socket connection to /xx.xx.xx.xx. (kafka.network.Processor)
[2016-02-17 20:50:08,385] INFO Closing socket connection to /xx.xx.xx.xx. (kafka.network.Processor)
[2016-02-17 20:50:08,760] INFO Closing socket connection to /xx.xx.xx.xx. (kafka.network.Processor)

i created the topic in the following manner
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 5 --topic topic1

i am able to consume it in command prompt using
bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic topic1

Not able to understand what is the issue.

A: Try localhost instead of 127.0.0.1 in code to make sure local resolution is working fine.


text:
Q: Why C# TypeBuilder.DefineConstructor always create a Constructor named ".ctor"? I tried this sample. DefineConstructor does not provide a way to set Constructor name.
I wish to define a dynamic type so I can use it in DI container. But I cannot Get it work when I am trying to set a method name of constructor.

MethodBuilder myMethodBuilder = null;
AppDomain myCurrentDomain = AppDomain.CurrentDomain;
// Create assembly in current CurrentDomain.
AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = "TempAssembly";
// Create a dynamic assembly.
myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly
         (myAssemblyName, AssemblyBuilderAccess.Run);
// Create a dynamic module in the assembly.
myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("TempModule");
FieldInfo myFieldInfo =
   myModuleBuilder.DefineUninitializedData("myField", 2, FieldAttributes.Public);
// Create a type in the module.
TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("TempClass",TypeAttributes.Public);
FieldBuilder myGreetingField = myTypeBuilder.DefineField("Greeting",
                                    typeof(String), FieldAttributes.Public);
Type[] myConstructorArgs = { typeof(String) };
// Define a constructor of the dynamic class.
ConstructorBuilder myConstructor = myTypeBuilder.DefineConstructor(
MethodAttributes.Public, CallingConventions.Standard, myConstructorArgs);
// Display the name of the constructor.
Console.WriteLine("The constructor name is  : "+ myConstructor.Name);
// Display the 'Type' object from which this object was obtained.
Console.WriteLine("The reflected type  is  : "+ myConstructor.ReflectedType);
// Display the signature of the field.
Console.WriteLine(myConstructor.Signature);
// Display the constructor builder instance as a string.
Console.WriteLine(myConstructor.ToString());

A: In IL, constructors don't have names, because they're not real functions in a very specific way: they don't have a return type. The .ctor thing (as well as .cctor) is just something to help you visualize what it is at a glance, internally they're special entries in classes.

A: According to ECMA-335 II.10.5.1, constructors must be named .ctor.

An instance constructor initializes an instance of a type, and is called when an instance of a type is created by the newobj instruction (see Partition III). An instance constructor shall be an instance (not static or virtual) method, it shall be named .ctor [...]

You don't need to name the constructor a specific name in order to call it with reflection. Given a Type t, you can call one of its constructors by:
Activator.CreateInstance(t, arg1, arg2, ...argn);

where arg1, arg2, ...argn are the arguments you pass to the constructor.
If you really want a name for your constructor, perhaps because you need two constructors that have the same signature but does different things, you can make it a factory method instead. Make a parameterless constructor Use DefineMethod to define a static method that calls that constructor, sets some properties of the created object in some way, and returns it. Then you can give a name to that static method.

A: .ctor is the defined name of all instance constructors, as defined by ECMA-335. Contrary to the other answer, it is actually the name of the function. But being that constructors cannot be called directly, only via a newobj instruction (new in C#) it makes little difference.
ECMA-335 says (my bold):

10.5.1 Instance constructor
An instance constructor initializes an instance of a type, and is called when an instance of a type is created by the newobj instruction (see Partition III). An instance constructor shall be an instance (not static or virtual) method, it shall be named .ctor, and marked instance, rtspecialname, and specialname...

It is also clear from section 22.26, that the actual name .ctor is encoded in the executable.


text:
Q: Save csv files using filenames in a map function loop I am looping a number of csv files in a folder using the map function. I want to save the results of the loop using a sliced version of the name of the csv. But I am getting an error when attempting to save the results to csv. Here is my code
library(tidyverse)
library(fs)
library(dismo)

file_paths <- fs::dir_ls("loop/")

file_paths %>%
  map(function (path){
    all_data <- read_csv(path, show_col_types = FALSE)
    name <- tools::file_path_sans_ext(basename(file_paths))
    print(name)
    t_max <- all_data[,c(2)]
    t_min <- all_data[, c(3)]
    rain_fall <- all_data[,c(4)]
    res <- data.frame(biovars(t_max, t_min, rain_fall))
    myfile = sprintf("%s_bio.csv", name)
    write_csv(res, file=myfile, col_names = TRUE)
  })

Error:
Error in if (is_url(path)) { : the condition has length > 1

A: You're using the full vector of full_paths inside your map, you should be using just the singular path:
file_paths %>%
  map(function (path){
    all_data <- read_csv(path, show_col_types = FALSE)
    name <- tools::file_path_sans_ext(basename(path))
    print(name)
    t_max <- all_data[,c(2)]
    t_min <- all_data[, c(3)]
    rain_fall <- all_data[,c(4)]
    res <- data.frame(biovars(t_max, t_min, rain_fall))
    myfile = sprintf("%s_bio.csv", name)
    write_csv(res, file=myfile, col_names = TRUE)
  })


text:
Q: django psycopg2 and postgresql insertion error I'm having trouble adding any data to my database. It lets me modify entries in tables, but any action that will create a new row or new column in a database is mysteriously failing. Here is the stack trace:
Traceback (most recent call last):
  File "manage.py", line 25, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/management/commands/migrate.py", line 107, in handle
    ignore_ghosts = ignore_ghosts,
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/__init__.py", line 219, in migrate_app
    success = migrator.migrate_many(target, workplan, database)
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 235, in migrate_many
    result = migrator.__class__.migrate_many(migrator, target, migrations, database)
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 310, in migrate_many
    result = self.migrate(migration, database)
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 134, in migrate
    self.done_migrate(migration, database)
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 113, in done_migrate
    self.record(migration, database)
  File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/migration/migrators.py", line 280, in record
    record.save()
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/base.py", line 463, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/base.py", line 551, in save_base
    result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/manager.py", line 203, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/query.py", line 1576, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/sql/compiler.py", line 910, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/util.py", line 40, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.4-py2.7.egg/django/db/backends/postgresql_psycopg2/base.py", line 52, in execute
    return self.cursor.execute(query, args)
django.db.utils.DatabaseError: syntax error at or near "RETURNING" at character 171

It was working fine until I migrated databases to another server. Now I'm having all sorts of trouble and I'm unsure what to do. Also, this seems to happen for South as well if trying to add a field to the database. Curiously, modifying existing objects / columns in the database succeeds without failure. I'm really unsure what to do and would love any assistance.

A: 8.1 doesn't support the RETURNING clause. So upgrade your database version to the current stable release.

A: 8.1 doesn't support RETURNING ids of inserted objects so you need to disable it.
from django.db import connection
##just before insert statement
connection.features.can_return_id_from_insert = False
###some insert statement


text:
Q: Rate my app dialog when the user want to exit my app I want to change the dialog of exit app with twi choices choice 1 = "rate" and choice 2 = "exit"  now i can only show exit or stay dialog but i want to convert it to what i described here is the code :
    @Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setNeutralButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   PicSelect.this.finish();
               }
           })
           .setNegativeButton("No", null)
           .show();
}

and this the class code `
public class PicSelect extends SherlockActivity {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private Itemadapter imageAdapter;
private AdView mAdView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_picselct);
    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#c5d951")));
    mAdView = (AdView) findViewById(R.id.adViewad);
    mAdView.loadAd(new AdRequest.Builder().build());

    mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
    mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
    photoGrid = (GridView) findViewById(R.id.albumGrid);

    Model.LoadModel();
    String[] ids = new String[Model.Items.size()];
    for (int i= 0; i < ids.length; i++){
        ids[i] = Integer.toString(i+1);
    }

    imageAdapter=new Itemadapter(getApplicationContext(), R.layout.photo_item,ids,"CATIMAGE");
    photoGrid.setAdapter(imageAdapter);

    // get the view tree observer of the grid and set the height and numcols dynamically
            photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (imageAdapter.getNumColumns() == 0) {
                        final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
                        if (numColumns > 0) {
                            final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
                            imageAdapter.setNumColumns(numColumns);
                            imageAdapter.setItemHeight(columnWidth);

                        }
                    }
                }
            });

            photoGrid.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    Log.e("FolderName", Model.GetbyId(position+1).FolderName);

                    String FolderName=Model.GetbyId(position+1).FolderName;
                    String CategoryName=Model.GetbyId(position+1).Name;
                    Intent i=new Intent(PicSelect.this,PicItem.class);
                    i.putExtra("Folder", FolderName);
                    i.putExtra("Category", CategoryName);
                    startActivity(i);

                }
            });

}
@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setNeutralButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   PicSelect.this.finish();
               }
           })
           .setNegativeButton("No", null)
           .show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.home, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{

    switch (menuItem.getItemId())
    {

    case R.id.rateapp:

        final String appName = getPackageName();//your application package name i.e play store application url
        try {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("market://details?id="
                            + appName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id="
                            + appName)));
        }
        return true;

    case R.id.moreapp:

        startActivity(new Intent(
                Intent.ACTION_VIEW,
                Uri.parse(getString(R.string.play_more_apps))));

        return true;

    default:
        return super.onOptionsItemSelected(menuItem);
    }

}

}
`
finaly if anyone know how to style the text thank you for your help

A: .setNegativeButton("Rate App", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   Intent i = new Intent(android.content.Intent.ACTION_VIEW);
                   i.setData(Uri.parse("market://details?id=[your package name]"));
                   startActivity(i);
               }
           })

This will give you a negative option that says Rate App that when clicked opens the market to your app.

A: Improve your app with this snippet in onBackPressed():
 if(isTaskRoot()) {
            if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
                toast = Toast.makeText(this, getString(R.string.hinweisBeendeApp), Toast.LENGTH_SHORT);
                toast.show();
                this.lastBackPressTime = System.currentTimeMillis();
            } else {
                if (toast != null) {
                    toast.cancel();
                }
                super.onBackPressed();
            }
        }else {
            super.onBackPressed();
        }


text:
Q: continue php script execution called by ajax after i have a page called call.php with this codes
    <script src="http://localhost/js/jquery.js"></script>
    <script>
        $(document).ready(function()
        {
            $.post("exe.php",
            {
                a: 'a'
            },
            function(data)
            {
                alert(data);
            });
        });
    </script>
///close tabs after onload

and in exe.php i have this code
<?php

    set_time_limit(60);
    ignore_user_abort(true);
    sleep(20);

    $file = fopen("test.txt","w");
?>

i need to continue php execution even after closing tab immediately
it works fine in localhost using WAMP
but in my host doesn't work it stops after perhaps 10-14 secs
in localhost and server ignore_user_abort(true) is off
the question is : turning this function ON solves the problem? and why in localhost  it works even when this function is off
my execution takes about 30 sec times i need to get it working
EDIT
i tried something like this
<?php
    ignore_user_abort(true);
function shutdown()
{
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/2.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/4.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/6.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/8.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/10.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/12.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/14.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/16.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/18.txt',"w");
    sleep(2);
    $file = fopen($_SERVER["DOCUMENT_ROOT"].'/logs/20.txt',"w");
}
//register_shutdown_function('shutdown');
shutdown();
?>

opened tab and closed immediately after if completely loaded
this code created 2.txt ... 10.txt
so certainly there is an option which shuts down script after 10 secs

A: On Windows, PHP will buffer the output to a certain amount of Bytes (last time I tested, I believe it was 2048). As long as PHP does not try to flush that buffer, it will not detect a closed connection, and so it will not abort the script. On Linux that buffer works differently and most importantly does not ignore flush().
As to why your ignore_user_abort(true) call "does not work" (this kind of sentence is not a good error report and will not likely result in your getting a good answer) I can not possibly know.

*

*You could however try to use register_shutdown_function instead.

*You could also try increasing the max execution time using a .htaccess file. The syntax is quite easy
php_flag max_execution_time 120

*The web server itself also may have an execution time limit that may abort your script, see TimeOut for example.

A: You want to use the ignore_user_abort function.
Definition:

Set whether a client disconnect should abort script execution

Warning: Be careful with this, the only way to kill an infinite loop would be to kill the web server/PHP depending on your setup.

A: You need to call ignore_user_abort and set_time_limit before you call sleep.


text:
Q: I have ap-hotspot installed and working, but only HTTPS sites can connect I installed ap-hotspot on my Linux Mint. Everything looks fine now, but only HTTPS sites can be connected from my Galaxy S4 phone such as Facebook, Google etc. When I want to connect to some other sites it is just not doing anything, just shows loading and dies due to timeout.
Here is my ap-hotspot debug log
* Stopping advanced IEEE 802.11 management hostapd
...done.
* Stopping DNS forwarder and DHCP server dnsmasq
* (not running)
update-rc.d: warning:  start runlevel arguments (none) do not match hostapd Default-Start values (2 3 4 5)
update-rc.d: warning:  stop runlevel arguments (none) do not match hostapd Default-Stop values (0 1 6)
Disabling system startup links for /etc/init.d/hostapd ...
Removing any system startup links for /etc/init.d/hostapd ...
/etc/rc0.d/K20hostapd
/etc/rc1.d/K20hostapd
/etc/rc2.d/K80hostapd
/etc/rc3.d/K80hostapd
/etc/rc4.d/K80hostapd
/etc/rc5.d/K80hostapd
/etc/rc6.d/K20hostapd
Adding system startup for /etc/init.d/hostapd ...
/etc/rc0.d/K20hostapd -> ../init.d/hostapd
/etc/rc1.d/K20hostapd -> ../init.d/hostapd
/etc/rc6.d/K20hostapd -> ../init.d/hostapd
/etc/rc2.d/K80hostapd -> ../init.d/hostapd
/etc/rc3.d/K80hostapd -> ../init.d/hostapd
/etc/rc4.d/K80hostapd -> ../init.d/hostapd
/etc/rc5.d/K80hostapd -> ../init.d/hostapd
update-rc.d: warning:  start runlevel arguments (none) do not match dnsmasq Default-Start values (2 3 4 5)
update-rc.d: warning:  stop runlevel arguments (none) do not match dnsmasq Default-Stop values (0 1 6)
Disabling system startup links for /etc/init.d/dnsmasq ...
Removing any system startup links for /etc/init.d/dnsmasq ...
/etc/rc0.d/K85dnsmasq
/etc/rc1.d/K85dnsmasq
/etc/rc2.d/K85dnsmasq
/etc/rc3.d/K85dnsmasq
/etc/rc4.d/K85dnsmasq
/etc/rc5.d/K85dnsmasq
/etc/rc6.d/K85dnsmasq
Adding system startup for /etc/init.d/dnsmasq ...
/etc/rc0.d/K85dnsmasq -> ../init.d/dnsmasq
/etc/rc1.d/K85dnsmasq -> ../init.d/dnsmasq
/etc/rc6.d/K85dnsmasq -> ../init.d/dnsmasq
/etc/rc2.d/K85dnsmasq -> ../init.d/dnsmasq
/etc/rc3.d/K85dnsmasq -> ../init.d/dnsmasq
/etc/rc4.d/K85dnsmasq -> ../init.d/dnsmasq
/etc/rc5.d/K85dnsmasq -> ../init.d/dnsmasq
* Restarting DNS forwarder and DHCP server dnsmasq
...done.
net.ipv4.ip_forward = 1


text:
Q: Signed hex subtraction vs unsigned I have to do subtraction on two signed 16-bit hexadecimal numbers. C352 - 36AE. Whats the difference between signed and unsigned, when it comes to doing math with them? Is the only solution converting them to binary, performing signed subtraction, and then converting the answer back to hex? Thanks.

A: Subtraction is the same for both signed and unsigned.  What is different is how the results are interpreted.  Unsigned numbers can never be negative:
0xffff is -1  signed.
0xffff is 65,535 unsigned.
It's the same number.
http://en.wikipedia.org/wiki/Two%27s_complement

A: The result of a 16 bit signed or unsigned subtraction is always 16 bits (being the result of bitwise subtraction) plus a 17th bit with the 17th bit being either the overflow bit (signed subtraction) or the carry bit (unsigned subtraction).  If you only have a 16 bit result you have a bitwise subtraction NOT a signed or unsigned 16 bit subtraction.  Instead of specifying signed, unsigned, or bitwise subtraction many systems produce all three results at once.  You later use the overflow bit if you intended signed subtraction, the carry bit if you intended unsigned subtraction, or neither for a bitwise subtraction.  Note that many people don't look at the 17th bit because they know from the range of inputs that they don't need a true 16 bit subtraction.  For instance if I subtract a number that I know to be between 0-100 from a number that I know to be between 1000-2000 I don't need a true 16 bit subtraction so I don't need to look at the 17th bit.  Note: Overflow and carry are derived by different rules and are NOT the same but the difference between the two has already been explained elsewhere so I won't duplicate that answer here.