问:
JSON pretty printing isn't working in Python
As far as I can tell, this code should work.

```<code>import json
with open('path', 'r') as infile:
    data = json.load(infile)
    print(json.dumps(data, indent=4))
</code>```

But it doesn't. I get this:

```<code>"b'{\"Markets\":[{\"ID\":2461,\"Name\":\"Who will be elected German chancellor in 2017?\",\"ShortName\":\"Who will be elected German chancellor in 2017?\",\"TickerSymbol\":\"CHANCELLOR.GERMANY.2017\",\"Image\":\"https://az620379.vo.msecnd.net/images/Markets/5914fd50-9a60-46d1-ac5f-b36c2c4c9832.png\",\"URL\":\"https://www.predictit.org/Market/2461/Who-will-be-elected-German-chancellor-in-2017\",\"Contracts\":[{\"ID\":3613,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_494e673d-12cc-40c5-ab6a-2976c582303f.png\" ...
</code>```

However, if I go to http://jsonprettyprint.com/ and give it the same data, I get pretty indentation. So the problem's with the code, not the data (though I don't understand why there are so many backslashes).

What am I doing wrong?

Edit: Sample data

```<code>"b'{\"ID\":2461,\"Name\":\"Who will be elected German chancellor in 2017?\",\"ShortName\":\"Who will be elected German chancellor in 2017?\",\"TickerSymbol\":\"CHANCELLOR.GERMANY.2017\",\"Image\":\"https://az620379.vo.msecnd.net/images/Markets/5914fd50-9a60-46d1-ac5f-b36c2c4c9832.png\",\"URL\":\"https://www.predictit.org/Market/2461/Who-will-be-elected-German-chancellor-in-2017\",\"Contracts\":[{\"ID\":3613,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_494e673d-12cc-40c5-ab6a-2976c582303f.png\",\"URL\":\"https://www.predictit.org/Contract/3613/Will-Angela-Merkel-be-elected-German-chancellor-in-2017\",\"Name\":\"Angela Merkel\",\"LongName\":\"Will Angela Merkel be elected German chancellor in 2017?\",\"ShortName\":\"Merkel\",\"TickerSymbol\":\"MERKEL.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.10,\"BestBuyYesCost\":0.10,\"BestBuyNoCost\":0.93,\"BestSellYesCost\":0.07,\"BestSellNoCost\":0.90,\"LastClosePrice\":0.10},{\"ID\":3614,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_d87c6a74-372d-40b5-95d9-2f994738acf5.png\",\"URL\":\"https://www.predictit.org/Contract/3614/Will-Sigmar-Gabriel-be-elected-German-chancellor-in-2017\",\"Name\":\"Sigmar Gabriel\",\"LongName\":\"Will Sigmar Gabriel be elected German chancellor in 2017?\",\"ShortName\":\"Gabriel\",\"TickerSymbol\":\"GABRIEL.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3615,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_be043f00-72fb-479c-b5ae-37e51154935f.png\",\"URL\":\"https://www.predictit.org/Contract/3615/Will-Frank-Walter-Steinmeier-be-elected-German-chancellor-in-2017\",\"Name\":\"Frank-Walter Steinmeier\",\"LongName\":\"Will Frank-Walter Steinmeier be elected German chancellor in 2017?\",\"ShortName\":\"Steinmeier\",\"TickerSymbol\":\"STEINMEIER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3616,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_9d6f499c-245d-4cba-a1b1-537d1a41408d.png\",\"URL\":\"https://www.predictit.org/Contract/3616/Will-Martin-Schulz-be-elected-German-chancellor-in-2017\",\"Name\":\"Martin Schulz\",\"LongName\":\"Will Martin Schulz be elected German chancellor in 2017?\",\"ShortName\":\"Schulz\",\"TickerSymbol\":\"SCHULZ.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3617,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_a8e62e71-b5f3-4050-8340-c41204d58e30.png\",\"URL\":\"https://www.predictit.org/Contract/3617/Will-Wolfgang-Sch%C3%A4uble-be-elected-German-chancellor-in-2017\",\"Name\":\"Wolfgang Sch\\xc3\\xa4uble\",\"LongName\":\"Will Wolfgang Sch\\xc3\\xa4uble be elected German chancellor in 2017?\",\"ShortName\":\"Sch\\xc3\\xa4uble\",\"TickerSymbol\":\"SCHAUBLE.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3618,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_a41f6020-3a21-4679-ab04-1ff2c4e90e14.png\",\"URL\":\"https://www.predictit.org/Contract/3618/Will-Frauke-Petry-be-elected-German-chancellor-in-2017\",\"Name\":\"Frauke Petry\",\"LongName\":\"Will Frauke Petry be elected German chancellor in 2017?\",\"ShortName\":\"Petry\",\"TickerSymbol\":\"PETRY.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3619,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_18819f42-5bba-4640-96fb-e62ce4879cd0.png\",\"URL\":\"https://www.predictit.org/Contract/3619/Will-Thomas-de-Maizi%C3%A8re-be-elected-German-chancellor-in-2017\",\"Name\":\"Thomas de Maizi\\xc3\\xa8re\",\"LongName\":\"Will Thomas de Maizi\\xc3\\xa8re be elected German chancellor in 2017?\",\"ShortName\":\"de Maizi\\xc3\\xa8re\",\"TickerSymbol\":\"DEMAIZIERE.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3620,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_deffbe18-669e-45c6-9bb5-62ab61363d49.png\",\"URL\":\"https://www.predictit.org/Contract/3620/Will-Ursula-Von-der-Leyen-be-elected-German-chancellor-in-2017\",\"Name\":\"Ursula Von der Leyen\",\"LongName\":\"Will Ursula Von der Leyen be elected German chancellor in 2017?\",\"ShortName\":\"Von der Leyen\",\"TickerSymbol\":\"VONDERLEYEN.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3621,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_0b630af8-c76c-427c-91af-50a2e5f37bc4.png\",\"URL\":\"https://www.predictit.org/Contract/3621/Will-Christian-Lindner-be-elected-German-chancellor-in-2017\",\"Name\":\"Christian Lindner\",\"LongName\":\"Will Christian Lindner be elected German chancellor in 2017?\",\"ShortName\":\"Lindner\",\"TickerSymbol\":\"LINDNER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3622,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_e6aaf4d2-00c7-437c-82c0-d29336d75ad7.png\",\"URL\":\"https://www.predictit.org/Contract/3622/Will-Horst-Seehofer-be-elected-German-chancellor-in-2017\",\"Name\":\"Horst Seehofer\",\"LongName\":\"Will Horst Seehofer be elected German chancellor in 2017?\",\"ShortName\":\"Seehofer\",\"TickerSymbol\":\"SEEHOFER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3623,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_59a0cbcf-8bbf-4f39-ab30-175d9213732f.png\",\"URL\":\"https://www.predictit.org/Contract/3623/Will-Cem-%C3%96zdemir-be-elected-German-chancellor-in-2017\",\"Name\":\"Cem \\xc3\\x96zdemir\",\"LongName\":\"Will Cem \\xc3\\x96zdemir be elected German chancellor in 2017?\",\"ShortName\":\"\\xc3\\x96zdemir\",\"TickerSymbol\":\"OZDEMIR.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3624,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_076c33fc-39fc-414f-abf2-cc7dfa2e4dad.png\",\"URL\":\"https://www.predictit.org/Contract/3624/Will-Katja-Kipping-be-elected-German-chancellor-in-2017\",\"Name\":\"Katja Kipping\",\"LongName\":\"Will Katja Kipping be elected German chancellor in 2017?\",\"ShortName\":\"Kipping\",\"TickerSymbol\":\"KIPPING.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3625,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_84a1659d-63fd-4169-a5e7-49762df694e2.png\",\"URL\":\"https://www.predictit.org/Contract/3625/Will-Hannelore-Kraft-be-elected-German-chancellor-in-2017\",\"Name\":\"Hannelore Kraft\",\"LongName\":\"Will Hannelore Kraft be elected German chancellor in 2017?\",\"ShortName\":\"Kraft\",\"TickerSymbol\":\"KRAFT.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3626,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_80d9880b-1881-4079-9935-c0a5691876e9.png\",\"URL\":\"https://www.predictit.org/Contract/3626/Will-Peter-Altmaier-be-elected-German-chancellor-in-2017\",\"Name\":\"Peter Altmaier\",\"LongName\":\"Will Peter Altmaier be elected German chancellor in 2017?\",\"ShortName\":\"Altmaier\",\"TickerSymbol\":\"ALTMAIER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3627,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_cb11286d-c0b9-41fc-a4b0-3f52dccbd9bf.png\",\"URL\":\"https://www.predictit.org/Contract/3627/Will-Olaf-Scholz-be-elected-German-chancellor-in-2017\",\"Name\":\"Olaf Scholz\",\"LongName\":\"Will Olaf Scholz be elected German chancellor in 2017?\",\"ShortName\":\"Scholz\",\"TickerSymbol\":\"SCHOLZ.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":4866,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_72649d7f-0d79-4d34-a061-3920669d69c3.png\",\"URL\":\"https://www.predictit.org/Contract/4866/Will-Jens-Spahn-be-elected-German-chancellor-in-2017\",\"Name\":\"Jens Spahn\",\"LongName\":\"Will Jens Spahn be elected German chancellor in 2017?\",\"ShortName\":\"Spahn\",\"TickerSymbol\":\"SPAHN.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":4885,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_86dc58ff-2801-4174-acb6-3fea5f5b801f.png\",\"URL\":\"https://www.predictit.org/Contract/4885/Will-Leif-Erik-Holm-be-elected-German-chancellor-in-2017\",\"Name\":\"Leif-Erik Holm\",\"LongName\":\"Will Leif-Erik Holm be elected German chancellor in 2017?\",\"ShortName\":\"Holm\",\"TickerSymbol\":\"HOLM.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":4920,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_bc912c09-4d05-4d0a-9bba-d2dda6621b5d.png\",\"URL\":\"https://www.predictit.org/Contract/4920/Will-Karl-Theodor-zu-Guttenberg-be-elected-German-chancellor-in-2017\",\"Name\":\"Karl-Theodor zu Guttenberg\",\"LongName\":\"Will Karl-Theodor zu Guttenberg be elected German chancellor in 2017?\",\"ShortName\":\"Guttenberg\",\"TickerSymbol\":\"GUTTENBERG.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.02,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.98,\"LastClosePrice\":0.01},{\"ID\":7974,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_a2440597-a99e-4ab3-96cc-0c821bb978a0.png\",\"URL\":\"https://www.predictit.org/Contract/7974/Will-Alexander-Gauland-be-elected-German-chancellor-in-2017\",\"Name\":\"Alexander Gauland\",\"LongName\":\"Will Alexander Gauland be elected German chancellor in 2017?\",\"ShortName\":\"Gauland\",\"TickerSymbol\":\"GAUL.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":7975,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_9bec806a-8b80-47e2-bd03-c279a2b6b799.png\",\"URL\":\"https://www.predictit.org/Contract/7975/Will-Alice-Weidel-be-elected-German-chancellor-in-2017\",\"Name\":\"Alice Weidel\",\"LongName\":\"Will Alice Weidel be elected German chancellor in 2017?\",\"ShortName\":\"Weidel\",\"TickerSymbol\":\"WEID.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01}],\"TimeStamp\":\"2017-12-09T01:44:29.7878389\",\"Status\":\"Open\"}'"
</code>```

