问:
Valgrind reports memory leak on QThread::start()
The issue is on VMware, somehow 3D acceleration causes memory leak and SIGSEGV, resulting in program crashing.

=============================

I have a problem with following codes:

```<code>    gc = new GameController(scene);
    subthread = new QThread(this);
    gc->moveToThread(subthread);
    subthread->start();
</code>```

This should be a regular sub-thread initialization, but valgrind memory analyzer says:

```<code>416 bytes in 1 blocks are possibly lost in loss record 8,318 of 8,856
  in Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  1: calloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:762
  2: allocate_dtv in /usr/lib64/ld-2.28.so
  3: _dl_allocate_tls in /usr/lib64/ld-2.28.so
  4: pthread_create@@GLIBC_2.2.5 in /usr/lib64/libpthread-2.28.so
  5: QThread::start(QThread::Priority) in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/lib/libQt5Core.so.5.13.2
  6: Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  7: main in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/main.cpp:8
</code>```

directly pointing to subthread->start().
The scene is not the parent but a QGraphicsScene pointer passed to do some computing in sub-thread, and I manually delete gc after quit()&wait() subthread in my destructor. The program runs smoothly, but I cant do any memory analyzing because of this.

There are 2 definite leaks if I check External Errors, leading to QApplication a(argc, argv); and malloc in 'vg_replace_malloc.c'.

```<code>544 bytes in 11 blocks are definitely lost in loss record 8,418 of 8,861
  in _dl_close_worker in /usr/lib64/ld-2.28.so
  1: malloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:309
  2: _dl_close_worker in /usr/lib64/ld-2.28.so
  3: _dl_close in /usr/lib64/ld-2.28.so
  4: _dl_catch_exception in /usr/lib64/libc-2.28.so
  5: _dl_catch_error in /usr/lib64/libc-2.28.so
  6: _dlerror_run in /usr/lib64/libdl-2.28.so
  7: dlclose in /usr/lib64/libdl-2.28.so
  8: g_module_close in /usr/lib64/libgmodule-2.0.so.0.5600.4
  9: /usr/lib64/libgio-2.0.so.0.5600.4
  10: g_type_module_unuse in /usr/lib64/libgobject-2.0.so.0.5600.4
  11: /usr/lib64/libgio-2.0.so.0.5600.4
  12: g_io_extension_point_get_extensions in /usr/lib64/libgio-2.0.so.0.5600.4
  13: /usr/lib64/libgio-2.0.so.0.5600.4
  14: g_settings_backend_get_default in /usr/lib64/libgio-2.0.so.0.5600.4
  15: /usr/lib64/libgio-2.0.so.0.5600.4
  16: /usr/lib64/libgobject-2.0.so.0.5600.4
  17: g_object_new_valist in /usr/lib64/libgobject-2.0.so.0.5600.4
  18: g_object_new in /usr/lib64/libgobject-2.0.so.0.5600.4
  19: g_settings_new_full in /usr/lib64/libgio-2.0.so.0.5600.4
  20: /usr/lib64/libgdk-3.so.0.2200.30
  21: /usr/lib64/libgdk-3.so.0.2200.30
  22: gdk_display_manager_open_display in /usr/lib64/libgdk-3.so.0.2200.30
  23: gtk_init_check in /usr/lib64/libgtk-3.so.0.2200.30
  24: gtk_init in /usr/lib64/libgtk-3.so.0.2200.30
  25: QGtk3Theme::QGtk3Theme() in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/plugins/platformthemes/libqgtk3.so
</code>```

Where could the leak happen?

答:
416 bytes in 1 blocks are possibly lost in loss record 8,318 of 8,856

The message is possibly lost, that means the Widget is still reachable, this is not a definitive memory leak like in int * x=new int; x = NULL;

You have that message because when your program finishes you did not deleted/freed all the allocated dynamic memory, that does not means your program is wrong.

Look at definitely lost blocks, if you do not have all is ok in fact. For that you can use the option --show-leak-kinds=definite which is equivalent to do --show-reachable=no --show-possibly-lost=no

Body:
The issue is on VMware, somehow 3D acceleration causes memory leak and SIGSEGV, resulting in program crashing.

=============================

I have a problem with following codes:

    gc = new GameController(scene);
    subthread = new QThread(this);
    gc->moveToThread(subthread);
    subthread->start();

This should be a regular sub-thread initialization, but valgrind memory analyzer says:

416 bytes in 1 blocks are possibly lost in loss record 8,318 of 8,856
  in Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  1: calloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:762
  2: allocate_dtv in /usr/lib64/ld-2.28.so
  3: _dl_allocate_tls in /usr/lib64/ld-2.28.so
  4: pthread_create@@GLIBC_2.2.5 in /usr/lib64/libpthread-2.28.so
  5: QThread::start(QThread::Priority) in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/lib/libQt5Core.so.5.13.2
  6: Widget::Widget(QWidget*) in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/widget.cpp:15
  7: main in /home/closer_ex/QtProjects/LifeGameWithTest/LifeGame/main.cpp:8

directly pointing to subthread->start().
The scene is not the parent but a QGraphicsScene pointer passed to do some computing in sub-thread, and I manually delete gc after quit()&wait() subthread in my destructor. The program runs smoothly, but I cant do any memory analyzing because of this.

There are 2 definite leaks if I check External Errors, leading to QApplication a(argc, argv); and malloc in 'vg_replace_malloc.c'.

544 bytes in 11 blocks are definitely lost in loss record 8,418 of 8,861
  in _dl_close_worker in /usr/lib64/ld-2.28.so
  1: malloc in /builddir/build/BUILD/valgrind-3.15.0/coregrind/m_replacemalloc/vg_replace_malloc.c:309
  2: _dl_close_worker in /usr/lib64/ld-2.28.so
  3: _dl_close in /usr/lib64/ld-2.28.so
  4: _dl_catch_exception in /usr/lib64/libc-2.28.so
  5: _dl_catch_error in /usr/lib64/libc-2.28.so
  6: _dlerror_run in /usr/lib64/libdl-2.28.so
  7: dlclose in /usr/lib64/libdl-2.28.so
  8: g_module_close in /usr/lib64/libgmodule-2.0.so.0.5600.4
  9: /usr/lib64/libgio-2.0.so.0.5600.4
  10: g_type_module_unuse in /usr/lib64/libgobject-2.0.so.0.5600.4
  11: /usr/lib64/libgio-2.0.so.0.5600.4
  12: g_io_extension_point_get_extensions in /usr/lib64/libgio-2.0.so.0.5600.4
  13: /usr/lib64/libgio-2.0.so.0.5600.4
  14: g_settings_backend_get_default in /usr/lib64/libgio-2.0.so.0.5600.4
  15: /usr/lib64/libgio-2.0.so.0.5600.4
  16: /usr/lib64/libgobject-2.0.so.0.5600.4
  17: g_object_new_valist in /usr/lib64/libgobject-2.0.so.0.5600.4
  18: g_object_new in /usr/lib64/libgobject-2.0.so.0.5600.4
  19: g_settings_new_full in /usr/lib64/libgio-2.0.so.0.5600.4
  20: /usr/lib64/libgdk-3.so.0.2200.30
  21: /usr/lib64/libgdk-3.so.0.2200.30
  22: gdk_display_manager_open_display in /usr/lib64/libgdk-3.so.0.2200.30
  23: gtk_init_check in /usr/lib64/libgtk-3.so.0.2200.30
  24: gtk_init in /usr/lib64/libgtk-3.so.0.2200.30
  25: QGtk3Theme::QGtk3Theme() in /home/closer_ex/Qt5.13.2/5.13.2/gcc_64/plugins/platformthemes/libqgtk3.so

Where could the leak happen?


来源: stackexchange

问:
Is there something I'm missing about tuples?
I'm trying to learn Python from ''Automate the Boring Stuff with Python'' and I came across a program which I don't clearly understand.

```<code>phone_regex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?                # area code
    (\s|-|\.)?                        # separator
    (\d{3})                           # first 3 digits
    (\s|-|\.)                         # separator
    (\d{4})                           # last 4 digits
    (\s*(ext|x|ext.)\s*(\d{2,5}))?    # extension
    )''', re.VERBOSE)

matches = []
for groups in phone_regex.findall(text):
    print('here')
    phone_number = '-'.join([groups[1], groups[3], groups[5]])
    if groups[8] != '':
        phone_number += ' x' + groups[8]
        matches.append(phone_number)
</code>```

This is obviously not the whole thing, but I don't understand how IS there a groups[8] when there are only 6 groups in the regex. Additionally, while I do know the first group, group[0], is supposedly the first one, I don't really understand how...Does it just work like that, when there's one big tuple containing multiple tuples, the big one is considered the first one when indexed ?

This is obviously not the whole thing, but I don't understand how IS there a groups[8] when there are only 6 groups in the regex. Additionally, while I do know the first group, group[0], is supposedly the first one, I don't really understand how...Does it just work like that, when there's one big tuple containing multiple tuples, the big one is considered the first one when indexed ?

Also, how do the for loops here work exactly ? What are they looping ? I thought adding something like groups=groups[0:] was necessary for iterations to actually be different from one another in cases like this...

Thanks in advance.

答:
Note that some capturing groups have embedded capturing groups,
which are also counted.

Hence:

(\d{3}|\(\d{3}\))? - is group 1.