Edit 2: The admittedly messy code to produce the json file.

```<code>from urllib.request import Request, urlopen

q = Request('https://www.predictit.org/api/marketdata/all/')
q.add_header('Accept', 'application/json')

import json
import datetime

def saveData(data):
    now = datetime.datetime.now()
    path = 'json/PI ' + str(now) + '.json'
    path = path.replace(':','-') # No colons in file name
    with open(path, 'w') as outfile:
        json.dump(str(data), outfile, ensure_ascii=False)

import time
starttime=time.time()
while True:
    data = urlopen(q).read()
    saveData(data)
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))
</code>```

答:
How did you produce this file? It's not a JSON object, it's a JSON string containing a Python repr containing a string of your original JSON. Or something like that. Which you can tell because of all the extra backslashes and the leading b' character.

This works:

```<code>import json
from ast import literal_eval

file_data = open('test_file.json', 'r').read()
python_repr = json.loads(file_data)
json_string = literal_eval(python_repr)
actual_dict = json.loads(json_string.decode('utf-8'))
print(json.dumps(actual_dict, indent=4)) # finally.
</code>```

But how in tarnation did you manage this in the first place?

You can write it back as simple JSON instead of multi-encoded wtf too:

```<code>with open('output.json', 'wb') as out_file:
    json.dump(actual_dict, out_file, indent=4)
</code>```

EDIT for file write:

When you read the data from the website, it's a string containing the JSON object. You need to convert that into a Python dict first, then write it out. Without calling str on it again. That's how you're ending up with the triple-encoded mess. Using your code from above:

```<code>data = urlopen(q).read()
json_data = json.loads(data.decode('utf-8')) # DECODE THE STRING
with open('output.json', 'w') as out:
    json.dump(json_data, out, indent=4) # DO NOT CALL STR ON IT AGAIN
</code>```

Once you've written it cleanly, you can read it easily too:

```<code>json_loaded = json.load(open('output.json', 'r'))
</code>```

Which will load it up as a python dict.

I'd suggest learning a bit more about the difference between your data itself and various representations of that data.

EDIT2: Also note that if you just want to save the data, you can simply write what you're getting from the website directly into a file, without bothering with the json.load/dump roundtrip.

```<code>data = urlopen(q).read()
with open('output.json', 'w') as out:
    out.write(data)
</code>```

Body:
As far as I can tell, this code should work.

import json
with open('path', 'r') as infile:
    data = json.load(infile)
    print(json.dumps(data, indent=4))

But it doesn't. I get this:

"b'{\"Markets\":[{\"ID\":2461,\"Name\":\"Who will be elected German chancellor in 2017?\",\"ShortName\":\"Who will be elected German chancellor in 2017?\",\"TickerSymbol\":\"CHANCELLOR.GERMANY.2017\",\"Image\":\"https://az620379.vo.msecnd.net/images/Markets/5914fd50-9a60-46d1-ac5f-b36c2c4c9832.png\",\"URL\":\"https://www.predictit.org/Market/2461/Who-will-be-elected-German-chancellor-in-2017\",\"Contracts\":[{\"ID\":3613,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_494e673d-12cc-40c5-ab6a-2976c582303f.png\" ...

However, if I go to http://jsonprettyprint.com/ and give it the same data, I get pretty indentation. So the problem's with the code, not the data (though I don't understand why there are so many backslashes).

What am I doing wrong?

Edit: Sample data

"b'{\"ID\":2461,\"Name\":\"Who will be elected German chancellor in 2017?\",\"ShortName\":\"Who will be elected German chancellor in 2017?\",\"TickerSymbol\":\"CHANCELLOR.GERMANY.2017\",\"Image\":\"https://az620379.vo.msecnd.net/images/Markets/5914fd50-9a60-46d1-ac5f-b36c2c4c9832.png\",\"URL\":\"https://www.predictit.org/Market/2461/Who-will-be-elected-German-chancellor-in-2017\",\"Contracts\":[{\"ID\":3613,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_494e673d-12cc-40c5-ab6a-2976c582303f.png\",\"URL\":\"https://www.predictit.org/Contract/3613/Will-Angela-Merkel-be-elected-German-chancellor-in-2017\",\"Name\":\"Angela Merkel\",\"LongName\":\"Will Angela Merkel be elected German chancellor in 2017?\",\"ShortName\":\"Merkel\",\"TickerSymbol\":\"MERKEL.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.10,\"BestBuyYesCost\":0.10,\"BestBuyNoCost\":0.93,\"BestSellYesCost\":0.07,\"BestSellNoCost\":0.90,\"LastClosePrice\":0.10},{\"ID\":3614,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_d87c6a74-372d-40b5-95d9-2f994738acf5.png\",\"URL\":\"https://www.predictit.org/Contract/3614/Will-Sigmar-Gabriel-be-elected-German-chancellor-in-2017\",\"Name\":\"Sigmar Gabriel\",\"LongName\":\"Will Sigmar Gabriel be elected German chancellor in 2017?\",\"ShortName\":\"Gabriel\",\"TickerSymbol\":\"GABRIEL.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3615,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_be043f00-72fb-479c-b5ae-37e51154935f.png\",\"URL\":\"https://www.predictit.org/Contract/3615/Will-Frank-Walter-Steinmeier-be-elected-German-chancellor-in-2017\",\"Name\":\"Frank-Walter Steinmeier\",\"LongName\":\"Will Frank-Walter Steinmeier be elected German chancellor in 2017?\",\"ShortName\":\"Steinmeier\",\"TickerSymbol\":\"STEINMEIER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3616,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_9d6f499c-245d-4cba-a1b1-537d1a41408d.png\",\"URL\":\"https://www.predictit.org/Contract/3616/Will-Martin-Schulz-be-elected-German-chancellor-in-2017\",\"Name\":\"Martin Schulz\",\"LongName\":\"Will Martin Schulz be elected German chancellor in 2017?\",\"ShortName\":\"Schulz\",\"TickerSymbol\":\"SCHULZ.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3617,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_a8e62e71-b5f3-4050-8340-c41204d58e30.png\",\"URL\":\"https://www.predictit.org/Contract/3617/Will-Wolfgang-Sch%C3%A4uble-be-elected-German-chancellor-in-2017\",\"Name\":\"Wolfgang Sch\\xc3\\xa4uble\",\"LongName\":\"Will Wolfgang Sch\\xc3\\xa4uble be elected German chancellor in 2017?\",\"ShortName\":\"Sch\\xc3\\xa4uble\",\"TickerSymbol\":\"SCHAUBLE.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3618,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_a41f6020-3a21-4679-ab04-1ff2c4e90e14.png\",\"URL\":\"https://www.predictit.org/Contract/3618/Will-Frauke-Petry-be-elected-German-chancellor-in-2017\",\"Name\":\"Frauke Petry\",\"LongName\":\"Will Frauke Petry be elected German chancellor in 2017?\",\"ShortName\":\"Petry\",\"TickerSymbol\":\"PETRY.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3619,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_18819f42-5bba-4640-96fb-e62ce4879cd0.png\",\"URL\":\"https://www.predictit.org/Contract/3619/Will-Thomas-de-Maizi%C3%A8re-be-elected-German-chancellor-in-2017\",\"Name\":\"Thomas de Maizi\\xc3\\xa8re\",\"LongName\":\"Will Thomas de Maizi\\xc3\\xa8re be elected German chancellor in 2017?\",\"ShortName\":\"de Maizi\\xc3\\xa8re\",\"TickerSymbol\":\"DEMAIZIERE.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3620,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_deffbe18-669e-45c6-9bb5-62ab61363d49.png\",\"URL\":\"https://www.predictit.org/Contract/3620/Will-Ursula-Von-der-Leyen-be-elected-German-chancellor-in-2017\",\"Name\":\"Ursula Von der Leyen\",\"LongName\":\"Will Ursula Von der Leyen be elected German chancellor in 2017?\",\"ShortName\":\"Von der Leyen\",\"TickerSymbol\":\"VONDERLEYEN.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3621,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_0b630af8-c76c-427c-91af-50a2e5f37bc4.png\",\"URL\":\"https://www.predictit.org/Contract/3621/Will-Christian-Lindner-be-elected-German-chancellor-in-2017\",\"Name\":\"Christian Lindner\",\"LongName\":\"Will Christian Lindner be elected German chancellor in 2017?\",\"ShortName\":\"Lindner\",\"TickerSymbol\":\"LINDNER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3622,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_e6aaf4d2-00c7-437c-82c0-d29336d75ad7.png\",\"URL\":\"https://www.predictit.org/Contract/3622/Will-Horst-Seehofer-be-elected-German-chancellor-in-2017\",\"Name\":\"Horst Seehofer\",\"LongName\":\"Will Horst Seehofer be elected German chancellor in 2017?\",\"ShortName\":\"Seehofer\",\"TickerSymbol\":\"SEEHOFER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3623,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_59a0cbcf-8bbf-4f39-ab30-175d9213732f.png\",\"URL\":\"https://www.predictit.org/Contract/3623/Will-Cem-%C3%96zdemir-be-elected-German-chancellor-in-2017\",\"Name\":\"Cem \\xc3\\x96zdemir\",\"LongName\":\"Will Cem \\xc3\\x96zdemir be elected German chancellor in 2017?\",\"ShortName\":\"\\xc3\\x96zdemir\",\"TickerSymbol\":\"OZDEMIR.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3624,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_076c33fc-39fc-414f-abf2-cc7dfa2e4dad.png\",\"URL\":\"https://www.predictit.org/Contract/3624/Will-Katja-Kipping-be-elected-German-chancellor-in-2017\",\"Name\":\"Katja Kipping\",\"LongName\":\"Will Katja Kipping be elected German chancellor in 2017?\",\"ShortName\":\"Kipping\",\"TickerSymbol\":\"KIPPING.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3625,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_84a1659d-63fd-4169-a5e7-49762df694e2.png\",\"URL\":\"https://www.predictit.org/Contract/3625/Will-Hannelore-Kraft-be-elected-German-chancellor-in-2017\",\"Name\":\"Hannelore Kraft\",\"LongName\":\"Will Hannelore Kraft be elected German chancellor in 2017?\",\"ShortName\":\"Kraft\",\"TickerSymbol\":\"KRAFT.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3626,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_80d9880b-1881-4079-9935-c0a5691876e9.png\",\"URL\":\"https://www.predictit.org/Contract/3626/Will-Peter-Altmaier-be-elected-German-chancellor-in-2017\",\"Name\":\"Peter Altmaier\",\"LongName\":\"Will Peter Altmaier be elected German chancellor in 2017?\",\"ShortName\":\"Altmaier\",\"TickerSymbol\":\"ALTMAIER.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":3627,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_cb11286d-c0b9-41fc-a4b0-3f52dccbd9bf.png\",\"URL\":\"https://www.predictit.org/Contract/3627/Will-Olaf-Scholz-be-elected-German-chancellor-in-2017\",\"Name\":\"Olaf Scholz\",\"LongName\":\"Will Olaf Scholz be elected German chancellor in 2017?\",\"ShortName\":\"Scholz\",\"TickerSymbol\":\"SCHOLZ.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":4866,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_72649d7f-0d79-4d34-a061-3920669d69c3.png\",\"URL\":\"https://www.predictit.org/Contract/4866/Will-Jens-Spahn-be-elected-German-chancellor-in-2017\",\"Name\":\"Jens Spahn\",\"LongName\":\"Will Jens Spahn be elected German chancellor in 2017?\",\"ShortName\":\"Spahn\",\"TickerSymbol\":\"SPAHN.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":4885,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_86dc58ff-2801-4174-acb6-3fea5f5b801f.png\",\"URL\":\"https://www.predictit.org/Contract/4885/Will-Leif-Erik-Holm-be-elected-German-chancellor-in-2017\",\"Name\":\"Leif-Erik Holm\",\"LongName\":\"Will Leif-Erik Holm be elected German chancellor in 2017?\",\"ShortName\":\"Holm\",\"TickerSymbol\":\"HOLM.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":4920,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_bc912c09-4d05-4d0a-9bba-d2dda6621b5d.png\",\"URL\":\"https://www.predictit.org/Contract/4920/Will-Karl-Theodor-zu-Guttenberg-be-elected-German-chancellor-in-2017\",\"Name\":\"Karl-Theodor zu Guttenberg\",\"LongName\":\"Will Karl-Theodor zu Guttenberg be elected German chancellor in 2017?\",\"ShortName\":\"Guttenberg\",\"TickerSymbol\":\"GUTTENBERG.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.02,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.98,\"LastClosePrice\":0.01},{\"ID\":7974,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_a2440597-a99e-4ab3-96cc-0c821bb978a0.png\",\"URL\":\"https://www.predictit.org/Contract/7974/Will-Alexander-Gauland-be-elected-German-chancellor-in-2017\",\"Name\":\"Alexander Gauland\",\"LongName\":\"Will Alexander Gauland be elected German chancellor in 2017?\",\"ShortName\":\"Gauland\",\"TickerSymbol\":\"GAUL.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01},{\"ID\":7975,\"DateEnd\":\"N/A\",\"Image\":\"https://az620379.vo.msecnd.net/images/Contracts/small_9bec806a-8b80-47e2-bd03-c279a2b6b799.png\",\"URL\":\"https://www.predictit.org/Contract/7975/Will-Alice-Weidel-be-elected-German-chancellor-in-2017\",\"Name\":\"Alice Weidel\",\"LongName\":\"Will Alice Weidel be elected German chancellor in 2017?\",\"ShortName\":\"Weidel\",\"TickerSymbol\":\"WEID.CHANCELLOR.GERMANY.2017\",\"Status\":\"Open\",\"LastTradePrice\":0.01,\"BestBuyYesCost\":0.01,\"BestBuyNoCost\":null,\"BestSellYesCost\":null,\"BestSellNoCost\":0.99,\"LastClosePrice\":0.01}],\"TimeStamp\":\"2017-12-09T01:44:29.7878389\",\"Status\":\"Open\"}'"

Edit 2: The admittedly messy code to produce the json file.

from urllib.request import Request, urlopen

q = Request('https://www.predictit.org/api/marketdata/all/')
q.add_header('Accept', 'application/json')

import json
import datetime

def saveData(data):
    now = datetime.datetime.now()
    path = 'json/PI ' + str(now) + '.json'
    path = path.replace(':','-') # No colons in file name
    with open(path, 'w') as outfile:
        json.dump(str(data), outfile, ensure_ascii=False)

import time
starttime=time.time()
while True:
    data = urlopen(q).read()
    saveData(data)
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))

Body:
How did you produce this file? It's not a JSON object, it's a JSON string containing a Python repr containing a string of your original JSON. Or something like that. Which you can tell because of all the extra backslashes and the leading b' character.

This works:

import json
from ast import literal_eval

file_data = open('test_file.json', 'r').read()
python_repr = json.loads(file_data)
json_string = literal_eval(python_repr)
actual_dict = json.loads(json_string.decode('utf-8'))
print(json.dumps(actual_dict, indent=4)) # finally.

But how in tarnation did you manage this in the first place?

You can write it back as simple JSON instead of multi-encoded wtf too:

with open('output.json', 'wb') as out_file:
    json.dump(actual_dict, out_file, indent=4)

EDIT for file write:

When you read the data from the website, it's a string containing the JSON object. You need to convert that into a Python dict first, then write it out. Without calling str on it again. That's how you're ending up with the triple-encoded mess. Using your code from above:

data = urlopen(q).read()
json_data = json.loads(data.decode('utf-8')) # DECODE THE STRING
with open('output.json', 'w') as out:
    json.dump(json_data, out, indent=4) # DO NOT CALL STR ON IT AGAIN

Once you've written it cleanly, you can read it easily too:

json_loaded = json.load(open('output.json', 'r'))

Which will load it up as a python dict.

I'd suggest learning a bit more about the difference between your data itself and various representations of that data.

EDIT2: Also note that if you just want to save the data, you can simply write what you're getting from the website directly into a file, without bothering with the json.load/dump roundtrip.

data = urlopen(q).read()
with open('output.json', 'w') as out:
    out.write(data)


来源: stackexchange

问:
Method return statement vs try-catch
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}
```

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!

答:
What you want to achieve can be achieved  by below sample code

As ArithmeticException is RuntimeException and in case of j=0 exception will be propagated to caller function.

```<code>int methodName(int i, int j) {
                    return i/j;
               }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Method return statement vs try-catch

Body:
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!

Body:
What you want to achieve can be achieved  by below sample code

As ArithmeticException is RuntimeException and in case of j=0 exception will be propagated to caller function.

int methodName(int i, int j) {
                    return i/j;
               }

ContentLicense: CC BY-SA 3.0


问:
Writing DCG for strings containing same number of specific digits - Prolog
I'm working on writing a DCG that would take strings in the form of u2v where u and v do not have to be of equal length and the number of 0's in u must be the same as the number of 1's in v.

So far I've been able to write several grammars that work on paper but when I code them and try a query I typically end up with a loop somewhere. This is the closest I've been able to get:

```<code>s-->[2].
s-->u,[0],n.
s-->u,s,v.
n-->s,[1],v.
u-->[1],u.
u-->[].
v-->[0],v.
v-->[].
</code>```

I can get the correct answers for the query s([0,1,1,2,0,0,1,0],N). which would be:

```<code>N = [] ;
N = [0]
</code>```

But it doesn't terminate with false after as it should. Instead it just repeats those answers. My knowledge of Prolog is pretty limited and I've been mostly self teaching from LPN, so I'm guessing this is more an issue of me not understanding how Prolog evaluates these kinds of things. If someone could explain why it won't terminate, that would be most helpful.

答:
What an interesting problem!

What immediately comes to mind for me is that you want to utilize the structure of your grammar. For instance, to match parentheses you have to do something along the lines of this:

```<code>expr --> [].
expr --> ['('], expr, [')'].
</code>```

That way, either you have whatever goes between parens, or you have a left and a right paren, every time.

I don't see an obvious way to achieve this kind of breakdown with this problem. There might be a way, but I don't see what it is. However, DCGs have the almost-supernatural ability to propagate information around between different locations in the parse, thanks to the way Prolog's variables work, and that's by creating parameters to the DCG rules, like so:

```<code>rule(Stuff) --> ...
</code>```

Anyway, the next snafu is that you're wanting to count something, which means arithmetic might be involved. However! We can cheat a little bit by using Peano numbers, since all we really care about is that they happen to equal each other on both sides, we don't really need to pass the result back to the user.

Without further ado, here's the solution I came up with:

```<code>u2v    --> u2v(_).
u2v(N) --> u(N), [2], v(N).

u(0)    --> [].
u(s(N)) --> [0], u(N).
u(N)    --> [X], { member(X, [1,2,3,4,5,6,7,8,9]) }, u(N).

v(0)    --> [].
v(s(N)) --> [1], v(N).
v(N)    --> [X], { member(X, [0,2,3,4,5,6,7,8,9]) }, v(N).
</code>```

I'm sure there are nicer ways to write this code (there may even be totally superior approaches) but this one does seem to work in my limited testing. It would even generate, except for the pesky unbounded recursion on both sides.

The crux of the solution is this line:

```<code>u2v(N) --> u(N), [2], v(N).
</code>```

In fact, you don't need to keep the N, but I found it useful for debugging. The essential thing here is that u(N) matches v(N). Then both u//1 and v//1 have the same structure: first, a base-case of matching nothing, then an inductive case that matches the desired number and increments the count, Peano-style (0, s(0), s(s(0)), s(s(s(0))), ...), and then an alternate inductive case that matches the other digits and propagates the previous count forward.