\(\d{3}\) - is not an embedded group, since both parentheses
are quoted and are treated literally.

separator, first 3 digits, second separator and
last 4 digits are groups 2 thru 5.

(\s*(ext|x|ext.)\s*(\d{2,5}))? - is group 6 (with 2 embedded groups).

(ext|x|ext.) - is group 7.

(\d{2,5}) - is group 8.

To see what has been captured by each group, run:

```<code>text = '123-456-9876 ext 22, (123)-456-9876'
for groups in phone_regex.findall(text):
    print(f'Whole match: {groups[0]}')
    n = 1
    for grp in groups[1:]:
        print(f'{n}: {grp:5}', end=', ')
        n += 1
    print()
</code>```

The result I got was:

```<code>Whole match: 123-456-9876 ext 22
1: 123  , 2: -    , 3: 456  , 4: -    , 5: 9876 , 6:  ext 22, 7: ext  , 8: 22   ,
Whole match: (123)-456-9876
1: (123), 2: -    , 3: 456  , 4: -    , 5: 9876 , 6:      , 7:      , 8:      ,
</code>```

And answering to your question in the comment:
I think you should avoid costructs like groups = groups[1:].
Syntactically it is correct, but this way you attempt to mess around
with the results of what has been found.
You can read groups[1:] like in my code above but don't attempt to
save there anything.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn Python from ''Automate the Boring Stuff with Python'' and I came across a program which I don't clearly understand.