It would probably be possible to do this with succ/2 instead of this, but I worry about where one would need to place the bit of pure Prolog to make it go. Going this route with Peano seemed simpler to me. (There's probably even a clpfd approach.)

Anyway, I hope this helps!

Body:
I'm working on writing a DCG that would take strings in the form of u2v where u and v do not have to be of equal length and the number of 0's in u must be the same as the number of 1's in v.

So far I've been able to write several grammars that work on paper but when I code them and try a query I typically end up with a loop somewhere. This is the closest I've been able to get:

s-->[2].
s-->u,[0],n.
s-->u,s,v.
n-->s,[1],v.
u-->[1],u.
u-->[].
v-->[0],v.
v-->[].

I can get the correct answers for the query s([0,1,1,2,0,0,1,0],N). which would be:

N = [] ;
N = [0]

But it doesn't terminate with false after as it should. Instead it just repeats those answers. My knowledge of Prolog is pretty limited and I've been mostly self teaching from LPN, so I'm guessing this is more an issue of me not understanding how Prolog evaluates these kinds of things. If someone could explain why it won't terminate, that would be most helpful.

Body:
What an interesting problem!

What immediately comes to mind for me is that you want to utilize the structure of your grammar. For instance, to match parentheses you have to do something along the lines of this:

expr --> [].
expr --> ['('], expr, [')'].

That way, either you have whatever goes between parens, or you have a left and a right paren, every time.

I don't see an obvious way to achieve this kind of breakdown with this problem. There might be a way, but I don't see what it is. However, DCGs have the almost-supernatural ability to propagate information around between different locations in the parse, thanks to the way Prolog's variables work, and that's by creating parameters to the DCG rules, like so:

rule(Stuff) --> ...

Anyway, the next snafu is that you're wanting to count something, which means arithmetic might be involved. However! We can cheat a little bit by using Peano numbers, since all we really care about is that they happen to equal each other on both sides, we don't really need to pass the result back to the user.

Without further ado, here's the solution I came up with:

u2v    --> u2v(_).
u2v(N) --> u(N), [2], v(N).

u(0)    --> [].
u(s(N)) --> [0], u(N).
u(N)    --> [X], { member(X, [1,2,3,4,5,6,7,8,9]) }, u(N).

v(0)    --> [].
v(s(N)) --> [1], v(N).
v(N)    --> [X], { member(X, [0,2,3,4,5,6,7,8,9]) }, v(N).

I'm sure there are nicer ways to write this code (there may even be totally superior approaches) but this one does seem to work in my limited testing. It would even generate, except for the pesky unbounded recursion on both sides.

The crux of the solution is this line:

u2v(N) --> u(N), [2], v(N).

In fact, you don't need to keep the N, but I found it useful for debugging. The essential thing here is that u(N) matches v(N). Then both u//1 and v//1 have the same structure: first, a base-case of matching nothing, then an inductive case that matches the desired number and increments the count, Peano-style (0, s(0), s(s(0)), s(s(s(0))), ...), and then an alternate inductive case that matches the other digits and propagates the previous count forward.

It would probably be possible to do this with succ/2 instead of this, but I worry about where one would need to place the bit of pure Prolog to make it go. Going this route with Peano seemed simpler to me. (There's probably even a clpfd approach.)

Anyway, I hope this helps!


问:
Make woocommerce product search only search certain fields
I've just built a specialist bookshop website using Woocommerce (2.1.11) with their free Mystile theme. The products (books) have several custom fields added including isbn, author, publisher etc.

I would like now to amend the default product search facility to ONLY search the custom fields (as opposed to just including custom fields in the search). Does anyone know how to do that?

Thanks

答:
Custom code to search using name and product description (just paste this code in function.php)</p>
```<code>// Join in your where condition

function cf_search_join( $join ) {

    global $wpdb;

    if ( is_search() ) {
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }

    return $join;
}

add_filter('posts_join', 'cf_search_join' );

function cf_search_distinct( $where ) {

    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}

add_filter( 'posts_distinct', 'cf_search_distinct' );

// Search by Post Title

function search_by_id_only( $search, &$wp_query )
{

    //remove_filter( 'posts_search', 'vc_search_by_title_only', 500, 2 );

    global $wpdb,$wp_the_query,$wp;

    if ( empty( $search ) ){
        return $search; // skip processing - no search term in query
    }
        $q = $wp_query->query_vars;

        $n = ! empty( $q['exact'] ) ? '' : '%';
        $search = $searchand = '';

        foreach ( (array) $q['search_terms'] as $term ) {

            $term = $wpdb->esc_like( $term );
      $n = '%';

            $like = $n . $term . $n;
            $search .= $wpdb->prepare( "{$searchand}($wpdb->posts.ID LIKE %s)", $like );

            $searchand = ' OR ';

                            $search .= $wpdb->prepare( "{$searchand}($wpdb->posts.post_title LIKE %s)", $like );
            $searchand = ' OR ';

    $search .= $wpdb->prepare( "{$searchand}($wpdb->postmeta.meta_key = '_sku' AND CAST($wpdb->postmeta.meta_value AS CHAR) LIKE %s)", $like );

            //$search .= $wpdb->prepare("{$searchand} (select * from {$wpdb->postmeta} where post_id={$wpdb->posts}.ID and meta_key in ('_sku') and meta_value like %s )",$like);
            $searchand = ' OR ';

    //$search .= $wpdb->prepare( "{$searchand}($wpdb->posts.post_content LIKE %s)", $like );

    //      $searchand = ' OR ';
        }
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";

        }
    return $search;

}

if( !is_admin() ){

  add_filter( 'posts_search', 'search_by_id_only', 500, 2 );

}
</code>```

Body:
Custom code to search using name and product description (just paste this code in function.php)

// Join in your where condition

function cf_search_join( $join ) {

    global $wpdb;

    if ( is_search() ) {
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }

    return $join;
}

add_filter('posts_join', 'cf_search_join' );

function cf_search_distinct( $where ) {

    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}

add_filter( 'posts_distinct', 'cf_search_distinct' );

// Search by Post Title

function search_by_id_only( $search, &$wp_query )
{

    //remove_filter( 'posts_search', 'vc_search_by_title_only', 500, 2 );

    global $wpdb,$wp_the_query,$wp;

    if ( empty( $search ) ){
        return $search; // skip processing - no search term in query
    }
        $q = $wp_query->query_vars;

        $n = ! empty( $q['exact'] ) ? '' : '%';
        $search = $searchand = '';

        foreach ( (array) $q['search_terms'] as $term ) {

            $term = $wpdb->esc_like( $term );
      $n = '%';

            $like = $n . $term . $n;
            $search .= $wpdb->prepare( "{$searchand}($wpdb->posts.ID LIKE %s)", $like );

            $searchand = ' OR ';

                            $search .= $wpdb->prepare( "{$searchand}($wpdb->posts.post_title LIKE %s)", $like );
            $searchand = ' OR ';

    $search .= $wpdb->prepare( "{$searchand}($wpdb->postmeta.meta_key = '_sku' AND CAST($wpdb->postmeta.meta_value AS CHAR) LIKE %s)", $like );

            //$search .= $wpdb->prepare("{$searchand} (select * from {$wpdb->postmeta} where post_id={$wpdb->posts}.ID and meta_key in ('_sku') and meta_value like %s )",$like);
            $searchand = ' OR ';

    //$search .= $wpdb->prepare( "{$searchand}($wpdb->posts.post_content LIKE %s)", $like );

    //      $searchand = ' OR ';
        }
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";

        }
    return $search;

}

if( !is_admin() ){

  add_filter( 'posts_search', 'search_by_id_only', 500, 2 );

}


问:
Is it possible to fetch a cursor into a record using rowtype?
I'm always getting

```<code>PLS-00597: expression 'V_EMP_REC' in the INTO list is of wrong type
</code>```

Here's the package, i'm using default HR schema

```<code>CREATE OR REPLACE PACKAGE EMP_PKG AS
  TYPE T_EMP_REC IS RECORD (
    V_EMP_TAB EMPLOYEES%ROWTYPE,
    V_DEPT_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE
  );

  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE) RETURN T_EMP_REC;
END EMP_PKG;
/
CREATE OR REPLACE PACKAGE BODY EMP_PKG AS
  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE)
  RETURN T_EMP_REC
  AS
    CURSOR V_EMP_CUR IS
      SELECT E.*, D.DEPARTMENT_NAME
      FROM EMPLOYEES E, DEPARTMENTS D
      WHERE E.EMPLOYEE_ID = P_EMP_ID
      AND E.DEPARTMENT_ID = D.DEPARTMENT_ID;

  V_EMP_REC T_EMP_REC;
  BEGIN
    OPEN V_EMP_CUR;
    FETCH V_EMP_CUR INTO V_EMP_REC;
    CLOSE V_EMP_CUR;

  RETURN V_EMP_REC;
  END GET_EMP;
END EMP_PKG;
</code>```

The number of columns matches and I'm always using the same types as the table. I don't know if this approach is possible instead of declaring every column in the record type.

答:
As Guillaume suggested, explicitly mention the column names. And when you call the function, you receive T_EMP_REC record. Now each Variable can be accesses as T_EMP_REC.employees_col1, T_EMP_REC.employees_col2, T_EMP_REC.department_col1 etc.

Could'n reply on your comment on his answer, so answered this way.

Body:
I'm always getting

PLS-00597: expression 'V_EMP_REC' in the INTO list is of wrong type

Here's the package, i'm using default HR schema

CREATE OR REPLACE PACKAGE EMP_PKG AS
  TYPE T_EMP_REC IS RECORD (
    V_EMP_TAB EMPLOYEES%ROWTYPE,
    V_DEPT_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE
  );

  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE) RETURN T_EMP_REC;
END EMP_PKG;
/
CREATE OR REPLACE PACKAGE BODY EMP_PKG AS
  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE)
  RETURN T_EMP_REC
  AS
    CURSOR V_EMP_CUR IS
      SELECT E.*, D.DEPARTMENT_NAME
      FROM EMPLOYEES E, DEPARTMENTS D
      WHERE E.EMPLOYEE_ID = P_EMP_ID
      AND E.DEPARTMENT_ID = D.DEPARTMENT_ID;

  V_EMP_REC T_EMP_REC;
  BEGIN
    OPEN V_EMP_CUR;
    FETCH V_EMP_CUR INTO V_EMP_REC;
    CLOSE V_EMP_CUR;

  RETURN V_EMP_REC;
  END GET_EMP;
END EMP_PKG;

The number of columns matches and I'm always using the same types as the table. I don't know if this approach is possible instead of declaring every column in the record type.


问:
Help with (somewhat simple) MySQL JOIN
Consider I have three tables:

Movies (movie 1, movie 2, etc)

Categories (action, suspense, etc)

Movies_Categories (movie 1 -> action, movie 1 -> suspense, movie 2 -> suspense, etc)

How could I select only the movies that belong or don't belong to a specific category using only 1 query?

Thanks!

答:
```<code>    SELECT m.*,
           IF(mc.movie_id IS NULL, 'doesnt belong', 'belongs')
      FROM Movies m
 LEFT JOIN Movies_Categories mc ON mc.movie_id = m.id
                               AND mc.category_id = (SELECT id
                                                       FROM categories
                                                      WHERE name = 'action')
</code>```

ContentLicense: CC BY-SA 2.5

Title: Help with (somewhat simple) MySQL JOIN


问:
Task not in a faulted state when an exception is thrown
I can't seem to figure out why my task is not in a faulted state when an exception is thrown in the following sample (assume engine.Send(...) throws an exception):

```<code>       var receiverTask = new Task<Task>(async () => {
            result = await Task.FromResult(engine.Send(someObject));
        });
        receiverTask.Start();
        receiverTask.Wait();
</code>```

if I do receiverTask.IsFaulted after the receiverTask.Wait() it returns false instead of true as I would expect.

I have been reading that I need to use something like the following construct:

```<code>receiverTask.ContinueWith(t => { /* error handling */ },
    TaskContinuationOptions.OnlyOnFaulted);
</code>```

But I can't seem to figure out how to integrate this into the sample code. Do I call this before the Start()? before the Wait()?

I would like the calling program to somehow be aware that the receiverTask has thrown an exception and failed. Any pointers?

答:
If I correctly understand this context, you could leave out the .Start() and use .Wait() somewhat differently.