phone_regex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?                # area code
    (\s|-|\.)?                        # separator
    (\d{3})                           # first 3 digits
    (\s|-|\.)                         # separator
    (\d{4})                           # last 4 digits
    (\s*(ext|x|ext.)\s*(\d{2,5}))?    # extension
    )''', re.VERBOSE)

matches = []
for groups in phone_regex.findall(text):
    print('here')
    phone_number = '-'.join([groups[1], groups[3], groups[5]])
    if groups[8] != '':
        phone_number += ' x' + groups[8]
        matches.append(phone_number)

This is obviously not the whole thing, but I don't understand how IS there a groups[8] when there are only 6 groups in the regex. Additionally, while I do know the first group, group[0], is supposedly the first one, I don't really understand how...Does it just work like that, when there's one big tuple containing multiple tuples, the big one is considered the first one when indexed ?

This is obviously not the whole thing, but I don't understand how IS there a groups[8] when there are only 6 groups in the regex. Additionally, while I do know the first group, group[0], is supposedly the first one, I don't really understand how...Does it just work like that, when there's one big tuple containing multiple tuples, the big one is considered the first one when indexed ?

Also, how do the for loops here work exactly ? What are they looping ? I thought adding something like groups=groups[0:] was necessary for iterations to actually be different from one another in cases like this...

Thanks in advance.

Body:
Note that some capturing groups have embedded capturing groups,
which are also counted.

Hence:

(\d{3}|\(\d{3}\))? - is group 1.

\(\d{3}\) - is not an embedded group, since both parentheses
are quoted and are treated literally.

separator, first 3 digits, second separator and
last 4 digits are groups 2 thru 5.

(\s*(ext|x|ext.)\s*(\d{2,5}))? - is group 6 (with 2 embedded groups).

(ext|x|ext.) - is group 7.

(\d{2,5}) - is group 8.

To see what has been captured by each group, run:

text = '123-456-9876 ext 22, (123)-456-9876'
for groups in phone_regex.findall(text):
    print(f'Whole match: {groups[0]}')
    n = 1
    for grp in groups[1:]:
        print(f'{n}: {grp:5}', end=', ')
        n += 1
    print()

The result I got was:

Whole match: 123-456-9876 ext 22
1: 123  , 2: -    , 3: 456  , 4: -    , 5: 9876 , 6:  ext 22, 7: ext  , 8: 22   ,
Whole match: (123)-456-9876
1: (123), 2: -    , 3: 456  , 4: -    , 5: 9876 , 6:      , 7:      , 8:      ,

And answering to your question in the comment:
I think you should avoid costructs like groups = groups[1:].
Syntactically it is correct, but this way you attempt to mess around
with the results of what has been found.
You can read groups[1:] like in my code above but don't attempt to
save there anything.


问:
opengl glDrawArray throws exception
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000)</p>

```<code>glEnableClientState(GL_VERTEX_ARRAY);
float data[8];
data[0] = 10;
data[1] = 10;
data[2] = 10;
data[3] = 20;
data[4] = 20;
data[5] = 20;
data[6] = 20;
data[7] = 10;
glVertexPointer(2,GL_FLOAT,0,data);
glDrawArrays(GL_LINE_LOOP,0,4);
glDisableClientState(GL_VERTEX_ARRAY);
</code>```

答:
Try:

```<code>glDrawArrays(GL_LINE_LOOP,0,4);
</code>```

In your call to glVertexPointer() you are saying that each vertex has two floats. But in the call to glDrawArrays() you don't specify the number of elements in the array, you specify the number of coordinates, in this case they are four.

ContentLicense: CC BY-SA 3.0

Title: opengl glDrawArray throws exception

Body:
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000)

glEnableClientState(GL_VERTEX_ARRAY);
float data[8];
data[0] = 10;
data[1] = 10;
data[2] = 10;
data[3] = 20;
data[4] = 20;
data[5] = 20;
data[6] = 20;
data[7] = 10;
glVertexPointer(2,GL_FLOAT,0,data);
glDrawArrays(GL_LINE_LOOP,0,4);
glDisableClientState(GL_VERTEX_ARRAY);

Body:
Try:

glDrawArrays(GL_LINE_LOOP,0,4);

In your call to glVertexPointer() you are saying that each vertex has two floats. But in the call to glDrawArrays() you don't specify the number of elements in the array, you specify the number of coordinates, in this case they are four.


问:
SessionNotCreatedException: This version of ChromeDriver only supports Chrome version 84 using ChromeDriver and Chrome through Selenium and Python

I am using python 3 on windows 7, selenium, chromedriver version 84
  (latest) to automate my chrome browser.

I am using this script:

from selenium import webdriver
#import chromedriver_binary  # Adds chromedriver binary to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")
```

<p>and I always get this error upon running it.</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
  File "D:\Huzefa\Desktop\zzzzzz.py", line 4, in <module>
    driver = webdriver.Chrome()
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 84
</code>```

My ChromeDriver is in path. Also i have used other versions of chromedriver but i am not able to navigate to a website!

答:
Your ChromeDriver version and your installed version of Chrome need to match up. You are using ChromeDriver for Chrome version 84, which at the time of this answer, is a beta (non-stable) build of Chrome; you're probably not using it. Likely you're on version 83.

Check your Chrome version (Help -> About) and then find the correct ChromeDriver release. You could instead use webdriver-manager which can handle this for you.

Body:
I am using python 3 on windows 7, selenium, chromedriver version 84
  (latest) to automate my chrome browser.

I am using this script:

from selenium import webdriver
#import chromedriver_binary  # Adds chromedriver binary to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")

and I always get this error upon running it.

Traceback (most recent call last):
  File "D:\Huzefa\Desktop\zzzzzz.py", line 4, in <module>
    driver = webdriver.Chrome()
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Huzefa\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 84

My ChromeDriver is in path. Also i have used other versions of chromedriver but i am not able to navigate to a website!


问:
is there any way of sorting an array of string in lexicographically in O(N)?
there is an approach using strcmp() and strcpy() but it is O(n^2) but is there any faster method?</p>

答:
When dealing with arrays if strings, keep in mind that there are two separate quantities that will inform the runtime: how many strings you have (let’s call that n), and how many total characters those strings have (let’s call that m). If either of these values are large, it will increase the runtime. For example, sorting an array of two identical strings that are each a million characters long is going to take a while even though there’s only two strings.

If you have a fixed-sized alphabet (say, just English letters and digits), then you can sort an array of strings in time O(m + n) by inserting all of the strings into a trie and then doing a DFS over the trie to read them back in sorted order. You can achieve a similar effect by using a most-significant character radix sort. These approaches are a bit more involved than simple sorting algorithms combine with strcmp, but are much faster for large numbers of long strings.

Hope this helps!


问:
IntelliJ Git checkout in one instance corrupts opened project in another instance
I use IntelliJ Idea 18 + Git in our project.

I have cloned myproject into locations like C:\workspaces\myproject1 and C:\workspaces\myproject2

If I open 2 instances of IntelliJ: one pointing to myproject1 and another into myProject2 then if I start using myproject1 and switch branches in that IntelliJ IDEA... it sorts of corrupts the myproject2 as well.

Why is it happening? I just want to have 2 copies of the repo working at the same time in the machine so that I can usually work on my branch and can also peer review another branch from the same repo in another IntelliJ project. But changing one branch in IntelliJ (myproject1) also impacts the myproject2.

答:
You need to make sure that you should open myproject1 and myproject2 in completely different IntelliJ instances.
From your description, it looks like they are "overlapping" somewhere and it could be due to:

You have opened your projects by choosing C:\workspaces\

You have opened the same project by mistake


问:
How to read large avro file with out loading entire file into memory
I want to read large avro file of size 2.5 GB. Currently, I'm using

```<code>new DataFileReader<>(readFile, userDatumReader);
</code>```

Which loads entire 2.5 GB file into memory.

Is there any way to read large avro file with out loading complete file into memory?

答:
Using a DataFileReader should almost certainly not load the complete file into memory.

```<code>DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
try (DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(file, datumReader)) {
  while (dataFileReader.hasNext()) {
    GenericRecord datum = dataFileReader.next(null)
    processRecord(datum);
    // Make sure you're not keeping a reference
    // to datum after it's been processed.
  }
}
</code>```

I've verified that datum can be garbage collected once it's been processed, and should not be kept around in memory by Avro.  Is it possible that you're saving the data in a collection or keeping a reference in your code?  This will, of course, prevent garbage collection.

The other way Avro might read the entire file contents into memory is if there is  only one record of 2.5GB in the Avro file... in this case, you might want to revisit your design for storing data!

Body:
I want to read large avro file of size 2.5 GB. Currently, I'm using

new DataFileReader<>(readFile, userDatumReader);

Which loads entire 2.5 GB file into memory.

Is there any way to read large avro file with out loading complete file into memory?

Body:
Using a DataFileReader should almost certainly not load the complete file into memory.

DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
try (DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(file, datumReader)) {
  while (dataFileReader.hasNext()) {
    GenericRecord datum = dataFileReader.next(null)
    processRecord(datum);
    // Make sure you're not keeping a reference
    // to datum after it's been processed.
  }
}

I've verified that datum can be garbage collected once it's been processed, and should not be kept around in memory by Avro.  Is it possible that you're saving the data in a collection or keeping a reference in your code?  This will, of course, prevent garbage collection.

The other way Avro might read the entire file contents into memory is if there is  only one record of 2.5GB in the Avro file... in this case, you might want to revisit your design for storing data!


问:
Oracle SQLDeveloper on MacOS won't open after installation of correct Java
I downloaded the Oracle SQLDeveloper, but when I opened it, it said that it requires a minimum of Java 8 and gave me the website for the download. I went on and downloaded Java 10.0.1, but when I went back on to open SQL, it continued saying it required a minimum of Java 8.

I checked that the Java 10.0.1 had installed correctly, and I'm pretty sure it has. It shows up in System Preferences and when clicked, it opens the Java Control Panel fine.

I'm on a MacOS X El Captain 10.11.6.

答:
Previously, only JDK 8 worked with Oracle SQL Developer.

But, per https://www.oracle.com/tools/downloads/sqldev-v192-downloads.html, JDK 8 or 11 are required. (there is some misleading documentation that says JDK 8 or higher, but it must be 8 or 11).  Also, per Oracle, JDK 11.0.7 is certified for Mac OS Catalina.

JDK 11 certification: https://www.oracle.com/java/technologies/javase/products-doc-jdk11certconfig.html

JDK Certifications: https://www.oracle.com/java/technologies/javase-subscription/documentation.html#sysconfig

When I only had JDK 14 installed, it wouldn't run.  It looked like it was going to, but wouldn't even start.  You will need to give permission for it to run as it is still not an Apple approved app. (Ctrl-click, then Open, supposedly works & saves your setting, but after so many changes trying to get this to work, I can't promise).


问:
Change cursor to 'move' on 'dragstart'
I am trying to change the cursor to 'move' after the dragging starts. I tried setting the dropEffect property to move but that doesn't work. https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

How can I change the cursor to move only AFTER the dragstart event fires?

const button = document.querySelector("button");
console.log(button);

button.addEventListener("dragstart", dragStart);

function dragStart(e) {
  e.dataTransfer.setData("text/plain", 'hello');
  e.dataTransfer.dropEffect = "move";
  console.log(e);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" draggable="true">Drag Me</button></code>```

答:
As far as I can read dropEffect is only available for when the user hovers over a drop target:

Within event handlers for dragenter and dragover events, dropEffect should be modified if a different action is desired than the action that the user is requesting.

— MDN

It says dragenter, dragover but not dragstart.

Title: Change cursor to 'move' on 'dragstart'

Body:
I am trying to change the cursor to 'move' after the dragging starts. I tried setting the dropEffect property to move but that doesn't work. https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

How can I change the cursor to move only AFTER the dragstart event fires?

const button = document.querySelector("button");
console.log(button);

button.addEventListener("dragstart", dragStart);

function dragStart(e) {
  e.dataTransfer.setData("text/plain", 'hello');
  e.dataTransfer.dropEffect = "move";
  console.log(e);
}

<button type="button" draggable="true">Drag Me</button>


问:
SubQuery In presto
```<code>SELECT
  id,(select something
   from table2
   where table2.id = table.id) AS "Description"
 FROM table
</code>```

I am getting this error:

```<code>presto error: Scalar sub-query has returned multiple rows
</code>```

How to write subquery in presto ?

答:
Presto does support nested queries. I think the issue is your semantics.

You are trying to project something from the nested query and it is expecting an scalar value.

It could be something like this -

```<code>select
id, desc from
(select table.id as id, something as desc
    from table2
    where table2.id = table.id)
</code>```

Title: SubQuery In presto

Body:
SELECT
  id,(select something
   from table2
   where table2.id = table.id) AS "Description"
 FROM table

I am getting this error:

presto error: Scalar sub-query has returned multiple rows

How to write subquery in presto ?

Body:
Presto does support nested queries. I think the issue is your semantics.

You are trying to project something from the nested query and it is expecting an scalar value.

It could be something like this -

select
id, desc from
(select table.id as id, something as desc
    from table2
    where table2.id = table.id)


问:
Make socket class available to entire app
I have the following class which I will use to display an alert regardless of which page the user is on within the app.

What is the best way to make this class accessible to all pages with in the app? Do I need to include it in every page and then call it in the init method of that page?

```<code>class SocketHelper{

  connect(){
SocketIO socketIO = SocketIOManager().createSocketIO("http://someurl", "/", query: "userId=123",socketStatusCallback: _socketStatus);
socketIO.init();
socketIO.subscribe("somealert", _onReceiveAlert);
socketIO.connect();
  }

  _onReceiveAlert(){
    // todo
  }

  _socketStatus(){
    // todo
  }

}
</code>```

答: You should probably use Provider to pass it to other indépendant widgets.</p>

Body:
I have the following class which I will use to display an alert regardless of which page the user is on within the app.

What is the best way to make this class accessible to all pages with in the app? Do I need to include it in every page and then call it in the init method of that page?

class SocketHelper{

  connect(){
SocketIO socketIO = SocketIOManager().createSocketIO("http://someurl", "/", query: "userId=123",socketStatusCallback: _socketStatus);
socketIO.init();
socketIO.subscribe("somealert", _onReceiveAlert);
socketIO.connect();
  }

  _onReceiveAlert(){
    // todo
  }

  _socketStatus(){
    // todo
  }

}


问:
Creating nested array from flat array - Data Structure
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

```<code>const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];
</code>```

Output:

```<code>const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];
</code>```

The best approach would be something recursive.
Any suggestions for this algorithm?

答:
I was curious if the linked answer from Scott would be able to solve this problem without modification. It does!

import { tree } from './Tree'
import { bind } from './Func'

const parent = (path = "") =>
  bind
    ( (pos = path.lastIndexOf(".")) =>
        pos === -1
          ? null
          : path.substr(0, pos)
    )

const myTree =
  tree                          // <- make tree
    ( list                      // <- array of nodes
    , node => parent(node.path) // <- foreign key
    , (node, children) =>       // <- node reconstructor
        ({ ...node, children: children(node.path) }) // <- primary key
    )

console.log(JSON.stringify(myTree, null, 2))
```

```[
  {
    "location": 1,
    "path": "4",
    "children": [
      {
        "location": 2,
        "path": "4.1",
        "children": [
          {
            "location": 3,
            "path": "4.1.1",
            "children": []
          },
          {
            "location": 4,
            "path": "4.1.2",
            "children": []
          }
        ]
      },
      {
        "location": 5,
        "path": "4.2",
        "children": [
          {
            "location": 6,
            "path": "4.2.1",
            "children": []
          }
        ]
      },
      {
        "location": 7,
        "path": "4.3",
        "children": [
          {
            "location": 8,
            "path": "4.3.1",
            "children": []
          }
        ]
      }
    ]
  }
]
```

<p>The <code>Tree</code> module is shared in this post and here's a peek at the <code>Func</code> module that supplies <code>bind</code> -</p>

<pre class="lang-js prettyprint-override"><code>// Func.js
const identity = x => x

const bind = (f, ...args) =>
  f(...args)

const raise = (msg = "") => // functional throw
  { throw Error(msg) }

// ...

export { identity, bind, raise, ... }
</code>```

Expand the snippet below to verify the results in your browser -

// Func.js
const bind = (f, ...args) =>
  f(...args)

// Index.js
const empty = _ =>
  new Map

const update = (r, k, t) =>
  r.set(k, t(r.get(k)))

const append = (r, k, v) =>
  update(r, k, (all = []) => [...all, v])

const index = (all = [], indexer) =>
  all.reduce
      ( (r, v) => append(r, indexer(v), v)
      , empty()
      )

// Tree.js
// import { index } from './Index'
function tree (all, indexer, maker, root = null)
{ const cache =
    index(all, indexer)

  const many = (all = []) =>
    all.map(x => one(x))

  const one = (single) =>
    maker(single, next => many(cache.get(next)))

  return many(cache.get(root))
}

// Main.js
// import { tree } from './Tree'
// import { bind } from './Func'

const parent = (path = "") =>
  bind
    ( (pos = path.lastIndexOf(".")) =>
        pos === -1
          ? null
          : path.substr(0, pos)
    )

const list =
  [{location:1,path:'4'},{location:2,path:'4.1'},{location:3,path:'4.1.1'},{location:4,path:'4.1.2'},{location:5,path:'4.2'},{location:6,path:'4.2.1'},{location:7,path:'4.3'},{location:8,path:'4.3.1'}]

const myTree =
  tree
    ( list                      // <- array of nodes
    , node => parent(node.path) // <- foreign key
    , (node, children) =>       // <- node reconstructor
        ({ ...node, children: children(node.path) }) // <- primary key
    )

console.log(JSON.stringify(myTree, null, 2))```

Body:
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];

Output:

const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];

The best approach would be something recursive.
Any suggestions for this algorithm?

Body:
I was curious if the linked answer from Scott would be able to solve this problem without modification. It does!

import { tree } from './Tree'
import { bind } from './Func'

const parent = (path = "") =>
  bind
    ( (pos = path.lastIndexOf(".")) =>
        pos === -1
          ? null
          : path.substr(0, pos)
    )

const myTree =
  tree                          // <- make tree
    ( list                      // <- array of nodes
    , node => parent(node.path) // <- foreign key
    , (node, children) =>       // <- node reconstructor
        ({ ...node, children: children(node.path) }) // <- primary key
    )

console.log(JSON.stringify(myTree, null, 2))

[
  {
    "location": 1,
    "path": "4",
    "children": [
      {
        "location": 2,
        "path": "4.1",
        "children": [
          {
            "location": 3,
            "path": "4.1.1",
            "children": []
          },
          {
            "location": 4,
            "path": "4.1.2",
            "children": []
          }
        ]
      },
      {
        "location": 5,
        "path": "4.2",
        "children": [
          {
            "location": 6,
            "path": "4.2.1",
            "children": []
          }
        ]
      },
      {
        "location": 7,
        "path": "4.3",
        "children": [
          {
            "location": 8,
            "path": "4.3.1",
            "children": []
          }
        ]
      }
    ]
  }
]

The Tree module is shared in this post and here's a peek at the Func module that supplies bind -

// Func.js
const identity = x => x

const bind = (f, ...args) =>
  f(...args)

const raise = (msg = "") => // functional throw
  { throw Error(msg) }

// ...

export { identity, bind, raise, ... }

Expand the snippet below to verify the results in your browser -

// Func.js
const bind = (f, ...args) =>
  f(...args)

// Index.js
const empty = _ =>
  new Map

const update = (r, k, t) =>
  r.set(k, t(r.get(k)))

const append = (r, k, v) =>
  update(r, k, (all = []) => [...all, v])

const index = (all = [], indexer) =>
  all.reduce
      ( (r, v) => append(r, indexer(v), v)
      , empty()
      )

// Tree.js
// import { index } from './Index'
function tree (all, indexer, maker, root = null)
{ const cache =
    index(all, indexer)

  const many = (all = []) =>
    all.map(x => one(x))

  const one = (single) =>
    maker(single, next => many(cache.get(next)))

  return many(cache.get(root))
}

// Main.js
// import { tree } from './Tree'
// import { bind } from './Func'

const parent = (path = "") =>
  bind
    ( (pos = path.lastIndexOf(".")) =>
        pos === -1
          ? null
          : path.substr(0, pos)
    )

const list =
  [{location:1,path:'4'},{location:2,path:'4.1'},{location:3,path:'4.1.1'},{location:4,path:'4.1.2'},{location:5,path:'4.2'},{location:6,path:'4.2.1'},{location:7,path:'4.3'},{location:8,path:'4.3.1'}]

const myTree =
  tree
    ( list                      // <- array of nodes
    , node => parent(node.path) // <- foreign key
    , (node, children) =>       // <- node reconstructor
        ({ ...node, children: children(node.path) }) // <- primary key
    )

console.log(JSON.stringify(myTree, null, 2))


问:
Difference between list() and [ ] in Python 3
Is there any difference between list() and [] while initializing a list in Python 3?

答:
Let us take this example:

```<code>A = ("a","b","c")
B = list(A)
C = [A]

print("B=",B)
print("C=",C)

# list is mutable:
B.append("d")
C.append("d")

## New result
print("B=",B)
print("C=",C)

Result:
B= ['a', 'b', 'c']
C= [('a', 'b', 'c')]

B= ['a', 'b', 'c', 'd']
C= [('a', 'b', 'c'), 'd']
</code>```

Based on this example, we can say that: [ ] doesn't try to convert tuple into a list of elements  while list() is a method that try to convert  tuple into list of elements.

Body:
Let us take this example:

A = ("a","b","c")
B = list(A)
C = [A]

print("B=",B)
print("C=",C)

# list is mutable:
B.append("d")
C.append("d")

## New result
print("B=",B)
print("C=",C)

Result:
B= ['a', 'b', 'c']
C= [('a', 'b', 'c')]

B= ['a', 'b', 'c', 'd']
C= [('a', 'b', 'c'), 'd']

Based on this example, we can say that: [ ] doesn't try to convert tuple into a list of elements  while list() is a method that try to convert  tuple into list of elements.


问:
Idiomatic way to modify a member variable
I know Haskell isn't OO so it isn't strictly a 'member variable'.

```<code>data Foo = Foo {
    bar :: Int,
    moo :: Int,
    meh :: Int,
    yup :: Int
}

modifyBar (Foo b m me y) = (Foo b' m me y)
    where b' = 2
</code>```

This is how my code looks at the moment. The problem is I am now making data types with 16 or more members. When I need to modify a single member it results in very verbose code. Is there a way around this?

答:
Haskell's "record syntax" that @KennyTM shows is the built-in way to do this, though keep in mind that it's still just a way of constructing a new value based on the old one.

There are some annoying limitations to record syntax, though, particularly that the form used to "modify" a single item in a record aren't first-class entities in the language, so you can't abstract over them and pass them around the way you'd do with a regular function.

An alternative is using a library such as fclabels which provides similar functionality, using Template Haskell to auto-generate accessor functions instead of built-in syntax. The result is often much nicer, with the downside that you now have a dependency on TH....

Body:
I know Haskell isn't OO so it isn't strictly a 'member variable'.

data Foo = Foo {
    bar :: Int,
    moo :: Int,
    meh :: Int,
    yup :: Int
}

modifyBar (Foo b m me y) = (Foo b' m me y)
    where b' = 2

This is how my code looks at the moment. The problem is I am now making data types with 16 or more members. When I need to modify a single member it results in very verbose code. Is there a way around this?


问:
NodeJS check if object property is not null
I'm working on nodejs and I want to check if my object property is not null when uses a filter :

propositions = propositions.filter((prop) => {
  return prop.issuer.city.equals(req.user.city._id);
});
```

<p><code>prop.issuer</code> may be null some time and I want to avoid this comparison when it's null! </p>

<p>I tried this but it's not worked :</p>

<pre class="lang-js prettyprint-override"><code>propositions = propositions.filter((prop) => {
  return prop.issuer?.city.equals(req.user.city._id);
});
</code>```

答:
```<code>propositions = propositions.filter(prop => prop.issuer ? prop.issuer.city.equals(req.user.city._id) : false)
</code>```

I assumed you want to filter out propositions with null issuer, that's why I used false as third operand of ternary operator; if I was wrong, use true.

Body:
I'm working on nodejs and I want to check if my object property is not null when uses a filter :

propositions = propositions.filter((prop) => {
  return prop.issuer.city.equals(req.user.city._id);
});

prop.issuer may be null some time and I want to avoid this comparison when it's null!

I tried this but it's not worked :

propositions = propositions.filter((prop) => {
  return prop.issuer?.city.equals(req.user.city._id);
});

Body:
propositions = propositions.filter(prop => prop.issuer ? prop.issuer.city.equals(req.user.city._id) : false)

I assumed you want to filter out propositions with null issuer, that's why I used false as third operand of ternary operator; if I was wrong, use true.


问:
Job Scheduler in Android
I am working on an application where user can set reminder for any task and there is start and end date for this reminder. All the information regarding task is stored in database. So I need to write scheduler which run after every 15 min and fetch details from database and check if user has set any reminder then app will give notification. I tried to search on google but most of the examples are using start and stop buttons. Can anyone help me to use proper way to call scheduler without any click event.</p>

答:
Use WorkManager to periodically perform a task. You can refer to the documentation here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/recurring-work

Sample Code:
Your worker class:

```<code>class YourWorkerClass(appContext: Context, workerParams: WorkerParameters)
    : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        // Do the work here--in this case, fetch data from database.

        return Result.success()
    }
}
</code>```

Using WorkManager to schedule the Work:

```<code>val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .build()

    val saveRequest =
    PeriodicWorkRequestBuilder<YourWorkerClass>(15, TimeUnit.MINUTES)
        .setConstraints(constraints)
        .build()

    WorkManager.getInstance(myContext)
        .enqueue(saveRequest)
</code>```

Title: Job Scheduler in Android

Body:
Use WorkManager to periodically perform a task. You can refer to the documentation here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/recurring-work

Sample Code:
Your worker class:

class YourWorkerClass(appContext: Context, workerParams: WorkerParameters)
    : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        // Do the work here--in this case, fetch data from database.

        return Result.success()
    }
}

Using WorkManager to schedule the Work:

val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .build()

    val saveRequest =
    PeriodicWorkRequestBuilder<YourWorkerClass>(15, TimeUnit.MINUTES)
        .setConstraints(constraints)
        .build()

    WorkManager.getInstance(myContext)
        .enqueue(saveRequest)


问:
Could not find or load main class org.apache.hadoop.hdfs.server.namenode.Namenode
I know this has been asked before but I could not figure out the solution. I am getting the below error when I am trying to run hdfs name node -format:

Could not find or load main class org.apache.hadoop.hdfs.server.namenode.Namenode

I followed the instructions from this website to install on my centos machine. The only difference is that I installed using root instead of hadoopuser as mentioned in the link.

Bashrc

# User specific aliases and functions

export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/
export HADOOP_INSTALL=/usr/local/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_HOME=$HADOOP_INSTALL
export HADOOP_HDFS_HOME=$HADOOP_INSTALL
export YARN_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_INSTALL/lib/native
export PATH=$PATH:$HADOOP_INSTALL/sbin
export PATH=$PATH:$HADOOP_INSTALL/bin
```

<h3>hadoop-env.sh</h3>

<pre class="lang-sh prettyprint-override"><code>export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/
</code>```

Mapred

<property>
    <name>mapreduce.framework.name</name>
    <value>yarn</value>
</property>
```

<h3>Yarn-site.xml</h3>

<pre class="lang-xml prettyprint-override"><code><property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
</property>
</code>```

core-site.xml

<property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
</property>
```

<h3>hdfs-site.xml</h3>

<pre class="lang-xml prettyprint-override"><code><property>
    <name>dfs.replication</name>
    <value>1</value>
</property>

<property>
    <name>dfs.name.dir</name>
    <value>file:///home/hadoopspace/hdfs/namenode</value>
</property>

<property>
    <name>dfs.data.dir</name>
    <value>file:///home/hadoopspace/hdfs/datanode</value>
</property>
</code>```

答:
Could be a classpath issue.

Add the following to your ~/.bashrc

```<code> export HADOOP_CLASSPATH=$(cygpath -pw $(hadoop classpath)):$HADOOP_CLASSPATH
</code>```

Body:
I know this has been asked before but I could not figure out the solution. I am getting the below error when I am trying to run hdfs name node -format:

Could not find or load main class org.apache.hadoop.hdfs.server.namenode.Namenode

I followed the instructions from this website to install on my centos machine. The only difference is that I installed using root instead of hadoopuser as mentioned in the link.

Bashrc

# User specific aliases and functions

export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/
export HADOOP_INSTALL=/usr/local/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_HOME=$HADOOP_INSTALL
export HADOOP_HDFS_HOME=$HADOOP_INSTALL
export YARN_HOME=$HADOOP_INSTALL
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_INSTALL/lib/native
export PATH=$PATH:$HADOOP_INSTALL/sbin
export PATH=$PATH:$HADOOP_INSTALL/bin

hadoop-env.sh

export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64/

Mapred

<property>
    <name>mapreduce.framework.name</name>
    <value>yarn</value>
</property>

Yarn-site.xml

<property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
</property>

core-site.xml

<property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
</property>

hdfs-site.xml

<property>
    <name>dfs.replication</name>
    <value>1</value>
</property>

<property>
    <name>dfs.name.dir</name>
    <value>file:///home/hadoopspace/hdfs/namenode</value>
</property>

<property>
    <name>dfs.data.dir</name>
    <value>file:///home/hadoopspace/hdfs/datanode</value>
</property>

Body:
Could be a classpath issue.

Add the following to your ~/.bashrc

 export HADOOP_CLASSPATH=$(cygpath -pw $(hadoop classpath)):$HADOOP_CLASSPATH


问:
Snowflake json_extract_path_text does not accept a key with spaces
The data coming into the warehouse is structured like this

{"Client ID":"1234567","client_name":"Kareem" }

when I use the function

```<code>JSON_EXTRACT_PATH_TEXT(COLUMN_NAME, 'Client ID')
</code>```

it give me this error :

```<code>Invalid extraction path 'Client ID': invalid token at position 7.
</code>```

is there another workaround to get the value for this key ? or for using this key with the function to get the value out of the JSON column ?

答:
The following does work, which is supposed to be close to equivalent.  My example assumes your values are a string, since that is the input of the function you were trying to use:</p>

```<code>WITH x AS (SELECT '{"Client ID":"1234567","client_name":"Kareem" }' as json_string)
SELECT parse_json(json_string):"Client ID"
FROM x;
</code>```

Body:
The data coming into the warehouse is structured like this

{"Client ID":"1234567","client_name":"Kareem" }

when I use the function

JSON_EXTRACT_PATH_TEXT(COLUMN_NAME, 'Client ID')

it give me this error :

Invalid extraction path 'Client ID': invalid token at position 7.

is there another workaround to get the value for this key ? or for using this key with the function to get the value out of the JSON column ?

Body:
The following does work, which is supposed to be close to equivalent.  My example assumes your values are a string, since that is the input of the function you were trying to use:

WITH x AS (SELECT '{"Client ID":"1234567","client_name":"Kareem" }' as json_string)
SELECT parse_json(json_string):"Client ID"
FROM x;


问:
Connecting to Python socket from iOS Safari browser
I have a python socket listening on my computer's ip address on a specific port. I am using the standard python socket library with something like the following code:

```<code>listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind(server_address) # Server address is a tuple (HOST, PORT) with host being
                                   # something like 123.456.789.00 and port being 4000
listen_socket.listen()
client_connection, client_address = listen_socket.accept()
request_data = client_connection.recv(1024).decode('utf-8')
print(request_data)
</code>```

When I use Chrome on my iPhone to connect to the address, the rest of my code runs fine and processes the incoming request by sending an html page. When I use Safari, it loads for a while until it fails and a says "Safari cannot open the page because it could not connect to the server."

Funny enough, if I stay on the page, restart the server, and then reload the page using the refresh button, it connects fine. But trying to access the address through the url address does not work. Refreshing using the refresh button seems to work. Why is Safari having trouble connecting to my Python socket?

答:
Try increasing the backlog count in the listen_socket.listen() call.

I had a similar issue with a python 2 socket server and macOS Safari.  Safari would say it could not connect to the server, but Chrome/Firefox/IE/curl all worked without any errors. I changed this:

```<code>listen_socket.listen(1)
</code>```

To this:

```<code>listen_socket.listen(5)
</code>```

Safari then worked without any errors.  I am now using 128 instead of 5, not sure what the default is in Python 3.

When set to 1, in the python server I would see Safari connect, but then socket.recv() would never return.

Body:
I have a python socket listening on my computer's ip address on a specific port. I am using the standard python socket library with something like the following code:

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind(server_address) # Server address is a tuple (HOST, PORT) with host being
                                   # something like 123.456.789.00 and port being 4000
listen_socket.listen()
client_connection, client_address = listen_socket.accept()
request_data = client_connection.recv(1024).decode('utf-8')
print(request_data)

When I use Chrome on my iPhone to connect to the address, the rest of my code runs fine and processes the incoming request by sending an html page. When I use Safari, it loads for a while until it fails and a says "Safari cannot open the page because it could not connect to the server."

Funny enough, if I stay on the page, restart the server, and then reload the page using the refresh button, it connects fine. But trying to access the address through the url address does not work. Refreshing using the refresh button seems to work. Why is Safari having trouble connecting to my Python socket?

Body:
Try increasing the backlog count in the listen_socket.listen() call.

I had a similar issue with a python 2 socket server and macOS Safari.  Safari would say it could not connect to the server, but Chrome/Firefox/IE/curl all worked without any errors. I changed this:

listen_socket.listen(1)

To this:

listen_socket.listen(5)

Safari then worked without any errors.  I am now using 128 instead of 5, not sure what the default is in Python 3.

When set to 1, in the python server I would see Safari connect, but then socket.recv() would never return.


问:
not able to run same class with diff job name and group, run at same time
I am working on a quartz scheduler.
I have created a class(com.test.job.MyClass) that implements Job
MyClass contains some dynamic values which pass in DataMap while scheduling. based on datamap value, i need to invoke the rest API by passing this data map value.

So in my DB, I defined job having className, jobName, groupName and operationValue. I have defined multiple entries in DB having

Like JOB-1 is

```<code>jobClassName= com.test.job.MyClass
jobName=TEST1
groupName =group
operationValue =ADD
</code>```

Like JOB-2 is

```<code>jobClassName= com.test.job.MyClass
jobName=TEST2
groupName =group
operationValue =ADD
</code>```

I am trying to schedule these 2 jobs having same Cron expression. but only the TEST1 job is executing. Test2 is not. even the jobName is different

```<code>Scheduler scheduler = scheduleFactory.getScheduler();
        try {
            Class<? extends Job> jobClassName = (Class<? extends Job>) Class.forName(className);
            JobDetail jobDetails = JobBuilder.newJob(jobClassName).withIdentity(jobName, groupName).build();
            putIntoDataMap(job, jobDetails.getJobDataMap(), user);
            CronTrigger trigger = newTrigger().withIdentity(jobName, groupName)
                    .withSchedule(cronSchedule(cronExpression).inTimeZone("Asia/Kolkata")).build();

            scheduler.scheduleJob(jobDetails, trigger);
        } catch (SchedulerException | ClassNotFoundException ex) {
            throw new CredityRuntimeException(CredityErrorCodes.INVALID_TRIGGER.name(), ex);
        }
</code>```

in the implemented class, I can see ADD operation, so it means only TEST1 was run. I expect both should run.

```<code>public class MyClass implements Job {

@Override
    public void execute(JobExecutionContext context) throws JobExecutionException
    {
        .....
         String operationValue=jobDataMap.get("Operation");
    }
}
</code>```

答:
Very strange. You may want to use QuartzDesk (I am biased here) or some other alternative Quartz management GUI tool to:

(1) connect to your Quartz instance and check the registered jobs and triggers. In your case, you should see two jobs TEST1 and TEST2.

(2) try to manually execute the registered jobs to see if your jobs can be invoked.

Note: The free QuartzDesk Lite Edition should be entirely sufficient and help you quickly identify the issue.

One thing to be aware of is the job durability flag. Non-durable Quartz jobs are automatically discarded by Quartz when there are no associated triggers that are expected to fire the job in the future. You did not include your cron expressions for TEST1 and TEST2 so you may want to call storeDurably when building your job details just in case...

Body:
I am working on a quartz scheduler.
I have created a class(com.test.job.MyClass) that implements Job
MyClass contains some dynamic values which pass in DataMap while scheduling. based on datamap value, i need to invoke the rest API by passing this data map value.

So in my DB, I defined job having className, jobName, groupName and operationValue. I have defined multiple entries in DB having

Like JOB-1 is

jobClassName= com.test.job.MyClass
jobName=TEST1
groupName =group
operationValue =ADD

Like JOB-2 is

jobClassName= com.test.job.MyClass
jobName=TEST2
groupName =group
operationValue =ADD

I am trying to schedule these 2 jobs having same Cron expression. but only the TEST1 job is executing. Test2 is not. even the jobName is different

Scheduler scheduler = scheduleFactory.getScheduler();
        try {
            Class<? extends Job> jobClassName = (Class<? extends Job>) Class.forName(className);
            JobDetail jobDetails = JobBuilder.newJob(jobClassName).withIdentity(jobName, groupName).build();
            putIntoDataMap(job, jobDetails.getJobDataMap(), user);
            CronTrigger trigger = newTrigger().withIdentity(jobName, groupName)
                    .withSchedule(cronSchedule(cronExpression).inTimeZone("Asia/Kolkata")).build();

            scheduler.scheduleJob(jobDetails, trigger);
        } catch (SchedulerException | ClassNotFoundException ex) {
            throw new CredityRuntimeException(CredityErrorCodes.INVALID_TRIGGER.name(), ex);
        }

in the implemented class, I can see ADD operation, so it means only TEST1 was run. I expect both should run.

public class MyClass implements Job {

@Override
    public void execute(JobExecutionContext context) throws JobExecutionException
    {
        .....
         String operationValue=jobDataMap.get("Operation");
    }
}


问:
Change default text color in Docusaurus v2
In Docusaurus v2 I can override the default text color for each class as:

```<code>.features {
  display: flex;
  align-items: center;
  padding: 2rem 0;
  width: 100%;
  color: red;
}
</code>```

I don't like this approach because it makes it harder to define separate colors for the dark and light theme.

By default the text color is set to black in light theme, and white in dark theme. However, I cannot seem to find where these are defined.

I am interested in modifying these defaults, where are they defined?

Is this the recommended way of styling the default text color?

答:
Use the browser to inspect HTML and see which CSS variables affect the text color.

Modify the var(--ifm-font-color-base) color by adding the following CSS to custom.css.

:root {
  --ifm-font-color-base: #000;
}
```

Body:
In Docusaurus v2 I can override the default text color for each class as:

.features {
  display: flex;
  align-items: center;
  padding: 2rem 0;
  width: 100%;
  color: red;
}

I don't like this approach because it makes it harder to define separate colors for the dark and light theme.

By default the text color is set to black in light theme, and white in dark theme. However, I cannot seem to find where these are defined.

I am interested in modifying these defaults, where are they defined?

Is this the recommended way of styling the default text color?


问:
Concat column name in SQL
Is there a way to concat a column name as t26.crea+ted_at?

```<code>SELECT t0.id, t0.user, t26.`crea`+`ted_at` FROM users t0
RIGHT OUTER JOIN user_logs t26 ON (t0.id = t26.aid)
WHERE ((t26.`crea`+`ted_at` >= '2018-01-01 00:00:00') AND (t26.`crea`+`ted_at` <= '2019-01-31 23:59:59'));
</code>```

I simply need to fetch data from a certain date but a system is filtering the created_at column because it contains the keyword create

答:
When you concatenate some column , it becomes string and you can't use SQL operator (>=, <=, >, <) to compare string value.

But you can try this to fetch your data between two date:

```<code>SELECT t0.id, t0.user, t26.`crea` `ted_at`
FROM users t0
RIGHT OUTER JOIN user_logs t26 ON (t0.id = t26.aid)
WHERE (
            (t26.`crea` >= '2018-01-01' AND ted_at >= '00:00:00')
            AND
            (t26.`crea` <= '2019-01-31' AND ted_at <= '23:59:59')
      )
</code>```

Title: Concat column name in SQL

Body:
Is there a way to concat a column name as t26.crea+ted_at?

SELECT t0.id, t0.user, t26.`crea`+`ted_at` FROM users t0
RIGHT OUTER JOIN user_logs t26 ON (t0.id = t26.aid)
WHERE ((t26.`crea`+`ted_at` >= '2018-01-01 00:00:00') AND (t26.`crea`+`ted_at` <= '2019-01-31 23:59:59'));

I simply need to fetch data from a certain date but a system is filtering the created_at column because it contains the keyword create

Body:
When you concatenate some column , it becomes string and you can't use SQL operator (>=, <=, >, <) to compare string value.

But you can try this to fetch your data between two date:

SELECT t0.id, t0.user, t26.`crea` `ted_at`
FROM users t0
RIGHT OUTER JOIN user_logs t26 ON (t0.id = t26.aid)
WHERE (
            (t26.`crea` >= '2018-01-01' AND ted_at >= '00:00:00')
            AND
            (t26.`crea` <= '2019-01-31' AND ted_at <= '23:59:59')
      )


问:
Beautiful Soup Can't Redact Phone Number with Parentheses
I'm trying to redact phone number information from an html file ... and while I can identify all of the phone numbers easily enough I can't figure out why I am unable to replace the phone numbers that have parentheses in them.  Sample below:

```<code>import re
from bs4 import BeautifulSoup

text = '''<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (555) 555-5555</li>
</ul><b>Category:</b> <ul><li>Title 2    </li><li>Fake Info</li></ul>

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: 555-222-2222 | Record Number#:

 </html>'''

soup = BeautifulSoup(text, 'html.parser')

def find_phone_numbers(text):
    phones = re.findall(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", text)
    return phones

phones = find_phone_numbers(str(soup))

print(phones)

for i in phones:
    target = soup.find_all(text=re.compile(i, re.I))
    try:
        for v in target:
            v.replace_with(v.replace(i,'(XXX) XXX-XXXX'))
    except TypeError:
        pass;

print(soup)
</code>```

These are my results from running the above:

```<code>['(555) 555-5555', '(555) 111-1111', '555-222-2222']
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (555) 555-5555</li>
</ul><b>Category:</b> <ul><li>Title 2    </li><li>Fake Info</li></ul>

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:

 </div></body></html>
</code>```

答:
Slight change of approach. Get all li tags, then for each tag, replace the phone numbers with your mask, if a phone number exists. I have used an interim variable for that (temp_text), just to keep the code a bit more readable.

```<code>all_li=soup.find_all('li')

for li in all_li:
    temp_text=re.sub(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", '(XXX) XXX-XXXX', li.text)
    if temp_text:
        li.replace_with(temp_text)
</code>```

print(soup) output:

Body:
I'm trying to redact phone number information from an html file ... and while I can identify all of the phone numbers easily enough I can't figure out why I am unable to replace the phone numbers that have parentheses in them.  Sample below:

import re
from bs4 import BeautifulSoup

text = '''

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>