(I don't know what your engine.Send(someObject) method is, so I have to assume.)

Let's say your method returns a bool (it doesn't matter, but just to write something down.

If it is synchronous, the returned Task could be:

```<code> Task<bool> receiverTask = Task<bool>.Run(async () =>
            await Task<bool>.FromResult(engine.Send(someObject)));
</code>```

or

```<code> Task<bool> receiverTask = Task.Factory.StartNew(async delegate
 {
    bool _result = await Task<bool>.FromResult(engine.Send(someObject));
    return _result;
 }, TaskScheduler.Default).Unwrap();
</code>```

If it is asynchronous, the returned Task could be:

```<code> Task<bool> receiverTask = Task.Run(async () =>
            await engine.Send(someObject));
</code>```

or

```<code> Task<bool> receiverTask = Task.Factory.StartNew(async delegate
 {
    bool _result = await engine.Send(someObject);
    return _result;
 }, TaskScheduler.Current).Unwrap<bool>();
</code>```

(However, all these are blocking if there's no other async/await declaration).

Once your Task is scheduled, some Continuation condition can be defined to evaluate its status.

If the Task is in some faulty status (canceled, aborted etc.) its .IsCompleted property reports true, but the .Status property is not TaskStatus.RanToCompletion.

```<code> receiverTask.ContinueWith(t =>
 {
    //Continue on faulted
    Console.WriteLine(receiverTask.GetAwaiter().IsCompleted);
    if (receiverTask.IsFaulted)
       Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
 }, TaskContinuationOptions.OnlyOnFaulted).Wait(0);

 receiverTask.ContinueWith(t =>
 {
    //Continue on canceled
    Console.WriteLine(receiverTask.GetAwaiter().IsCompleted);
    if (receiverTask.IsCanceled)
       Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
 }, TaskContinuationOptions.OnlyOnCanceled).Wait(0);

 receiverTask.ContinueWith(t =>
 {
    //Standard behaviour
    Console.WriteLine(receiverTask.GetAwaiter().IsCompleted);
    Console.WriteLine(receiverTask.Status.ToString());
 }, TaskContinuationOptions.None).Wait();

 //This writes only if no errors have been raised
 if (receiverTask.Status == TaskStatus.RanToCompletion)
    Console.WriteLine("Completed: {0}  Result: {1}", receiverTask.GetAwaiter().IsCompleted, receiverTask.Result);
</code>```

But you might also use a Try/Catch block:

```<code> try
 {
    receiverTask.Wait();

    if (receiverTask.Status == TaskStatus.RanToCompletion)
       Console.WriteLine("Completed: {0}  Result: {1}", receiverTask.GetAwaiter().IsCompleted, receiverTask.Result);
 }
 catch (Exception)
 {
    receiverTask.ContinueWith(t =>
    {
       //With continuation
       if (receiverTask.IsFaulted)
          Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
    }, TaskContinuationOptions.OnlyOnFaulted);

       //or without
       //if (receiverTask.IsCanceled)
       //Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
 }
</code>```

Body:
I can't seem to figure out why my task is not in a faulted state when an exception is thrown in the following sample (assume engine.Send(...) throws an exception):

       var receiverTask = new Task<Task>(async () => {
            result = await Task.FromResult(engine.Send(someObject));
        });
        receiverTask.Start();
        receiverTask.Wait();

if I do receiverTask.IsFaulted after the receiverTask.Wait() it returns false instead of true as I would expect.

I have been reading that I need to use something like the following construct:

receiverTask.ContinueWith(t => { /* error handling */ },
    TaskContinuationOptions.OnlyOnFaulted);

But I can't seem to figure out how to integrate this into the sample code. Do I call this before the Start()? before the Wait()?

I would like the calling program to somehow be aware that the receiverTask has thrown an exception and failed. Any pointers?

Body:
If I correctly understand this context, you could leave out the .Start() and use .Wait() somewhat differently.

(I don't know what your engine.Send(someObject) method is, so I have to assume.)

Let's say your method returns a bool (it doesn't matter, but just to write something down.

If it is synchronous, the returned Task could be:

 Task<bool> receiverTask = Task<bool>.Run(async () =>
            await Task<bool>.FromResult(engine.Send(someObject)));

or

 Task<bool> receiverTask = Task.Factory.StartNew(async delegate
 {
    bool _result = await Task<bool>.FromResult(engine.Send(someObject));
    return _result;
 }, TaskScheduler.Default).Unwrap();

If it is asynchronous, the returned Task could be:

 Task<bool> receiverTask = Task.Run(async () =>
            await engine.Send(someObject));

or

 Task<bool> receiverTask = Task.Factory.StartNew(async delegate
 {
    bool _result = await engine.Send(someObject);
    return _result;
 }, TaskScheduler.Current).Unwrap<bool>();

(However, all these are blocking if there's no other async/await declaration).

Once your Task is scheduled, some Continuation condition can be defined to evaluate its status.

If the Task is in some faulty status (canceled, aborted etc.) its .IsCompleted property reports true, but the .Status property is not TaskStatus.RanToCompletion.

 receiverTask.ContinueWith(t =>
 {
    //Continue on faulted
    Console.WriteLine(receiverTask.GetAwaiter().IsCompleted);
    if (receiverTask.IsFaulted)
       Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
 }, TaskContinuationOptions.OnlyOnFaulted).Wait(0);

 receiverTask.ContinueWith(t =>
 {
    //Continue on canceled
    Console.WriteLine(receiverTask.GetAwaiter().IsCompleted);
    if (receiverTask.IsCanceled)
       Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
 }, TaskContinuationOptions.OnlyOnCanceled).Wait(0);

 receiverTask.ContinueWith(t =>
 {
    //Standard behaviour
    Console.WriteLine(receiverTask.GetAwaiter().IsCompleted);
    Console.WriteLine(receiverTask.Status.ToString());
 }, TaskContinuationOptions.None).Wait();

 //This writes only if no errors have been raised
 if (receiverTask.Status == TaskStatus.RanToCompletion)
    Console.WriteLine("Completed: {0}  Result: {1}", receiverTask.GetAwaiter().IsCompleted, receiverTask.Result);

But you might also use a Try/Catch block:

 try
 {
    receiverTask.Wait();

    if (receiverTask.Status == TaskStatus.RanToCompletion)
       Console.WriteLine("Completed: {0}  Result: {1}", receiverTask.GetAwaiter().IsCompleted, receiverTask.Result);
 }
 catch (Exception)
 {
    receiverTask.ContinueWith(t =>
    {
       //With continuation
       if (receiverTask.IsFaulted)
          Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
    }, TaskContinuationOptions.OnlyOnFaulted);

       //or without
       //if (receiverTask.IsCanceled)
       //Console.WriteLine(receiverTask.Exception.InnerExceptions[0].Message);
 }


问:
How to change action link as per drop-down list?
```<code><form action="result.php" method="POST">
<select name="strm">
  <option disabled="disabled" selected="selected" value="">Select Your Stream</option>
  <option value="ARTS">Arts</option>
  <option value="COMMERCE">Commerce</option>
  <option value="SCIENCE">Science</option>
</select>

<input maxlength="4" minlength="4" name="rollcode" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Center Code')" placeholder="Center Code" required="" type="text" />

<input maxlength="5" minlength="5" name="rollno" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Roll No')" placeholder="Roll No" required="" type="text" />

<input type="submit" value="Get Result" />
</code>```

Above mentioned a form where I want to change my action link as per selection of Arts, Commrence or Science. In other words Now the default php link contains all 3 stream's information in one but I want to create separate database for each and searchable from one form. Is there any way to do this?

答:
Making use of pure Javascript, not Jquery,
it occurs to me that you can use the data-action attribute to specify the action of the form, and then with elem.options [elem.selectedIndex] we obtain the selected option to subsequently obtain the data-action attribute

var select = document.getElementById('actions');
select.onchange=setNewAction;

function setNewAction(event) {
    var elem = event.target;
    if(!elem.value) alert('Please Select One');
    else {
      elem.form.action = elem.options[elem.selectedIndex].getAttribute('data-action');
      console.log(elem.form.action);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="result.php" method="POST">
<select name="strm" id="actions">
  <option disabled="disabled" selected="selected" value="">Select Your Stream</option>
  <option value="ARTS" data-action="arts.php">Arts</option>
  <option value="COMMERCE" data-action="commerce.php">Commerce</option>
  <option value="SCIENCE" data-action="science.php">Science</option>
</select>
</form></code>```

Body:
<form action="result.php" method="POST">
<select name="strm">
  <option disabled="disabled" selected="selected" value="">Select Your Stream</option>
  <option value="ARTS">Arts</option>
  <option value="COMMERCE">Commerce</option>
  <option value="SCIENCE">Science</option>
</select>

<input maxlength="4" minlength="4" name="rollcode" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Center Code')" placeholder="Center Code" required="" type="text" />

<input maxlength="5" minlength="5" name="rollno" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Roll No')" placeholder="Roll No" required="" type="text" />

<input type="submit" value="Get Result" />

Above mentioned a form where I want to change my action link as per selection of Arts, Commrence or Science. In other words Now the default php link contains all 3 stream's information in one but I want to create separate database for each and searchable from one form. Is there any way to do this?

Body:
Making use of pure Javascript, not Jquery,
it occurs to me that you can use the data-action attribute to specify the action of the form, and then with elem.options [elem.selectedIndex] we obtain the selected option to subsequently obtain the data-action attribute

var select = document.getElementById('actions');
select.onchange=setNewAction;

function setNewAction(event) {
    var elem = event.target;
    if(!elem.value) alert('Please Select One');
    else {
      elem.form.action = elem.options[elem.selectedIndex].getAttribute('data-action');
      console.log(elem.form.action);
    }
}

<form action="result.php" method="POST">
<select name="strm" id="actions">
  <option disabled="disabled" selected="selected" value="">Select Your Stream</option>
  <option value="ARTS" data-action="arts.php">Arts</option>
  <option value="COMMERCE" data-action="commerce.php">Commerce</option>
  <option value="SCIENCE" data-action="science.php">Science</option>
</select>
</form>


问:
javascript array - comparing elements with other elements within the same array
Am comparing javascript array of elements with other elements within the same array. If elements are same means, i have to give same number for all the common elements. If the elements are different i have to give some different number for all the non identical elements in another element.

for example :

```<code>Array structure = [{Location, Date, Number}]

array = [{ 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1},
         { 'NY','2017-12-01',2},
         { 'NY','2016-10-01',3},
         { 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1}]
</code>```

In this array 'Number' is dynamic element, It should be populate on the following rules.

```<code>key1 = location + '-' +date;
</code>```

Consider Key1 is the first element ( combination of location + date ). If the same key1 is present in the array, then 'Number' is common for all the same Key1.

In the above example {'LA','2017-12-01',1 } having the same number 1.

{ 'NY','2017-12-01',2} having the number 2. and
{ 'NY','2016-10-01',3}, having the number 3 because eventhough location is common but date is different.

Please find my code below.

```<code>var item = this.state.item;
var lines = item.order_items;
var count=1;
var key1;
var key2;

    for(var i=0;i<lines.length;i++)
        {
            key1 = lines[i].location + '-' + lines[i].date;

            for(var j=0;j<lines.length;j++)
                {
                    key2 = lines[j].location + '-' + lines[j].date;
                    if( key1 === key2 )
                        {
                            lines[i].number=count;
                            this.setState({item:item});
                        }
                    else
                        {
                            count++;
                            lines[j].number=count;
                            this.setState({item:item});
                        }
                }
        }
</code>```

Problem is, for loop is iterating multiple times - its keep on comparing the same element multiple times. how do i can solve this issue.

答:
If you are trying to compare each item to one another, your innermost for loop is starting at the wrong index. Currently you have

```<code>for(var j=0;j<lines.length;j++)
</code>```

Instead, you should begin where your outer loop left off, like so (by incrementing i by one)

```<code>for(var j=i+1;j<lines.length;j++)
</code>```

Hope this helps!

Body:
Am comparing javascript array of elements with other elements within the same array. If elements are same means, i have to give same number for all the common elements. If the elements are different i have to give some different number for all the non identical elements in another element.

for example :

Array structure = [{Location, Date, Number}]

array = [{ 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1},
         { 'NY','2017-12-01',2},
         { 'NY','2016-10-01',3},
         { 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1}]

In this array 'Number' is dynamic element, It should be populate on the following rules.

key1 = location + '-' +date;

Consider Key1 is the first element ( combination of location + date ). If the same key1 is present in the array, then 'Number' is common for all the same Key1.

In the above example {'LA','2017-12-01',1 } having the same number 1.

{ 'NY','2017-12-01',2} having the number 2. and
{ 'NY','2016-10-01',3}, having the number 3 because eventhough location is common but date is different.

Please find my code below.

var item = this.state.item;
var lines = item.order_items;
var count=1;
var key1;
var key2;

    for(var i=0;i<lines.length;i++)
        {
            key1 = lines[i].location + '-' + lines[i].date;

            for(var j=0;j<lines.length;j++)
                {
                    key2 = lines[j].location + '-' + lines[j].date;
                    if( key1 === key2 )
                        {
                            lines[i].number=count;
                            this.setState({item:item});
                        }
                    else
                        {
                            count++;
                            lines[j].number=count;
                            this.setState({item:item});
                        }
                }
        }

Problem is, for loop is iterating multiple times - its keep on comparing the same element multiple times. how do i can solve this issue.

Body:
If you are trying to compare each item to one another, your innermost for loop is starting at the wrong index. Currently you have

for(var j=0;j<lines.length;j++)

Instead, you should begin where your outer loop left off, like so (by incrementing i by one)

for(var j=i+1;j<lines.length;j++)

Hope this helps!


问:
Why spring boot scanBasePackages conflict with spring.jackson.date-format
I config the json date format in application.properties with annotation

```<code>//in application.properties
spring.jackson.date-format=yyyy-MM-dd

@SpringBootApplication(scanBasePackages = (arrayOf("com.khidi")))
</code>```

the json date format not working,but I remove scanBasePages, it's working.
I need set the scanBasePages, because some bean in another package, how to fix it. thx.

答:
I found that a piece of code conflict the config</p>

```<code>@Configuration
class CustomRepositoryRestMvcConfiguration : RepositoryRestMvcConfiguration() {

｝
</code>```

Body:
I config the json date format in application.properties with annotation

//in application.properties
spring.jackson.date-format=yyyy-MM-dd

@SpringBootApplication(scanBasePackages = (arrayOf("com.khidi")))

the json date format not working,but I remove scanBasePages, it's working.
I need set the scanBasePages, because some bean in another package, how to fix it. thx.

Body:
I found that a piece of code conflict the config

@Configuration
class CustomRepositoryRestMvcConfiguration : RepositoryRestMvcConfiguration() {

｝


问:
Problems deploying to github pages with vue project

I'm trying to deploy a vue-cli project to github pages, I followed the instructions on this website and on github support.

delpoy vue-cli to github pages:
https://medium.com/@mwolfhoffman/deploying-to-github-pages-with-vue-webpack-cli-5b2ba17f14a0

Configuring github pages
https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/

Setting -> source -> master /docs

have a /docs folder in the root of the repository

not follow the repository naming scheme username.github.io or orgname.github.io

Here is my repository : https://github.com/leewei05/blog

But the result keep giving me 404, still doesn't know what my problem is, please help!

答:
It turned out I've got the wrong config path, here are the steps to deploy a new vue-cli project to git hub pages.

(You got to install npm and vue-cli first)

$ vue init webpack [projectName]

$ cd [projectName]

$ npm install

go to your config/index.js file

modify your build section like this:

build: {
    index: path.resolve(__dirname, '../docs/index.html'),
    assetsRoot: path.resolve(__dirname, '../docs'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '',
    productionSourceMap: true,
    devtool: '#source-map',
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    bundleAnalyzerReport: process.env.npm_config_report
  }
```

$ npm run build

push it to your github repository

go to the setting in your repository

find your GitHub Pages Section and change the source from
'master' -> 'master/docs'

your page should be on https://[userName].github.io/[repositoryName]/#/

Good luck on that!

Body:
It turned out I've got the wrong config path, here are the steps to deploy a new vue-cli project to git hub pages.

(You got to install npm and vue-cli first)

$ vue init webpack [projectName]

$ cd [projectName]

$ npm install

go to your config/index.js file

modify your build section like this:

build: {
    index: path.resolve(__dirname, '../docs/index.html'),
    assetsRoot: path.resolve(__dirname, '../docs'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '',
    productionSourceMap: true,
    devtool: '#source-map',
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    bundleAnalyzerReport: process.env.npm_config_report
  }

$ npm run build

push it to your github repository

go to the setting in your repository

find your GitHub Pages Section and change the source from
'master' -> 'master/docs'

your page should be on https://[userName].github.io/[repositoryName]/#/

Good luck on that!


问:
How to find the argmax of a two dimensional array in numpy?
I have a numpy ndarray:

```<code>array = np.array([[1,2,3],[4,5,6],[7,8,9]])
</code>```

Whenever I do, np.argmax(array), it doesn't return a tuple of row and column.
 Why not?

答:
You didn't specify an axis.  It returns an index into the flattened array, as documented.

```<code>>>> L = [[1,2,3],[4,5,6],[7,8,9]]
>>> np.argmax(L)
8
>>> np.array(L).ravel()[np.argmax(L)]
9
</code>```

If you want to get the row and column from that index, unravel it:

```<code>>>> np.unravel_index(8, np.array(L).shape)
(2, 2)
</code>```

Body:
I have a numpy ndarray:

array = np.array([[1,2,3],[4,5,6],[7,8,9]])

Whenever I do, np.argmax(array), it doesn't return a tuple of row and column.
 Why not?

Body:
You didn't specify an axis.  It returns an index into the flattened array, as documented.

>>> L = [[1,2,3],[4,5,6],[7,8,9]]
>>> np.argmax(L)
8
>>> np.array(L).ravel()[np.argmax(L)]
9

If you want to get the row and column from that index, unravel it:

>>> np.unravel_index(8, np.array(L).shape)
(2, 2)


问:
Integrate ${Category.displayName} in Demandware content slot
There is way to show ${Category.displayName} in regular Demandware Content Slot? Please let me know if there are other options how I can show actual category name inside a content asset.

Thanks in advance for your help.

答: Assuming this is a Category type content slot configuration you can access the categories you configured via ${slotcontent.content} which is an iterator of categories (you can use only the first element in your use case and ignore if there is more than one category).


答:
This seems like the sort of problem well suited for a map. You shouldn't be looping over the array twice.</p>

```<code>var item = this.state.item;
var lines = item.order_items;
var map = new Map();
for (var i = 0; i < lines.length; i++) {
    key = lines[i].location + '-' + lines[i].date;
    if (!map.has(key)) {
        map.set(key, map.size + 1);
    }
    lines[i].number = map.get(key);
    this.setState({item: item});
}
</code>```

Title: javascript array - comparing elements with other elements within the same array

Body:
This seems like the sort of problem well suited for a map. You shouldn't be looping over the array twice.

var item = this.state.item;
var lines = item.order_items;
var map = new Map();
for (var i = 0; i < lines.length; i++) {
    key = lines[i].location + '-' + lines[i].date;
    if (!map.has(key)) {
        map.set(key, map.size + 1);
    }
    lines[i].number = map.get(key);
    this.setState({item: item});
}


问:
Replace line in css file, using Greasemonkey
I am trying to write a Greasemonkey script that replaces one line of a .css file.

The original line from all.css is

```<code>#header {
    background: transparent url('img/bg-graph-top.png?v=7e4ce14d05fb') no-repeat 50% -25px;
}
</code>```

I'd like to replace it with

```<code>#header {
    background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px;
}
</code>```

Based on https://stackoverflow.com/a/6854437/9072294 I tried to write my very first userscript like this:

```<code>// ==UserScript==
// @name            swap
// @include         http://tex.stackexchange.com/*
// @include         https://tex.stackexchange.com/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

var desiredImage    = "https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png";

//--- Straight image swap:
$('img/bg-graph-top.png?v=7e4ce14d05fb').attr ('src', desiredImage);

/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
    Since this image is transparent, clear the old BG image.
    Also constrain the new img to its container.
*/
$('#header all').css ('background-', 'none')
                .append ('<url>').find ('img/bg-graph-top.png?v=7e4ce14d05fb')  .attr ('src', desiredImage).css ();
</code>```

However the image is not changing :(

答:
You are trying to change a background image, not an  tag, like that other answer.

For such things, just use CSS overrides.

Here's what it looks like in a Greasemonkey/Tampermonkey script:

```<code>// ==UserScript==
// @name        _TeX SE, Swap header background
// @match       *://tex.stackexchange.com/*
// @grant       GM_addStyle
// @run-at      document-start
// ==/UserScript==

GM_addStyle ( `
    #header {
        background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px !important;
    }
` );
</code>```

Note the !important flag.

Also, @run-at  document-start may complicate things if your script does any DOM manipulation.

Anyway, for pure CSS changes, like this one, you are better off using the Stylish extension.  It's less fuss and performs better

Body:
I am trying to write a Greasemonkey script that replaces one line of a .css file.

The original line from all.css is

#header {
    background: transparent url('img/bg-graph-top.png?v=7e4ce14d05fb') no-repeat 50% -25px;
}

I'd like to replace it with

#header {
    background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px;
}

Based on https://stackoverflow.com/a/6854437/9072294 I tried to write my very first userscript like this:

// ==UserScript==
// @name            swap
// @include         http://tex.stackexchange.com/*
// @include         https://tex.stackexchange.com/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

var desiredImage    = "https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png";

//--- Straight image swap:
$('img/bg-graph-top.png?v=7e4ce14d05fb').attr ('src', desiredImage);

/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
    Since this image is transparent, clear the old BG image.
    Also constrain the new img to its container.
*/
$('#header all').css ('background-', 'none')
                .append ('<url>').find ('img/bg-graph-top.png?v=7e4ce14d05fb')  .attr ('src', desiredImage).css ();

However the image is not changing :(

Body:
You are trying to change a background image, not an <img> tag, like that other answer.

For such things, just use CSS overrides.

Here's what it looks like in a Greasemonkey/Tampermonkey script:

// ==UserScript==
// @name        _TeX SE, Swap header background
// @match       *://tex.stackexchange.com/*
// @grant       GM_addStyle
// @run-at      document-start
// ==/UserScript==

GM_addStyle ( `
    #header {
        background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px !important;
    }
` );

Note the !important flag.

Also, @run-at  document-start may complicate things if your script does any DOM manipulation.

Anyway, for pure CSS changes, like this one, you are better off using the Stylish extension.  It's less fuss and performs better


问:
Biggest advantage to using ASP.Net MVC vs web forms
What are some of the advantages of using one over the other?</p>

答:
You don't feel bad about using 'non post-back controls' anymore - and figuring how to smush them into a traditional asp.net environment.

This means that modern (free to use) javascript controls such this or this or this can all be used without that trying to fit a round peg in a square hole feel.

LastEditorDisplayName: dbr

OwnerDisplayName: Simon


问:
How to parse source code into english?
What step I have to take to build such program.

I want to have a program that take a simple (limited) java keyword into english human language.

e.g

```<code>public class HelloWorld {

public static void main(String[] args) {
    int x;
    int y;
    System.out.println("Hello, World");
 }

}
</code>```

to

Declare HelloWorld Class

Declare main method

Declare variable x

Declare variable y

Print the word "Hello, World"

Close curly braces

Close curly braces

The program will read the source code line by line.

I tried using cl-ppcre, but the problem is, I cant figure it out, how to take a word to temp.

e.g

Declare HelloWord then add "class" word.

not Declare class HelloWorld, but I want Declare Helloworld class

or, it's difficult to replace ");" at the end of print. Because another word have to be replaced.

I tried to read line by line

```<code>(with-open-file (input "~/test.java")
  (loop for line = (read-line input nil)
        while line do (format t "~a~%" (parse-laporan line))))
</code>```

and parse it

```<code>(defun parse-laporan (isi)
  (cond
   ((cl-ppcre:scan "int " isi)
    (cl-ppcre:regex-replace "int" isi "Declare variable"))
   ((cl-ppcre:scan "System.out.print+" isi)
    (cl-ppcre:regex-replace   "System.out.print+" isi "print word "))
   ((cl-ppcre:scan "System.out.println+" isi)
    (cl-ppcre:regex-replace "System.out.println+" isi "print word "))
   ((cl-ppcre:scan "(" isi)
    (cl-ppcre:regex-replace "()" isi " "))
   ((cl-ppcre:scan "public class" isi)
    (cl-ppcre:regex-replace "public class" isi "Declare Kelas "))))
</code>```

but it does not work well.

Do, I have to read all the content of the file and build an Abstract Syntax Tree ? (like an interpreter does)
or I can achieve it just by replacing word by word ?

答:
Do, I have to read all the content of the file and build an Abstract Syntax Tree ?

Of course yes.

And you probably want it to be not simply a tree but some DAG.

So you may want to keep several representations of your source code. You might want to have several passes.

PS. Your problem is probably harder than what you imagine. I would consider some rule-based system approach.

Title: How to parse source code into english?

Body:
What step I have to take to build such program.

I want to have a program that take a simple (limited) java keyword into english human language.

e.g

public class HelloWorld {

public static void main(String[] args) {
    int x;
    int y;
    System.out.println("Hello, World");
 }

}

to

Declare HelloWorld Class

Declare main method

Declare variable x

Declare variable y

Print the word "Hello, World"

Close curly braces

Close curly braces

The program will read the source code line by line.

I tried using cl-ppcre, but the problem is, I cant figure it out, how to take a word to temp.

e.g

Declare HelloWord then add "class" word.

not Declare class HelloWorld, but I want Declare Helloworld class

or, it's difficult to replace ");" at the end of print. Because another word have to be replaced.

I tried to read line by line

(with-open-file (input "~/test.java")
  (loop for line = (read-line input nil)
        while line do (format t "~a~%" (parse-laporan line))))

and parse it

(defun parse-laporan (isi)
  (cond
   ((cl-ppcre:scan "int " isi)
    (cl-ppcre:regex-replace "int" isi "Declare variable"))
   ((cl-ppcre:scan "System.out.print+" isi)
    (cl-ppcre:regex-replace   "System.out.print+" isi "print word "))
   ((cl-ppcre:scan "System.out.println+" isi)
    (cl-ppcre:regex-replace "System.out.println+" isi "print word "))
   ((cl-ppcre:scan "(" isi)
    (cl-ppcre:regex-replace "()" isi " "))
   ((cl-ppcre:scan "public class" isi)
    (cl-ppcre:regex-replace "public class" isi "Declare Kelas "))))

but it does not work well.

Do, I have to read all the content of the file and build an Abstract Syntax Tree ? (like an interpreter does)
or I can achieve it just by replacing word by word ?


答:
Maybe something like this:

```<code>  static int methodName(int i, int j) {
    if (j == 0) throw new ArithmeticException();
    return i/j;
  }
</code>```

You could also use Integer type for result and initialize it to null and your code would compile:

```<code>Integer result = null;
</code>```

Either way, the calling code will need to handle the exception or the possible null value.

Title: Method return statement vs try-catch

Body:
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!

Body:
Maybe something like this:

  static int methodName(int i, int j) {
    if (j == 0) throw new ArithmeticException();
    return i/j;
  }

You could also use Integer type for result and initialize it to null and your code would compile:

Integer result = null;

Either way, the calling code will need to handle the exception or the possible null value.


问:
PyODBC Connection Issue on Apache 2.4
I was running my application under Apache 2.4 and mod_wsgi.
The ODBC connection works fine using Python Shell and 500 Internal Server Error when working under Apache HTTP Server.

But whenever try to load the module from httpd.config by adding

```<code> LoadModule pyodbc_module
 "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"
</code>```

and restarting the server results in httpd -k restart

```<code>httpd: Syntax error on line 576 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error
</code>```

 error.log

```<code>[cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215:

End of script output before headers: hello_get.py, referer: http://localhost/index.html
Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
File "C:\\Apache24\\htdocs\\hello_get.py", line 6, in <module>\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
import pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
ImportError: No module named pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
</code>```

答:
In Apache 500 Internal Error Solved. Because of importing pypyodbc instead of pyodbc.

In python shell I was able to connect successfully retrive the results in python shell as well as MSSQL Server 2017.

Title: PyODBC Connection Issue on Apache 2.4

Body:
I was running my application under Apache 2.4 and mod_wsgi.
The ODBC connection works fine using Python Shell and 500 Internal Server Error when working under Apache HTTP Server.

But whenever try to load the module from httpd.config by adding

 LoadModule pyodbc_module
 "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"

and restarting the server results in httpd -k restart

httpd: Syntax error on line 576 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error

 error.log

[cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215:

End of script output before headers: hello_get.py, referer: http://localhost/index.html
Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
File "C:\\Apache24\\htdocs\\hello_get.py", line 6, in <module>\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
import pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html
ImportError: No module named pyodbc\r: C:/Apache24/htdocs/hello_get.py, referer: http://localhost/index.html


问:
shuffling elements in a QStringList
In my Qt c++ application I have a QStringList containing a set of QString values! I want to shuffle(change the positions of the QStrings in the QStringList arbitrarily) . Is there any default function like "shuffle_array" API in perl? If not how can I do it?

eg-

```<code>QStringList names;
names<<"John"<<"Smith"<<"Anne";
</code>```

shuffling may change the positions of John,Smith and Anne arbitrarily! How can I achieve this?

答:
Use the standard std::random_shuffle function:

```<code>std::random_shuffle(names.begin(), names.end());
</code>```

Also, don't forget to generate a new random number sequence, otherwise the same results will be produced every time:

```<code>#include <time.h>

// ...

qsrand(time(NULL));
</code>```

Title: shuffling elements in a QStringList

Body:
In my Qt c++ application I have a QStringList containing a set of QString values! I want to shuffle(change the positions of the QStrings in the QStringList arbitrarily) . Is there any default function like "shuffle_array" API in perl? If not how can I do it?

eg-

QStringList names;
names<<"John"<<"Smith"<<"Anne";

shuffling may change the positions of John,Smith and Anne arbitrarily! How can I achieve this?

Body:
Use the standard std::random_shuffle function:

std::random_shuffle(names.begin(), names.end());

Also, don't forget to generate a new random number sequence, otherwise the same results will be produced every time:

#include <time.h>

// ...

qsrand(time(NULL));


问:
How to create unique index in sqlite3 and perl?
I am trying to insert values into the database, My database table is as shown

```<code>$stmt = qq(CREATE TABLE IF NOT EXISTS INFO
   (

  DeviceName               TEXT    NOT NULL,
  CurrentStatus            INT     NOT NULL,
  ReportTime        TEXT,
  OldStatus         INT            NOT NULL,
  OldReportTime     TEXT           ););
</code>```

Here before inserting to the db I am creating a unique index for DeviceName column, so that whenever a new entry comes into the db with same name it is not inserted rather gets replaced,

```<code>$stmt = qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName));
$stmt = qq(INSERT OR REPLACE INTO INFO(DeviceName, CurrentStatus,ReportTime,OldStatus,OldReportTime)
           VALUES ('$FQDN', $currentstatus, '$currenttime', $oldstatus, '$oldtime' ););
my $rv = $dbh->do($stmt) or die $DBI::errstr;
</code>```

these are the few lines which i added to create a unique index and replace if the next entity enters with the same DeviceName. But though i followed this, the databases is still getting stored with the same DeviceName multiple times.

```<code> #!/usr/bin/perl
 use DBI;
 use strict;
 my $FQDN= "bubbly.bth.se";
 my $currenttime = "Sat Dec  9 02:07:31 2017";
 my $oldtime = "Sat Dec  9 02:06:31 2017";
 my $currentstatus = "1";
 my $oldstatus = "2";
 my $driver   = "SQLite";
 my $database = "test.db";
 my $dsn = "DBI:$driver:dbname=$database";
 my $userid = "";
 my $password = "";

 my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
     or die $DBI::errstr;
 print "Opened database successfully\n";

 $stmt = qq(CREATE TABLE IF NOT EXISTS INFO
 (

  DeviceName               TEXT    NOT NULL,
  CurrentStatus            INT     NOT NULL,
  ReportTime        TEXT,
  OldStatus         INT            NOT NULL,
  OldReportTime     TEXT           ););

my $rv = $dbh->do($stmt);
if(my $rv < 0) {
print $DBI::errstr;
} else {
print "Table created successfully\n";
    }
$stmt = qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName));
$stmt = qq(INSERT OR REPLACE INTO INFO(DeviceName,
CurrentStatus,ReportTime,OldStatus,OldReportTime)
           VALUES ('$FQDN', $currentstatus, '$currenttime', $oldstatus,
'$oldtime' ););
my $rv = $dbh->do($stmt) or die $DBI::errstr;
$dbh->disconnect();

NetSNMP::TrapReceiver::register("all", \&my_receiver) ||
warn "failed to register our perl trap handler\n";
print STDERR "Loaded the example perl snmptrapd handler\n";
</code>```

this is the code i am using,
 my output

```<code>bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
</code>```

But i wanted to have only one row in the database which updates or replaces every time if it finds the same DeviceName.

NOTE: Variable values are taken just for easy understanding.

`

答:
You never actually create the index.

Replace

```<code>$stmt = qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName));
</code>```

with

```<code>$dbh->do(qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName)));
</code>```

Cleaned up version:

```<code>#!/usr/bin/perl

use strict;
use warnings qw( all );

use DBI qw( );

my $database = "test.db";
my $dsn = "dbi:sqlite:dbname=$database";

my $dbh = DBI->connect($dsn, undef, undef,
   {
      RaiseError => 1,
      PrintError => 0,
      PrintWarn  => 1,
      AutoCommit => 1,
   },
);

$dbh->do(q{
   CREATE TABLE IF NOT EXISTS INFO (
             DeviceName     TEXT  NOT NULL,
             CurrentStatus  INT   NOT NULL,
             ReportTime     TEXT,
             OldStatus      INT   NOT NULL,
             OldReportTime  TEXT
          )
});

$dbh->do(q{ CREATE UNIQUE INDEX ree ON INFO ( DeviceName ) });

my $FQDN          = "bubbly.bth.se";
my $currenttime   = "Sat Dec  9 02:07:31 2017";
my $oldtime       = "Sat Dec  9 02:06:31 2017";
my $currentstatus = "1";
my $oldstatus     = "2";

$dbh->do(
   q{
      INSERT OR REPLACE INTO INFO (
                DeviceName,
                CurrentStatus,
                ReportTime,
                OldStatus,
                OldReportTime
             ) VALUES (
                ?, ?, ?, ?, ?
             )
   },
   undef,
   $FQDN, $currentstatus, $currenttime, $oldstatus, $oldtime
);

$dbh->disconnect();
</code>```

Always use use warnings qw( all );.

You incorrectly build your INSERT statement (injection bug).

You have poor indenting and spacing.

You have RaiseError => 1, so it makes no sense to check if the DBI methods return an error.

You have RaiseError => 1, so it makes much sense to also use PrintError => 1.

Body:
I am trying to insert values into the database, My database table is as shown

$stmt = qq(CREATE TABLE IF NOT EXISTS INFO
   (

  DeviceName               TEXT    NOT NULL,
  CurrentStatus            INT     NOT NULL,
  ReportTime        TEXT,
  OldStatus         INT            NOT NULL,
  OldReportTime     TEXT           ););

Here before inserting to the db I am creating a unique index for DeviceName column, so that whenever a new entry comes into the db with same name it is not inserted rather gets replaced,

$stmt = qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName));
$stmt = qq(INSERT OR REPLACE INTO INFO(DeviceName, CurrentStatus,ReportTime,OldStatus,OldReportTime)
           VALUES ('$FQDN', $currentstatus, '$currenttime', $oldstatus, '$oldtime' ););
my $rv = $dbh->do($stmt) or die $DBI::errstr;

these are the few lines which i added to create a unique index and replace if the next entity enters with the same DeviceName. But though i followed this, the databases is still getting stored with the same DeviceName multiple times.

 #!/usr/bin/perl
 use DBI;
 use strict;
 my $FQDN= "bubbly.bth.se";
 my $currenttime = "Sat Dec  9 02:07:31 2017";
 my $oldtime = "Sat Dec  9 02:06:31 2017";
 my $currentstatus = "1";
 my $oldstatus = "2";
 my $driver   = "SQLite";
 my $database = "test.db";
 my $dsn = "DBI:$driver:dbname=$database";
 my $userid = "";
 my $password = "";

 my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
     or die $DBI::errstr;
 print "Opened database successfully\n";

 $stmt = qq(CREATE TABLE IF NOT EXISTS INFO
 (

  DeviceName               TEXT    NOT NULL,
  CurrentStatus            INT     NOT NULL,
  ReportTime        TEXT,
  OldStatus         INT            NOT NULL,
  OldReportTime     TEXT           ););

my $rv = $dbh->do($stmt);
if(my $rv < 0) {
print $DBI::errstr;
} else {
print "Table created successfully\n";
    }
$stmt = qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName));
$stmt = qq(INSERT OR REPLACE INTO INFO(DeviceName,
CurrentStatus,ReportTime,OldStatus,OldReportTime)
           VALUES ('$FQDN', $currentstatus, '$currenttime', $oldstatus,
'$oldtime' ););
my $rv = $dbh->do($stmt) or die $DBI::errstr;
$dbh->disconnect();

NetSNMP::TrapReceiver::register("all", \&my_receiver) ||
warn "failed to register our perl trap handler\n";
print STDERR "Loaded the example perl snmptrapd handler\n";

this is the code i am using,
 my output

bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017
bubbly.bth.se|1|Sat Dec  9 02:07:31 2017|2|Sat Dec  9 02:06:31 2017

But i wanted to have only one row in the database which updates or replaces every time if it finds the same DeviceName.

NOTE: Variable values are taken just for easy understanding.

`

Body:
You never actually create the index.

Replace

$stmt = qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName));

with

$dbh->do(qq(CREATE UNIQUE INDEX ree ON INFO(DeviceName)));

Cleaned up version:

#!/usr/bin/perl

use strict;
use warnings qw( all );

use DBI qw( );

my $database = "test.db";
my $dsn = "dbi:sqlite:dbname=$database";

my $dbh = DBI->connect($dsn, undef, undef,
   {
      RaiseError => 1,
      PrintError => 0,
      PrintWarn  => 1,
      AutoCommit => 1,
   },
);

$dbh->do(q{
   CREATE TABLE IF NOT EXISTS INFO (
             DeviceName     TEXT  NOT NULL,
             CurrentStatus  INT   NOT NULL,
             ReportTime     TEXT,
             OldStatus      INT   NOT NULL,
             OldReportTime  TEXT
          )
});

$dbh->do(q{ CREATE UNIQUE INDEX ree ON INFO ( DeviceName ) });

my $FQDN          = "bubbly.bth.se";
my $currenttime   = "Sat Dec  9 02:07:31 2017";
my $oldtime       = "Sat Dec  9 02:06:31 2017";
my $currentstatus = "1";
my $oldstatus     = "2";

$dbh->do(
   q{
      INSERT OR REPLACE INTO INFO (
                DeviceName,
                CurrentStatus,
                ReportTime,
                OldStatus,
                OldReportTime
             ) VALUES (
                ?, ?, ?, ?, ?
             )
   },
   undef,
   $FQDN, $currentstatus, $currenttime, $oldstatus, $oldtime
);

$dbh->disconnect();

Always use use warnings qw( all );.

You incorrectly build your INSERT statement (injection bug).

You have poor indenting and spacing.

You have RaiseError => 1, so it makes no sense to check if the DBI methods return an error.

You have RaiseError => 1, so it makes much sense to also use PrintError => 1.