Redacted Redacted

 Contact Info

Position Title: My Fake Title

Email: Redacted@gmail.com

Phones: (555) 555-5555

Category:

Title 2

Fake Info

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: 555-222-2222 | Record Number#:

 '''

soup = BeautifulSoup(text, 'html.parser')

def find_phone_numbers(text):
    phones = re.findall(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", text)
    return phones

phones = find_phone_numbers(str(soup))

print(phones)

for i in phones:
    target = soup.find_all(text=re.compile(i, re.I))
    try:
        for v in target:
            v.replace_with(v.replace(i,'(XXX) XXX-XXXX'))
    except TypeError:
        pass;

print(soup)

These are my results from running the above:

['(555) 555-5555', '(555) 111-1111', '555-222-2222']

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>

Redacted Redacted

 Contact Info

Position Title: My Fake Title

Email: Redacted@gmail.com

Phones: (555) 555-5555

Category:

Title 2

Fake Info

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:

Body:
Slight change of approach. Get all li tags, then for each tag, replace the phone numbers with your mask, if a phone number exists. I have used an interim variable for that (temp_text), just to keep the code a bit more readable.

all_li=soup.find_all('li')

for li in all_li:
    temp_text=re.sub(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", '(XXX) XXX-XXXX', li.text)
    if temp_text:
        li.replace_with(temp_text)

print(soup) output:


问:
json.decode() Unexpected end of input (at character 1)
I am facing a anonymus closure error in flutter while signing in a user. It worked a few days before but now its not working, I dont no why. So please help and thanks in advance..Whenever i fill the details and tap on the signin button it throws the below error---</p>

```<code>E/flutter ( 2914): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 2914): FormatException: Unexpected end of input (at character 1)
E/flutter ( 2914):
E/flutter ( 2914): ^
E/flutter ( 2914):
E/flutter ( 2914): #0      _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1358:5)
E/flutter ( 2914): #1      _ChunkedJsonParser.close (dart:convert/runtime/libconvert_patch.dart:511:7)
E/flutter ( 2914): #2      _parseJson (dart:convert/runtime/libconvert_patch.dart:30:10)
E/flutter ( 2914): #3      JsonDecoder.convert (dart:convert/json.dart:540:36)
E/flutter ( 2914): #4      JsonCodec.decode (dart:convert/json.dart:167:41)
E/flutter ( 2914): #5      _SignInState._login.<anonymous closure> (package:restaurant_app/signin.dart:81:23)
</code>```

```<code>import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:restaurant_app/globalVar.dart';
import 'package:restaurant_app/homescreen.dart';
 import 'package:flutter_secure_storage/flutter_secure_storage.dart';
 import 'package:restaurant_app/signup.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_html_view/html_parser.dart';

class SignIn extends StatefulWidget {
 @override
_SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> with SingleTickerProviderStateMixin
{
TabController controller;
TextEditingController _email = new TextEditingController();
TextEditingController _password = new TextEditingController();
bool loading;

 final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>
();

@override
void initState() {
// TODO: implement initState
super.initState();
controller = new TabController(length: 2, vsync: this);
loading = false;
_email = new TextEditingController(text: "rajeshvishnani");
_password = new TextEditingController(text: "Rajesh@MaaKiRasoi");
}

@override
void dispose() {
// TODO: implement dispose
super.dispose();
controller.dispose();
setState(() {
  loading = false;
});
_email.dispose();
_password.dispose();
}

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
bool _autoValidate = false;

Future _writer(String username, String password, String token) async {
final storage = new FlutterSecureStorage();
await storage.write(key: authTokenKeys, value: token);
print(await storage.read(key: authTokenKeys));
await storage.write(key: nameKeys, value: username);
print(await storage.read(key: nameKeys));
await storage.write(key: passwordKeys, value: password);
}

  static final String authTokenKeys = 'auth_token';
static final String nameKeys = 'username';
static final String passwordKeys = 'password';

_login(username, password) async {
setState(() {
  loading = true;
});

var body = json.encode({
  "username": username,
  "password": password,
});

Map<String, String> headers = {
  'Content-type': 'application/json',
  'Accept': 'application/json',
};

await http
    .post("${GlobalVar.Ip}/wp-json/jwt-auth/v1/token",
        body: body, headers: headers)
    .then((response) {
  var body = json.decode(response.body);

  if (response.statusCode == 200) {
    // TODO: you need to store body['token'] to use in some authentication
    loading = false;
    _writer(_email.text, _password.text, body['token']);
    Navigator.pushReplacement(context,
        MaterialPageRoute(builder: (BuildContext ctx) => HomePage()));
  } else {
    // TODO: alert message
    final snackBar = SnackBar(
      content: Text(body['message']),
    );
    _scaffoldKey.currentState.showSnackBar(snackBar);
  }
  setState(() {
    loading = false;
  });
  });
}

@override
 Widget build(BuildContext context) {
return Scaffold(
  key: _scaffoldKey,
  resizeToAvoidBottomPadding: false,
  body: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('images/art.png'),
        fit: BoxFit.fill,
        colorFilter: ColorFilter.mode(
            Colors.white12.withOpacity(0.2), BlendMode.dstATop),
      ),
    ),
    child: ListView(
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      children: <Widget>[
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Align(
          alignment: Alignment.topCenter,
          child: CircleAvatar(
            backgroundColor: Colors.grey,
            radius: 55.0,
            backgroundImage: AssetImage('images/logo.png'),
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              height: MediaQuery.of(context).size.height / 300,
              child: new Center(
                child: new Container(
                  height: 10.0,
                  color: Colors.black12,
                ),
              ),
            ),
            Row(
              children: <Widget>[
                SizedBox(
                  width: MediaQuery.of(context).size.width / 4,
                ),
                Chip(
                  label: Text(
                    "SIGN IN",
                    style: TextStyle(color: Colors.white, fontSize: 18.0),
                  ),
                  backgroundColor: Color(0xFFD1A155),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width / 35,
                  child: Container(
                    width: MediaQuery.of(context).size.height / 12,
                    height: 2.0,
                    color: Colors.white,
                  ),
                ),
                Chip(
                  label: Text(
                    "SIGN UP",
                    style: TextStyle(color: Colors.white, fontSize: 18.0),
                  ),
                  backgroundColor: Colors.black87,
                ),
              ],
            )
          ],
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 35,
        ),
        Align(
            alignment: Alignment.center,
            child: Text(
              "Welcome back!",
              style: TextStyle(
                fontSize: 20.0,
                color: Color(0xFFD1A155),
              ),
            )),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Form(
          key: _formKey,
          autovalidate: _autoValidate,
          child: Column(
            children: <Widget>[
              Theme(
                data: ThemeData(
                  hintColor: Colors.black26,
                  primaryColor: Color(0xFFD1A155),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: TextFormField(
                    keyboardType: TextInputType.emailAddress,
                    //validator: _email.text.isEmpty?:null,
                    controller: _email,

                    decoration: InputDecoration(
                        border:
                            OutlineInputBorder(borderSide: BorderSide()),
                        prefixIcon: Icon(
                          Icons.email,
                          color: Color(0xFFD1A155),
                        ),
                        hintText: 'Email Address',
                        hintStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w400)),
                  ),
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height / 45,
              ),
              Theme(
                data: ThemeData(
                    primaryColor: Color(0xFFD1A155),
                    hintColor: Colors.black26),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    obscureText: true,
                    controller: _password,
                  decoration: InputDecoration(
                        border:
                            OutlineInputBorder(borderSide: BorderSide()),
                        prefixIcon: Icon(
                          Icons.lock,
                          color: Color(0xFFD1A155),
                        ),
                        hintText: 'Password',
                        hintStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w400)),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 15.0, left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        ActionChip(
                          onPressed: () {},
                          avatar: Checkbox(
                            value: false,
                            onChanged: (bool z) {
                              print(z);
                            },
                            activeColor: Color(0xFFD1A155),
                          ),
                          label: Text("Remember Me"),
                          backgroundColor: Colors.transparent,
                        ),
                      ],
                    ),
                    Text(
                      "Forgot Password?",
                      style: TextStyle(
                        color: Color(0xFFD1A155),
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                child: InkWell(
                  onTap: () {
                    _login(_email.text, _password.text);
         //                        Navigator.push(
        //                            context,
    //                            MaterialPageRoute(
     //                                builder: (context) => HomePage()));
                  },
                  child: loading
                      ? CircularProgressIndicator()
                      : Container(
                          height: MediaQuery.of(context).size.height / 13,
                          //width: MediaQuery.of(context).size.height / 1.8,
                          decoration: BoxDecoration(
                            color: Color(0xFFD1A155),
                            borderRadius: BorderRadius.circular(5.0),
                          ),
                          child: Center(
                            child: Text(
                              "LOGIN",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 18.0),
                            ),
                          ),
                        ),
                ),
              )
            ],
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 15,
        ),
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              height: 2.0,
              child: new Center(
                child: new Container(
                  height: 10.0,
                  color: Colors.black12,
                ),
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height / 18,
              width: MediaQuery.of(context).size.height / 11,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(23.0),
                  color: Colors.white,
                  border: Border.all(color: Colors.black12)),
              child: Center(
                  child: Text(
                "OR",
                style: TextStyle(fontSize: 18.0),
              )),
            ),
          ],
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15.0, right: 15.0),
          child: Row(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height / 13,
                width: MediaQuery.of(context).size.width / 2.2,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: Colors.white,
                    border: Border.all(color: Colors.black12)),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 18.0,
                    ),
                    Icon(Icons.tag_faces),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Facebook",
                      style: TextStyle(fontSize: 22.0, color: Colors.blue),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width / 40,
              ),
              Container(
                height: MediaQuery.of(context).size.height / 13,
                width: MediaQuery.of(context).size.width / 2.3,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: Colors.white,
                    border: Border.all(color: Colors.black12)),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 18.0,
                    ),
                    Icon(Icons.tag_faces),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Google+",
                      style: TextStyle(fontSize: 22.0, color: Colors.red),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 20,
        ),
        Align(
          alignment: Alignment.center,
          child: InkWell(
            onTap: () => Navigator.push(
                context, MaterialPageRoute(builder: (context) => SignUp())),
            child: RichText(
                text: TextSpan(
                    text: "Don't have an account?",
                    style: TextStyle(fontSize: 20.0, color: Colors.black87),
                    children: <TextSpan>[
                  TextSpan(
                      text: ' Sign up',
                      style: TextStyle(
                          color: Color(0xFFD1A155),
                          fontWeight: FontWeight.bold)),
                ])),
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
      ],
    ),
  ),
  );
 }
}
</code>```

答: Print your body and double check you aren't trying to decode an array rather than on object. </p>

Body:
I am facing a anonymus closure error in flutter while signing in a user. It worked a few days before but now its not working, I dont no why. So please help and thanks in advance..Whenever i fill the details and tap on the signin button it throws the below error---

E/flutter ( 2914): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 2914): FormatException: Unexpected end of input (at character 1)
E/flutter ( 2914):
E/flutter ( 2914): ^
E/flutter ( 2914):
E/flutter ( 2914): #0      _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1358:5)
E/flutter ( 2914): #1      _ChunkedJsonParser.close (dart:convert/runtime/libconvert_patch.dart:511:7)
E/flutter ( 2914): #2      _parseJson (dart:convert/runtime/libconvert_patch.dart:30:10)
E/flutter ( 2914): #3      JsonDecoder.convert (dart:convert/json.dart:540:36)
E/flutter ( 2914): #4      JsonCodec.decode (dart:convert/json.dart:167:41)
E/flutter ( 2914): #5      _SignInState._login.<anonymous closure> (package:restaurant_app/signin.dart:81:23)

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:restaurant_app/globalVar.dart';
import 'package:restaurant_app/homescreen.dart';
 import 'package:flutter_secure_storage/flutter_secure_storage.dart';
 import 'package:restaurant_app/signup.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_html_view/html_parser.dart';

class SignIn extends StatefulWidget {
 @override
_SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> with SingleTickerProviderStateMixin
{
TabController controller;
TextEditingController _email = new TextEditingController();
TextEditingController _password = new TextEditingController();
bool loading;

 final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>
();

@override
void initState() {
// TODO: implement initState
super.initState();
controller = new TabController(length: 2, vsync: this);
loading = false;
_email = new TextEditingController(text: "rajeshvishnani");
_password = new TextEditingController(text: "Rajesh@MaaKiRasoi");
}

@override
void dispose() {
// TODO: implement dispose
super.dispose();
controller.dispose();
setState(() {
  loading = false;
});
_email.dispose();
_password.dispose();
}

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
bool _autoValidate = false;

Future _writer(String username, String password, String token) async {
final storage = new FlutterSecureStorage();
await storage.write(key: authTokenKeys, value: token);
print(await storage.read(key: authTokenKeys));
await storage.write(key: nameKeys, value: username);
print(await storage.read(key: nameKeys));
await storage.write(key: passwordKeys, value: password);
}

  static final String authTokenKeys = 'auth_token';
static final String nameKeys = 'username';
static final String passwordKeys = 'password';

_login(username, password) async {
setState(() {
  loading = true;
});

var body = json.encode({
  "username": username,
  "password": password,
});

Map<String, String> headers = {
  'Content-type': 'application/json',
  'Accept': 'application/json',
};

await http
    .post("${GlobalVar.Ip}/wp-json/jwt-auth/v1/token",
        body: body, headers: headers)
    .then((response) {
  var body = json.decode(response.body);

  if (response.statusCode == 200) {
    // TODO: you need to store body['token'] to use in some authentication
    loading = false;
    _writer(_email.text, _password.text, body['token']);
    Navigator.pushReplacement(context,
        MaterialPageRoute(builder: (BuildContext ctx) => HomePage()));
  } else {
    // TODO: alert message
    final snackBar = SnackBar(
      content: Text(body['message']),
    );
    _scaffoldKey.currentState.showSnackBar(snackBar);
  }
  setState(() {
    loading = false;
  });
  });
}

@override
 Widget build(BuildContext context) {
return Scaffold(
  key: _scaffoldKey,
  resizeToAvoidBottomPadding: false,
  body: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('images/art.png'),
        fit: BoxFit.fill,
        colorFilter: ColorFilter.mode(
            Colors.white12.withOpacity(0.2), BlendMode.dstATop),
      ),
    ),
    child: ListView(
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      children: <Widget>[
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Align(
          alignment: Alignment.topCenter,
          child: CircleAvatar(
            backgroundColor: Colors.grey,
            radius: 55.0,
            backgroundImage: AssetImage('images/logo.png'),
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              height: MediaQuery.of(context).size.height / 300,
              child: new Center(
                child: new Container(
                  height: 10.0,
                  color: Colors.black12,
                ),
              ),
            ),
            Row(
              children: <Widget>[
                SizedBox(
                  width: MediaQuery.of(context).size.width / 4,
                ),
                Chip(
                  label: Text(
                    "SIGN IN",
                    style: TextStyle(color: Colors.white, fontSize: 18.0),
                  ),
                  backgroundColor: Color(0xFFD1A155),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width / 35,
                  child: Container(
                    width: MediaQuery.of(context).size.height / 12,
                    height: 2.0,
                    color: Colors.white,
                  ),
                ),
                Chip(
                  label: Text(
                    "SIGN UP",
                    style: TextStyle(color: Colors.white, fontSize: 18.0),
                  ),
                  backgroundColor: Colors.black87,
                ),
              ],
            )
          ],
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 35,
        ),
        Align(
            alignment: Alignment.center,
            child: Text(
              "Welcome back!",
              style: TextStyle(
                fontSize: 20.0,
                color: Color(0xFFD1A155),
              ),
            )),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Form(
          key: _formKey,
          autovalidate: _autoValidate,
          child: Column(
            children: <Widget>[
              Theme(
                data: ThemeData(
                  hintColor: Colors.black26,
                  primaryColor: Color(0xFFD1A155),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: TextFormField(
                    keyboardType: TextInputType.emailAddress,
                    //validator: _email.text.isEmpty?:null,
                    controller: _email,

                    decoration: InputDecoration(
                        border:
                            OutlineInputBorder(borderSide: BorderSide()),
                        prefixIcon: Icon(
                          Icons.email,
                          color: Color(0xFFD1A155),
                        ),
                        hintText: 'Email Address',
                        hintStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w400)),
                  ),
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height / 45,
              ),
              Theme(
                data: ThemeData(
                    primaryColor: Color(0xFFD1A155),
                    hintColor: Colors.black26),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    obscureText: true,
                    controller: _password,
                  decoration: InputDecoration(
                        border:
                            OutlineInputBorder(borderSide: BorderSide()),
                        prefixIcon: Icon(
                          Icons.lock,
                          color: Color(0xFFD1A155),
                        ),
                        hintText: 'Password',
                        hintStyle: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w400)),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 15.0, left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        ActionChip(
                          onPressed: () {},
                          avatar: Checkbox(
                            value: false,
                            onChanged: (bool z) {
                              print(z);
                            },
                            activeColor: Color(0xFFD1A155),
                          ),
                          label: Text("Remember Me"),
                          backgroundColor: Colors.transparent,
                        ),
                      ],
                    ),
                    Text(
                      "Forgot Password?",
                      style: TextStyle(
                        color: Color(0xFFD1A155),
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                child: InkWell(
                  onTap: () {
                    _login(_email.text, _password.text);
         //                        Navigator.push(
        //                            context,
    //                            MaterialPageRoute(
     //                                builder: (context) => HomePage()));
                  },
                  child: loading
                      ? CircularProgressIndicator()
                      : Container(
                          height: MediaQuery.of(context).size.height / 13,
                          //width: MediaQuery.of(context).size.height / 1.8,
                          decoration: BoxDecoration(
                            color: Color(0xFFD1A155),
                            borderRadius: BorderRadius.circular(5.0),
                          ),
                          child: Center(
                            child: Text(
                              "LOGIN",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 18.0),
                            ),
                          ),
                        ),
                ),
              )
            ],
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 15,
        ),
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              height: 2.0,
              child: new Center(
                child: new Container(
                  height: 10.0,
                  color: Colors.black12,
                ),
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height / 18,
              width: MediaQuery.of(context).size.height / 11,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(23.0),
                  color: Colors.white,
                  border: Border.all(color: Colors.black12)),
              child: Center(
                  child: Text(
                "OR",
                style: TextStyle(fontSize: 18.0),
              )),
            ),
          ],
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15.0, right: 15.0),
          child: Row(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height / 13,
                width: MediaQuery.of(context).size.width / 2.2,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: Colors.white,
                    border: Border.all(color: Colors.black12)),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 18.0,
                    ),
                    Icon(Icons.tag_faces),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Facebook",
                      style: TextStyle(fontSize: 22.0, color: Colors.blue),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width / 40,
              ),
              Container(
                height: MediaQuery.of(context).size.height / 13,
                width: MediaQuery.of(context).size.width / 2.3,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: Colors.white,
                    border: Border.all(color: Colors.black12)),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 18.0,
                    ),
                    Icon(Icons.tag_faces),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Google+",
                      style: TextStyle(fontSize: 22.0, color: Colors.red),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 20,
        ),
        Align(
          alignment: Alignment.center,
          child: InkWell(
            onTap: () => Navigator.push(
                context, MaterialPageRoute(builder: (context) => SignUp())),
            child: RichText(
                text: TextSpan(
                    text: "Don't have an account?",
                    style: TextStyle(fontSize: 20.0, color: Colors.black87),
                    children: <TextSpan>[
                  TextSpan(
                      text: ' Sign up',
                      style: TextStyle(
                          color: Color(0xFFD1A155),
                          fontWeight: FontWeight.bold)),
                ])),
          ),
        ),
        SizedBox(
          height: MediaQuery.of(context).size.height / 30,
        ),
      ],
    ),
  ),
  );
 }
}