问:
What is the best way in WebMatrix to query WCF services?
I have an ASP.Net project using the Razor view engine which currently queries various databases directly with WebMatrix.Data.Database.Open.

I'm trying to migrate all direct database access to Web Services using WCF so that I get consistent business logic.  In doing this, I have also enabled the WCF service to be "httpGetEnabled".  This allows me to use Excel Macros to query the same web service.

My question is, what is the best way to query these web services from a Razor/WebMatrix page?

Should I JSON enable my WCF service and use the WebMatrix JSON helper?  Or should I be using JQuery to get the xml?

I would assume the former would be the best way, but how do I JSON enable my WCF service?  I remember seeing a video that allowed me to specify an additional query parameter to the WCF request to get JSON, but I can't find it again.

Any thoughts or pointers in the right direction would be greatly appreciated.

Kind regards.

Edit:

I've recently seen this on Stack Overflow :
Client Side Binding using by Converting the WCF Services to JSON

On following this, I went to the MSDN article referred to around WebHttpBehavior.  I have since added "automaticFormatSelectionEnabled=true" to the webHttp element in Web.config.  In addition, I added the following code which then allowed me to specify "format=json" as a query parameter:

```<code>string formatQueryStringValue = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
if (!string.IsNullOrEmpty(formatQueryStringValue))
{
    if (formatQueryStringValue.Equals("xml", System.StringComparison.OrdinalIgnoreCase))
    {
        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
    }
    else if (formatQueryStringValue.Equals("json", System.StringComparison.OrdinalIgnoreCase))
    {
        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
    }
}
</code>```

I now just need to work out how to use the WebMatrix JSON helper to get the results... Will update when I get some more information.

Edit 2

Hmm, I don't think that helped... Now I can get JSON from the webservice, but the JSON web helper only seems to help if you have some JSON data already.  I'm just not sure how to get that JSON data which I can then use the JSON Helper to convert it (decode) into a class.

So I guess my question now is, how do I get JSON data and then bridge that to WebMatrix/Razor for use in a WebGrid?

答:
From all I read you would want to know what is the best practice in this case if I am correct.

The best practice from what I know is to not make your website query through the wcf at all.

why ?
-Because their both located on your server... no point creating a connection again to just get data.
They should both have direct connection to the data which for you is webmatrix....
You would use WCF for other applications like a .exe you created which stores farm animals.

Extra note: you can add the WCF to your ASP.NEt project and both access same database which would be best case if you still require it.

Body:
I have an ASP.Net project using the Razor view engine which currently queries various databases directly with WebMatrix.Data.Database.Open.

I'm trying to migrate all direct database access to Web Services using WCF so that I get consistent business logic.  In doing this, I have also enabled the WCF service to be "httpGetEnabled".  This allows me to use Excel Macros to query the same web service.

My question is, what is the best way to query these web services from a Razor/WebMatrix page?

Should I JSON enable my WCF service and use the WebMatrix JSON helper?  Or should I be using JQuery to get the xml?

I would assume the former would be the best way, but how do I JSON enable my WCF service?  I remember seeing a video that allowed me to specify an additional query parameter to the WCF request to get JSON, but I can't find it again.

Any thoughts or pointers in the right direction would be greatly appreciated.

Kind regards.

Edit:

I've recently seen this on Stack Overflow :
Client Side Binding using by Converting the WCF Services to JSON

On following this, I went to the MSDN article referred to around WebHttpBehavior.  I have since added "automaticFormatSelectionEnabled=true" to the webHttp element in Web.config.  In addition, I added the following code which then allowed me to specify "format=json" as a query parameter:

string formatQueryStringValue = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
if (!string.IsNullOrEmpty(formatQueryStringValue))
{
    if (formatQueryStringValue.Equals("xml", System.StringComparison.OrdinalIgnoreCase))
    {
        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
    }
    else if (formatQueryStringValue.Equals("json", System.StringComparison.OrdinalIgnoreCase))
    {
        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
    }
}

I now just need to work out how to use the WebMatrix JSON helper to get the results... Will update when I get some more information.

Edit 2

Hmm, I don't think that helped... Now I can get JSON from the webservice, but the JSON web helper only seems to help if you have some JSON data already.  I'm just not sure how to get that JSON data which I can then use the JSON Helper to convert it (decode) into a class.

So I guess my question now is, how do I get JSON data and then bridge that to WebMatrix/Razor for use in a WebGrid?


来源: stackexchange

问:
IPython crashing when I hold any key
When I ssh into a particular remote machine and start an IPython session, it crashed whenever I hold a key for about half a second (e.g. backspace key).

The error output is pasted below:

```<code>  File "/home/zach/local/anaconda3/bin/ipython", line 11, in <module>
    sys.exit(start_ipython())
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/__init__.py", line 125, in start_ipython
    return launch_new_instance(argv=argv, **kwargs)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/ipapp.py", line 356, in start
    self.shell.mainloop()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/interactiveshell.py", line 498, in mainloop
    self.interact()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/interactiveshell.py", line 481, in interact
    code = self.prompt_for_code()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/interactiveshell.py", line 410, in prompt_for_code
    **self._extra_prompt_options())
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/shortcuts/prompt.py", line 738, in prompt
    return run_sync()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/shortcuts/prompt.py", line 727, in run_sync
    return self.app.run(inputhook=self.inputhook, pre_run=pre_run2)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/application/application.py", line 709, in run
    return run()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/application/application.py", line 682, in run
    run_until_complete(f, inputhook=inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/defaults.py", line 123, in run_until_complete
    return get_event_loop().run_until_complete(future, inputhook=inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/posix.py", line 66, in run_until_complete
    self._run_once(inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/posix.py", line 85, in _run_once
    self._inputhook_context.call_inputhook(ready, inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/inputhook.py", line 78, in call_inputhook
    threading.Thread(target=thread).start()
  File "/home/zach/local/anaconda3/lib/python3.7/threading.py", line 847, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread

If you suspect this is an IPython bug, please report it at:
    https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@python.org

You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.

Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
    %config Application.verbose_crash=True
</code>```

It drops me from here into a broken bash session where my keystrokes do not appear on screen, although I can execute commands such as ls, man, pwd, ipython, etc. I can only kill the bash session by pressing Control D followed by Control C.  In particular, the message's suggestion that I press %tb and so forth is not possible.

Other programs are not competing for threads. Looking through the error, it looks like the an event loop is possibly trying to create a thread to handle every key press, and this eventually causes failure to allocate more threads. It seems a little far-fetched that this would be the issue though since holding a key down is surely expected behavior.

This seems potentially similar to the issue https://ipython.org/faq.html#ipython-crashes-under-os-x-when-using-the-arrow-keys.

It appears not to be a Python issue per se, since if I use Python rather than IPython the issue disappears. I initially used Anaconda ipython but also switched to the system ipython in /usr/bin/ipython with the same results. Also tried a clean install of Anaconda, with the same issue. Also tried a fresh install of Anaconda on a different machine with the same OS, and the issue did not occur.

I am looking for ideas to make progress on this issue. Any ideas are appreciated, and I will post follow-up data if needed.

Python 3.7.3 (default, Mar 27 2019, 22:11:17)
IPython 7.5.0
Ubuntu 18.04.2 LTS

答:
It is fixed now, but still somewhat mysterious to me. I followed the stack trace all the way down through CPython to the pthreads library calls. The pthreads documentation indicated that the error can essentially only arise if one is out of memory on the heap or if the max number of threads has been allocated. I used ulimit to set the virtual memory per process to unlimited (it had been ~3 GB). This resolved the issue.

So apparently the virtual memory limit interfered with the ability to allocate a thread. The obvious solution is that more memory was needed, although it is hard to believe that more than 3 GB is needed to respond to a key press. Another possibility is that the amount allocated per thread is a function of the virtual memory limit--I remember something like that in the pthreads documentation although it was a bit above my head.

ContentLicense: CC BY-SA 4.0

Title: IPython crashing when I hold any key

Body:
When I ssh into a particular remote machine and start an IPython session, it crashed whenever I hold a key for about half a second (e.g. backspace key).

The error output is pasted below:

  File "/home/zach/local/anaconda3/bin/ipython", line 11, in <module>
    sys.exit(start_ipython())
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/__init__.py", line 125, in start_ipython
    return launch_new_instance(argv=argv, **kwargs)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/ipapp.py", line 356, in start
    self.shell.mainloop()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/interactiveshell.py", line 498, in mainloop
    self.interact()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/interactiveshell.py", line 481, in interact
    code = self.prompt_for_code()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/IPython/terminal/interactiveshell.py", line 410, in prompt_for_code
    **self._extra_prompt_options())
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/shortcuts/prompt.py", line 738, in prompt
    return run_sync()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/shortcuts/prompt.py", line 727, in run_sync
    return self.app.run(inputhook=self.inputhook, pre_run=pre_run2)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/application/application.py", line 709, in run
    return run()
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/application/application.py", line 682, in run
    run_until_complete(f, inputhook=inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/defaults.py", line 123, in run_until_complete
    return get_event_loop().run_until_complete(future, inputhook=inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/posix.py", line 66, in run_until_complete
    self._run_once(inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/posix.py", line 85, in _run_once
    self._inputhook_context.call_inputhook(ready, inputhook)
  File "/home/zach/local/anaconda3/lib/python3.7/site-packages/prompt_toolkit/eventloop/inputhook.py", line 78, in call_inputhook
    threading.Thread(target=thread).start()
  File "/home/zach/local/anaconda3/lib/python3.7/threading.py", line 847, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread

If you suspect this is an IPython bug, please report it at:
    https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@python.org

You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.

Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
    %config Application.verbose_crash=True

It drops me from here into a broken bash session where my keystrokes do not appear on screen, although I can execute commands such as ls, man, pwd, ipython, etc. I can only kill the bash session by pressing Control D followed by Control C.  In particular, the message's suggestion that I press %tb and so forth is not possible.

Other programs are not competing for threads. Looking through the error, it looks like the an event loop is possibly trying to create a thread to handle every key press, and this eventually causes failure to allocate more threads. It seems a little far-fetched that this would be the issue though since holding a key down is surely expected behavior.

This seems potentially similar to the issue https://ipython.org/faq.html#ipython-crashes-under-os-x-when-using-the-arrow-keys.

It appears not to be a Python issue per se, since if I use Python rather than IPython the issue disappears. I initially used Anaconda ipython but also switched to the system ipython in /usr/bin/ipython with the same results. Also tried a clean install of Anaconda, with the same issue. Also tried a fresh install of Anaconda on a different machine with the same OS, and the issue did not occur.

I am looking for ideas to make progress on this issue. Any ideas are appreciated, and I will post follow-up data if needed.

Python 3.7.3 (default, Mar 27 2019, 22:11:17)
IPython 7.5.0
Ubuntu 18.04.2 LTS


问:
How to remove the camera feed in ARSCNView?
I'd like to replace the camera feed in ARSCNView as the camera quality is not as good as the native camera feed.

Does anyone know how to remove the camera feed in ARSCNView?

答:
You can simply do this on an instance of ARSCNView:

```<code>scene.background.contents = nil
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can simply do this on an instance of ARSCNView:

scene.background.contents = nil


问:
"pip install selenium" not working // using python 3 // windows 10
I cannot install selenium. I have python 3.7 and window 10.

These are some of the things i have tried and the outcome:

C:\Users\dani>pip install selenium
'pip' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>sudo pip install selenium
'sudo' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>pip3 install selenium
'pip3' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>conda install selenium
'conda' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>pip install -U selenium
'pip' is not recognized as an internal or external command,
operable program or batch file.

答:
If you didn't install it on your Windows, this might be the reason. Otherwise did you check if it's registered to PATH?

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

I had the same problem that you are having.
From the instructions given on the internet it is very clear that this command must be given from inside Python's IDLE interface, but that is wrong.
You should open a DOS command prompt as administrator and then execute the commands. To find out if PIP exists on your computer type at the DOS prompt (PIP) and press enter. wait a few moments and you will see the list of commands. If it does not work, PIP is not installed on your computer.


问:
Show microphone permission when denied
I have a button that when tap on it I have to check microphone permission.

For this reason I done this:

```<code>public func askMicrophoneAuthorization()
    {

        recordingSession = AVAudioSession.sharedInstance()
        recordingSession.requestRecordPermission() { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed
                    {
                        self.goToNextStep()

                    } else
                    {
                        self.denied()
                    }
                }
            }
 }
</code>```

my problem is this: when I tap on button and askMicrophoneAuthorization method is called, if its the first time that I ask the permission, the microphone system alert, with text inserted in plist file, shows and I can denied or not the permission. If I deny the permission and then I re-tap on button method self.denied() is executed and I dont see the microphone system alert.
Is it possibile to re-show the system-alert?

答:
It's not possible to show the system alert if the user has already denied.
The best you can do is to check the permission and if they're denied show an alert with a button that opens the app settings.</p>

```<code>func askPermissionIfNeeded() {
    switch AVAudioSession.sharedInstance().recordPermission {
    case undetermined:
        askMicrophoneAuthorization()
    case denied:
        let alert = UIAlertController(title: "Error", message: "Please allow microphone usage from settings", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Open settings", style: .default, handler: { action in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    case granted:
        goToNextStep()
    }
}
</code>```

Title: Show microphone permission when denied

Body:
I have a button that when tap on it I have to check microphone permission.

For this reason I done this:

public func askMicrophoneAuthorization()
    {

        recordingSession = AVAudioSession.sharedInstance()
        recordingSession.requestRecordPermission() { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed
                    {
                        self.goToNextStep()

                    } else
                    {
                        self.denied()
                    }
                }
            }
 }

my problem is this: when I tap on button and askMicrophoneAuthorization method is called, if its the first time that I ask the permission, the microphone system alert, with text inserted in plist file, shows and I can denied or not the permission. If I deny the permission and then I re-tap on button method self.denied() is executed and I dont see the microphone system alert.
Is it possibile to re-show the system-alert?

Body:
It's not possible to show the system alert if the user has already denied.
The best you can do is to check the permission and if they're denied show an alert with a button that opens the app settings.

func askPermissionIfNeeded() {
    switch AVAudioSession.sharedInstance().recordPermission {
    case undetermined:
        askMicrophoneAuthorization()
    case denied:
        let alert = UIAlertController(title: "Error", message: "Please allow microphone usage from settings", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Open settings", style: .default, handler: { action in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    case granted:
        goToNextStep()
    }
}


问:
~0 vs. !0 vs. 1 in C
I was reading some code today by someone I consider to be a reasonable programmer, and I noticed they used a =~0 to set a loop quit variable.

Is there any compelling reason to do this rather than simply quit = 1;?

I'm mostly just curious, before I go ahead and change it. Thanks!

Example:

```<code>while(!quit){
    ...;

    if(!strcmp(s, "q"))
        quit=~0;
}
</code>```

答:
There is no strong reason for that, unless some other code tests quit differently, such as testing any other bit.  !0 is one, but ~0 is -1 on all modern architectures.

On some architectures ~0 is faster than !0, though that should be optimized away by any decent compiler.

Title: ~0 vs. !0 vs. 1 in C

Body:
I was reading some code today by someone I consider to be a reasonable programmer, and I noticed they used a =~0 to set a loop quit variable.

Is there any compelling reason to do this rather than simply quit = 1;?

I'm mostly just curious, before I go ahead and change it. Thanks!

Example:

while(!quit){
    ...;

    if(!strcmp(s, "q"))
        quit=~0;
}


问:
What's the difference in the extend and append methods when applying them while creating a list and after having created the list
I'd like to know why when using the methods of append and extend while creating a list, the code returns none, but when they are applied after creating the list, the result is as expected.

Here is the code:

mylist = list(range(1,10))
mylist.extend(list(range(20,30)))
print(mylist)

mylist = list(range(1,10))
mylist.append(list(range(20,30)))
print(mylist)
```

<p>This results in <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]</code></p>

<p>And <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]</code></p>

<p>But when using</p>

<pre class="lang-py prettyprint-override"><code>mylist = list(range(1,10)).extend(list(range(20,30)))
print(mylist)

mylist = list(range(1,10)).extend(list(range(20,30)))
print(mylist)
</code>```

They both result in None

I am using python 3.7.0

答:
Neither list.extend nor list.append return values; they only modify their object.

If you want to create a new list and assign it to a different variable, you should use the + operator.

(But note that in your example code you're using .extend twice, rather than .append).

Body:
I'd like to know why when using the methods of append and extend while creating a list, the code returns none, but when they are applied after creating the list, the result is as expected.

Here is the code:

mylist = list(range(1,10))
mylist.extend(list(range(20,30)))
print(mylist)

mylist = list(range(1,10))
mylist.append(list(range(20,30)))
print(mylist)

This results in [1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

And [1, 2, 3, 4, 5, 6, 7, 8, 9, [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]

But when using

mylist = list(range(1,10)).extend(list(range(20,30)))
print(mylist)

mylist = list(range(1,10)).extend(list(range(20,30)))
print(mylist)

They both result in None

I am using python 3.7.0


问:
Eclipse shows nasty white cross in red circle with no message
This is me just trying to get rid of warning messages.

My logback xml files start rather baldly with "<configuration>..." which gives a warning about no "XML or DTD constraints".

So an answer here in SO suggests putting these two lines at the top of the file:

```<code><?XML version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
</code>```

When I do that, however, I get a nasty white cross in a red circle with no error message from Eclipse.

Can anyone identify the problem and hopefully the solution?

答:
Here's a link - might be helpful I think -  take a look at the first two/three answers:

No grammar constraints (DTD or XML schema) detected for the document

First try changing <!DOCTYPE configuration> to <!DOCTYPE xml>

Body:
This is me just trying to get rid of warning messages.

My logback xml files start rather baldly with "<configuration>..." which gives a warning about no "XML or DTD constraints".

So an answer here in SO suggests putting these two lines at the top of the file:

<?XML version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>

When I do that, however, I get a nasty white cross in a red circle with no error message from Eclipse.

Can anyone identify the problem and hopefully the solution?


问:
Ansible: How to extract values from a dictionary of lists
I'm trying to fetch the values from list of dict but unable to get the exact output, which is required

Using Linux server with installed versions of ansible 2.7.5 & jinja2 2.7.2 .

The below one is the list of dict value.

```<code>DOMAIN_GROUPS_ASSIGNMENT:

CACHE01:
    - domain_group: DG1
      is_active: true
    - domain_group: DG2
      is_active: true
    - domain_group: DG3
      is_active: true
  CACHE02:
    - domain_group: DG4
      is_active: true
    - domain_group: DG5
      is_active: true
    - domain_group: DG6
      is_active: true

  SCACHE01:
    - domain_group: DG1
      is_active: false
    - domain_group: DG2
      is_active: false
    - domain_group: DG3
      is_active: true
  SCACHE02:
    - domain_group: DG4
      is_active: false
    - domain_group: DG5
      is_active: false
    - domain_group: DG6
      is_active: false
</code>```

So far trying with the below code:

```<code>- debug:
      msg: "KEY: {{ item.key }}, VALUE: {{ item.value }}"
    loop: "{{ lookup('dict', DOMAIN_GROUPS_ASSIGNMENT) }}"
</code>```

Output which I'm getting is:

```<code>TASK [debug] ************************************************************************************************************************************************
task path: /u02/netcracker/reir1015_test/singlesite/test.yml:7
Friday 31 May 2019  08:54:59 -0400 (0:00:00.058)       0:00:00.897 ************
ok: [localhost] => (item={'key': u'CACHE01', 'value': [{u'is_active': True, u'domain_group': u'DG1'}, {u'is_active': True, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: CACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': True}, {u'domain_group': u'DG2', u'is_active': True}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'SCACHE02', 'value': [{u'is_active': False, u'domain_group': u'DG4'}, {u'is_active': False, u'domain_group': u'DG5'}, {u'is_active': False, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: SCACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': False}, {u'domain_group': u'DG5', u'is_active': False}, {u'domain_group': u'DG6', u'is_active': False}]

ok: [localhost] => (item={'key': u'SCACHE01', 'value': [{u'is_active': False, u'domain_group': u'DG1'}, {u'is_active': False, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: SCACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': False}, {u'domain_group': u'DG2', u'is_active': False}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'CACHE02', 'value': [{u'is_active': True, u'domain_group': u'DG4'}, {u'is_active': True, u'domain_group': u'DG5'}, {u'is_active': True, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: CACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': True}, {u'domain_group': u'DG5', u'is_active': True}, {u'domain_group': u'DG6', u'is_active': True}]
</code>```

Required output:

Result should be in dict format and should be stored in one variable.

I expect something like below in list or dict format:

CACHE01: True ,CACHE02: True, SCACHE01:False, SCACHE02: False

The above values should get stored in one variable.

答:
The task below

    - debug:
        msg: "{{ item.key }} {{ item.value|json_query('[].is_active') }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"
```
<p>gives:</p>
<pre class="lang-yaml prettyprint-override"><code>  msg: CACHE01 [True, True, True]
  msg: CACHE02 [True, True, True]
  msg: SCACHE01 [False, False, True]
  msg: SCACHE02 [False, False, False]
</code>```

The filter map, instead of json_query, gives the same result

    - debug:
        msg: "{{ item.key }} {{ item.value|map(attribute='is_active')|list }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"
```
<hr>
<p><strong>(In Ansible 2.3. and lower)</strong>
To combine the logical values let's create filter_plugins/bool_utils.py
with 2 filters <em>bool_and</em> and <em>bool_or</em> which apply Python functions <em>all(list)</em> and <em>any(list)</em> respectively</p>
<pre class="lang-py prettyprint-override"><code>    shell> cat filter_plugins/bool_utils.py
    def bool_and(h):
        return all(h)
    def bool_or(h):
        return any(h)
    class FilterModule(object):
        ''' utility filters for operating on list of Boolean '''
        def filters(self):
            return {
                'bool_and' : bool_and,
                'bool_or' : bool_or,
            }
</code>```

The task below with the filter bool_and

    - debug:
        msg: "{{ item.key }} {{ item.value|json_query('[].is_active')
                                          |bool_and }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>  msg: CACHE01 True
  msg: CACHE02 True
  msg: SCACHE01 False
  msg: SCACHE02 False
</code>```

The task below creates the list status

    - set_fact:
        status: "{{ status|default([]) +
                    [{item.key: item.value|json_query('[].is_active')
                                          |bool_and}] }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"
    - debug:
        var: status
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>  status:
  - CACHE01: true
  - CACHE02: true
  - SCACHE01: false
  - SCACHE02: false
</code>```

(In Ansible 2.4. and later) There are tests any, all available. The task below gives the same results

    - debug:
        msg: "{{ item.key }} {{ item.value|json_query('[].is_active') is all }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}
```

Body:
I'm trying to fetch the values from list of dict but unable to get the exact output, which is required

Using Linux server with installed versions of ansible 2.7.5 & jinja2 2.7.2 .

The below one is the list of dict value.

DOMAIN_GROUPS_ASSIGNMENT:

CACHE01:
    - domain_group: DG1
      is_active: true
    - domain_group: DG2
      is_active: true
    - domain_group: DG3
      is_active: true
  CACHE02:
    - domain_group: DG4
      is_active: true
    - domain_group: DG5
      is_active: true
    - domain_group: DG6
      is_active: true

  SCACHE01:
    - domain_group: DG1
      is_active: false
    - domain_group: DG2
      is_active: false
    - domain_group: DG3
      is_active: true
  SCACHE02:
    - domain_group: DG4
      is_active: false
    - domain_group: DG5
      is_active: false
    - domain_group: DG6
      is_active: false

So far trying with the below code:

- debug:
      msg: "KEY: {{ item.key }}, VALUE: {{ item.value }}"
    loop: "{{ lookup('dict', DOMAIN_GROUPS_ASSIGNMENT) }}"

Output which I'm getting is:

TASK [debug] ************************************************************************************************************************************************
task path: /u02/netcracker/reir1015_test/singlesite/test.yml:7
Friday 31 May 2019  08:54:59 -0400 (0:00:00.058)       0:00:00.897 ************
ok: [localhost] => (item={'key': u'CACHE01', 'value': [{u'is_active': True, u'domain_group': u'DG1'}, {u'is_active': True, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: CACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': True}, {u'domain_group': u'DG2', u'is_active': True}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'SCACHE02', 'value': [{u'is_active': False, u'domain_group': u'DG4'}, {u'is_active': False, u'domain_group': u'DG5'}, {u'is_active': False, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: SCACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': False}, {u'domain_group': u'DG5', u'is_active': False}, {u'domain_group': u'DG6', u'is_active': False}]

ok: [localhost] => (item={'key': u'SCACHE01', 'value': [{u'is_active': False, u'domain_group': u'DG1'}, {u'is_active': False, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: SCACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': False}, {u'domain_group': u'DG2', u'is_active': False}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'CACHE02', 'value': [{u'is_active': True, u'domain_group': u'DG4'}, {u'is_active': True, u'domain_group': u'DG5'}, {u'is_active': True, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: CACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': True}, {u'domain_group': u'DG5', u'is_active': True}, {u'domain_group': u'DG6', u'is_active': True}]

Required output:

Result should be in dict format and should be stored in one variable.

I expect something like below in list or dict format:

CACHE01: True ,CACHE02: True, SCACHE01:False, SCACHE02: False

The above values should get stored in one variable.

Body:
The task below

    - debug:
        msg: "{{ item.key }} {{ item.value|json_query('[].is_active') }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"

gives:

  msg: CACHE01 [True, True, True]
  msg: CACHE02 [True, True, True]
  msg: SCACHE01 [False, False, True]
  msg: SCACHE02 [False, False, False]

The filter map, instead of json_query, gives the same result

    - debug:
        msg: "{{ item.key }} {{ item.value|map(attribute='is_active')|list }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"

(In Ansible 2.3. and lower)
To combine the logical values let's create filter_plugins/bool_utils.py
with 2 filters bool_and and bool_or which apply Python functions all(list) and any(list) respectively

    shell> cat filter_plugins/bool_utils.py
    def bool_and(h):
        return all(h)
    def bool_or(h):
        return any(h)
    class FilterModule(object):
        ''' utility filters for operating on list of Boolean '''
        def filters(self):
            return {
                'bool_and' : bool_and,
                'bool_or' : bool_or,
            }

The task below with the filter bool_and

    - debug:
        msg: "{{ item.key }} {{ item.value|json_query('[].is_active')
                                          |bool_and }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"

gives

  msg: CACHE01 True
  msg: CACHE02 True
  msg: SCACHE01 False
  msg: SCACHE02 False

The task below creates the list status

    - set_fact:
        status: "{{ status|default([]) +
                    [{item.key: item.value|json_query('[].is_active')
                                          |bool_and}] }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}"
    - debug:
        var: status

gives

  status:
  - CACHE01: true
  - CACHE02: true
  - SCACHE01: false
  - SCACHE02: false

(In Ansible 2.4. and later) There are tests any, all available. The task below gives the same results

    - debug:
        msg: "{{ item.key }} {{ item.value|json_query('[].is_active') is all }}"
      loop: "{{ DOMAIN_GROUPS_ASSIGNMENT|dict2items }}


问:
Floating action button is jump, when click on it
When I click on FAB to show Snackbar, Fab is jump and Snackbar hided Fab

My code

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    android:id="@+id/main_coordinator_layout">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottom_app_bar"
        app:fabAlignmentMode="center"
        android:layout_width = match_parent
        android:layout_height = wrap_content
        android:layout_gravity = bottom
        android:backgroundTint" = @color/colorPrimary
        fabCradleMargin" = 15dp
        fabCradleRoundedCornerRadius = 15dp
        hideOnScroll = true
        layout_scrollFlags = scroll|enterAlways
        buttonGravity = bottom
        app:menu="@menu/menu"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:src="@drawable/ic_plus"
        app:layout_anchor="@id/bottom_app_bar"
        android:layout_width = wrap_content
        android:layout_height = wrap_content
        android:backgroundTint = "@color/colorPrimaryDark"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

I tried change params view on snackbar, but it do not work

```<code>public void showSnackBar(CoordinatorLayout coordinatorLayout, FloatingActionButton fab, String text) {

    Snackbar snackbar = Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_SHORT);
    View snackBarView = snackbar.getView();
    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) snackBarView.getLayoutParams();
    params.setMargins(
            params.leftMargin,
            params.topMargin,
            params.rightMargin,
            params.bottomMargin + 100);
    snackBarView.setLayoutParams(params);
    snackbar.setAnchorView(fab);
    snackbar.show();

}
</code>```

How can I fix it ?  so that FAB does not jump or Snackbar showed up

答:
since you are using CoordinatorLayout FAB will always move up when snackbar shows up  .

The CoordinatorLayout can listen to all it’s direct child view’s
  event, and when some event occured such as snackbar popup, it will
  move the floating button up also.

so it's a natural behavior , so to avoid that you should create a custom behavior.
So, how do you customize this behavior? You define your own Behavior subclass , please read this tutorial for more info  .

Body:
When I click on FAB to show Snackbar, Fab is jump and Snackbar hided Fab

My code

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    android:id="@+id/main_coordinator_layout">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottom_app_bar"
        app:fabAlignmentMode="center"
        android:layout_width = match_parent
        android:layout_height = wrap_content
        android:layout_gravity = bottom
        android:backgroundTint" = @color/colorPrimary
        fabCradleMargin" = 15dp
        fabCradleRoundedCornerRadius = 15dp
        hideOnScroll = true
        layout_scrollFlags = scroll|enterAlways
        buttonGravity = bottom
        app:menu="@menu/menu"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:src="@drawable/ic_plus"
        app:layout_anchor="@id/bottom_app_bar"
        android:layout_width = wrap_content
        android:layout_height = wrap_content
        android:backgroundTint = "@color/colorPrimaryDark"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

I tried change params view on snackbar, but it do not work

public void showSnackBar(CoordinatorLayout coordinatorLayout, FloatingActionButton fab, String text) {

    Snackbar snackbar = Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_SHORT);
    View snackBarView = snackbar.getView();
    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) snackBarView.getLayoutParams();
    params.setMargins(
            params.leftMargin,
            params.topMargin,
            params.rightMargin,
            params.bottomMargin + 100);
    snackBarView.setLayoutParams(params);
    snackbar.setAnchorView(fab);
    snackbar.show();

}

How can I fix it ?  so that FAB does not jump or Snackbar showed up


答:
It can be done in base like this:

```<code> sapply(1:ncol(example), function(x) rev(tail(names(sort(table(example[,x]))), 2)))
</code>```

And if you want to know the frequencies then just ignore names():

```<code>sapply(1:ncol(example), function(x) rev(tail(sort(table(example[,x])), 2)))
</code>```

Title: Most frequent element per column

Body:
I have the following  matrix:

set.seed(3690)

example = matrix(sample(1:10, 100, replace = TRUE), nrow = 10)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    4    4    2    7    2    2    3    8    2     5
 [2,]    7    3    2    6    6    5    7    8    1     3
 [3,]    7    5    7    9    4    9    4    8    2     7
 [4,]    5    3    4    2    1    5    9   10    9     5
 [5,]    9   10    7    2    7    4    9    1    1     9
 [6,]    2    3    5    1    2    8    1    5    9     4
 [7,]    5    4   10    5    9   10    1    6    1    10
 [8,]    6    3    9    7    1    1    9    2    1     7
 [9,]    5    9    4    8    9    9    5   10    5     4
[10,]   10    1    4    7    3    2    3    5    4     5

How can I find in R the most top 10 (or top 5) frequently occurring elements per column?

This is how I have coded this in Stata:

tempvar freq
generate byte `freq'=1

sort serial t0400_0415_d1-t0345_0400_d7

collapse (count) `freq' serial,  by(t0400_0415_d1-t0345_0400_d7)
list, sepby(`freq')

gsort -`freq' t0400_0415_d1-t0345_0400_d7
generate rank=_n
keep if rank<=20
drop `freq'

sort  t0400_0415_d1-t0345_0400_d7
tempfile top20
save `"`top20'"'

sort rank t0400_0415_d1-t0345_0400_d7
list rank t0400_0415_d1-t0345_0400_d7

Note that t0400_0415_d1 - t0345_0400_d7 are variable names.

Body:
It can be done in base like this:

 sapply(1:ncol(example), function(x) rev(tail(names(sort(table(example[,x]))), 2)))

And if you want to know the frequencies then just ignore names():

sapply(1:ncol(example), function(x) rev(tail(sort(table(example[,x])), 2)))


问:
Tab bar controller inside a navigation controller, or sharing a navigation root view
I'm trying to implement a UI structured like in the Tweetie app, which behaves as so: the top-level view controller seems to be a navigation controller, whose root view is an "Accounts" table view.  If you click on any account, it goes to the second level, which has a tab bar across the bottom.  Each tab item shows a different list and lets you drill down further (the subsequent levels don't show the tab bar).

So, this seems like the implementation hierarchy is:

UINavigationController

Accounts: UITableViewController

UITabBarController

Tweets: UITableViewController

Detail view of a tweet/user/etc

Replies: UITableViewController

...

This seems to work[^1], but appears to be unsupported according to the SDK documentation for -pushViewController:animated: (emphasis added):

viewController: The view controller that is pushed onto the stack. It cannot be an instance of tab bar controller.

I would like to avoid private APIs and the like, but I'm not sure why this usage is explicitly prohibited even when it seems to work fine.  Anyone know the reason?

I've thought about putting the tab bar controller as the main controller, with each of the tabs containing separate navigation controllers.  The problem with this is that each nav controller needs to share a single root view controller (namely the "Accounts" table in Tweetie) -- this doesn't seem to work: pushing the table controller to a second nav controller seems to remove it from the first.  Not to mention all the book-keeping when selecting a different account would probably be a pain.

How should I implement this the Right Way?

[^1]: The tab bar controller needs to be subclassed so that the tab bar controller's navigation item at that level stays in sync with the selected tab's navigation item, and the individual tab's table controller's need to push their respective detail views to self.tabBarController.navigationController instead of self.navigationController.

答:
I wrote a blog post on how I approached this problem.  For me, using a modal view was a simpler solution than writing a custom tab-bar implementation.

http://www.alexmedearis.com/uitabbarcontroller-inside-a-uinavigationcontroller/

OwnerDisplayName: dd

ContentLicense: CC BY-SA 2.5


问:
How do I use the Bluetooth module in the Arduino MKR Wifi 1010?
I'm currently trying to set up a program using the Bluetooth Low Energy (BLE) module in the Arduino MKR Wifi 1010.
Currently though the only library that I can find is CurieBLE for the Arduino/Genuino 101.

Are the correct libaries availiable in the IDE or are they somewhere else to be downloaded?

答: Use the ArduinoBLE library for Bluetooth LE support on the MKR 1010. The ArduinoBLE API is similar to CurieBLE but the implementation is different.</p>


问:
SQL Query: Showing multiple data and total order values
As part of an SQL Queries assignment, I am required to meet the following criteria:

"Display all customers who have bought anything in the last 6 months. Show >customer name, loyalty card number, date of order, and total value of order. >Ensure this is named correctly in the query results as Total_Order_Value."

For this, I came up with a script which has been marked as wrong. I am confused by the feedback as I believe I have met the question criteria.
Find the script and feedback below:

Script

```<code>SELECT Aorder.*, Acustomer.*, AorderDetails.quantity, (AorderDetails.quantity *AmenuItem.itemCost) AS Total_Order_Value
FROM Aorder, Acustomer, AmenuItem, AorderDetails
WHERE orderDateTime < Now() AND orderDateTime > DATE_ADD(Now(), INTERVAL -6 MONTH)
AND Acustomer.customerID = Aorder.customerID
AND Aorder.orderID = AorderDetails.orderID
AND AorderDetails.itemID = AmenuItem.itemID
AND Aorder.paymentType IN ('Cash' , 'Card');
</code>```

Feedback

"At the moment this will multiply cost *qty for each individual item bought in one order.  You need the total value for each order.  I.e. at the moment I would see a value for each item I bought in one order, I would like to see the total for the whole order.  You need to add an aggregate and a group by"

I would appreciate any assistance in helping me understand what went wrong and how I may structure this correctly to meet the requirements.
Thank you in advance.

答:
Essentially, you are reporting results at the orders items level and not customers and orders level as the original question asked. Your current resultset likely repeats customers and order details for each corresponding item which can be lengthy with its one-to-many relationships.

To resolve, simply refactor your SQL statement into an aggregate query that groups on customer and order items and sums each order item's value to retrieve the total amount of whole order. Additionally heed best practices in SQL:

EXPLICIT JOIN: As mentioned in comments do not use the old-join style of commas in FROM clause with matching conditions in WHERE. This is known as implicit joins. The current standard introduced in ANSI-92 emphasizes explicit joins using JOIN and ON clauses. While this does not change efficiency or output, it does aid in readability and maintainability.

SELECT CLAUSE: Try avoiding selecting all fields in tables with Aorder.*, Acustomer.* which is an open-ended resultset output. Your question specifically asked for certain fields: customer name, loyalty card number, date of order, and total value of order. So, select them accordingly.

TABLE ALIASES: For longer table names and tables that share the same prefixes, stems, or suffixes like your A tables, use table aliases that properly abbreviates and defines your identifiers. Again this practice should not change output but aids in readability and maintainability.

See below working SQL statement (adjust field names to actuals).

```<code>SELECT c.customer_name,
       c.loyalty_card_number,
       CAST(o.orderDateTime AS DATE)  AS Order_Date,
       SUM(d.quantity * m.itemCost) AS Total_Order_Value

FROM Aorder o
INNER JOIN Acustomer c ON c.customerID = o.customerID
INNER JOIN AorderDetails d ON o.orderID = d.orderID
INNER JOIN AmenuItem m ON d.itemID = m.itemID
WHERE o.orderDateTime < Now()
  AND o.orderDateTime > DATE_ADD(Now(), INTERVAL -6 MONTH)
  AND o.paymentType IN ('Cash' , 'Card')

GROUP BY c.customer_name,
         c.loyalty_card_number,
         CAST(o.orderDateTime AS DATE)
</code>```

NOTE: Do not make the mistake as many MySQL users do in excluding non-aggregated columns in GROUP BY clause of an aggregate query which is required in ANSI-SQL. Asterisks, *, should never be used in aggregate queries. MySQL unfortunately allows this feature with its ONLY FULL GROUP BY mode turned off and can return unreliable results.

Body:
As part of an SQL Queries assignment, I am required to meet the following criteria:

"Display all customers who have bought anything in the last 6 months. Show >customer name, loyalty card number, date of order, and total value of order. >Ensure this is named correctly in the query results as Total_Order_Value."

For this, I came up with a script which has been marked as wrong. I am confused by the feedback as I believe I have met the question criteria.
Find the script and feedback below:

Script

SELECT Aorder.*, Acustomer.*, AorderDetails.quantity, (AorderDetails.quantity *AmenuItem.itemCost) AS Total_Order_Value
FROM Aorder, Acustomer, AmenuItem, AorderDetails
WHERE orderDateTime < Now() AND orderDateTime > DATE_ADD(Now(), INTERVAL -6 MONTH)
AND Acustomer.customerID = Aorder.customerID
AND Aorder.orderID = AorderDetails.orderID
AND AorderDetails.itemID = AmenuItem.itemID
AND Aorder.paymentType IN ('Cash' , 'Card');

Feedback

"At the moment this will multiply cost *qty for each individual item bought in one order.  You need the total value for each order.  I.e. at the moment I would see a value for each item I bought in one order, I would like to see the total for the whole order.  You need to add an aggregate and a group by"

I would appreciate any assistance in helping me understand what went wrong and how I may structure this correctly to meet the requirements.
Thank you in advance.

Body:
Essentially, you are reporting results at the orders items level and not customers and orders level as the original question asked. Your current resultset likely repeats customers and order details for each corresponding item which can be lengthy with its one-to-many relationships.

To resolve, simply refactor your SQL statement into an aggregate query that groups on customer and order items and sums each order item's value to retrieve the total amount of whole order. Additionally heed best practices in SQL:

EXPLICIT JOIN: As mentioned in comments do not use the old-join style of commas in FROM clause with matching conditions in WHERE. This is known as implicit joins. The current standard introduced in ANSI-92 emphasizes explicit joins using JOIN and ON clauses. While this does not change efficiency or output, it does aid in readability and maintainability.

SELECT CLAUSE: Try avoiding selecting all fields in tables with Aorder.*, Acustomer.* which is an open-ended resultset output. Your question specifically asked for certain fields: customer name, loyalty card number, date of order, and total value of order. So, select them accordingly.

TABLE ALIASES: For longer table names and tables that share the same prefixes, stems, or suffixes like your A tables, use table aliases that properly abbreviates and defines your identifiers. Again this practice should not change output but aids in readability and maintainability.

See below working SQL statement (adjust field names to actuals).

SELECT c.customer_name,
       c.loyalty_card_number,
       CAST(o.orderDateTime AS DATE)  AS Order_Date,
       SUM(d.quantity * m.itemCost) AS Total_Order_Value

FROM Aorder o
INNER JOIN Acustomer c ON c.customerID = o.customerID
INNER JOIN AorderDetails d ON o.orderID = d.orderID
INNER JOIN AmenuItem m ON d.itemID = m.itemID
WHERE o.orderDateTime < Now()
  AND o.orderDateTime > DATE_ADD(Now(), INTERVAL -6 MONTH)
  AND o.paymentType IN ('Cash' , 'Card')

GROUP BY c.customer_name,
         c.loyalty_card_number,
         CAST(o.orderDateTime AS DATE)

NOTE: Do not make the mistake as many MySQL users do in excluding non-aggregated columns in GROUP BY clause of an aggregate query which is required in ANSI-SQL. Asterisks, *, should never be used in aggregate queries. MySQL unfortunately allows this feature with its ONLY FULL GROUP BY mode turned off and can return unreliable results.


问:
Restricting re-renders to specific state change in functional component
If I have a component with three different states and I only want the component to re-render when one specific state in that component changes, how would I go about doing that?

Below I've included a code example. Say I only want this component to re-render when setSecondState() is called, not when setFirstState() or setThirdState() is called.

```<code>const ExampleComponent = () => {
     const [firstState, setFirstState] = React.useState(0);
     const [secondState, setSecondState] = React.useState(false);
     const [thirdState, setThirdState] = React.useState("");

     return (
          <div>
                Rendered
          </div>
     );
}
</code>```

答:
You can use the shouldComponentUpdate lifecycle function.
This will return a boolean which tells react to render or not.

In the below example when v1 value changes it does not trigger re-render while changing v2 triggers a re-render.

class App extends React.Component {
  state = {
    v1: 0,
    v2: 0
  }

  shouldComponentUpdate(nextProps, nextState){
    console.log('v1: ', nextState.v1, ', v2: ', nextState.v2);
    return this.state.v1 === nextState.v1
  }

  render(){
    const { v1, v2 } = this.state;

    return (

        <button onClick={() => this.setState(({ v1 }) => ({ v1: v1 + 1 }))}>{`Increase but do not render: ${v1}`}</button>

        <button onClick={() => this.setState(({ v2 }) => ({ v2: v2 + 1 }))}>{`Increase and render: ${v2}`}</button>

    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
If I have a component with three different states and I only want the component to re-render when one specific state in that component changes, how would I go about doing that?

Below I've included a code example. Say I only want this component to re-render when setSecondState() is called, not when setFirstState() or setThirdState() is called.

const ExampleComponent = () => {
     const [firstState, setFirstState] = React.useState(0);
     const [secondState, setSecondState] = React.useState(false);
     const [thirdState, setThirdState] = React.useState("");

     return (

                Rendered

     );
}

Body:
You can use the shouldComponentUpdate lifecycle function.
This will return a boolean which tells react to render or not.

In the below example when v1 value changes it does not trigger re-render while changing v2 triggers a re-render.

class App extends React.Component {
  state = {
    v1: 0,
    v2: 0
  }

  shouldComponentUpdate(nextProps, nextState){
    console.log('v1: ', nextState.v1, ', v2: ', nextState.v2);
    return this.state.v1 === nextState.v1
  }

  render(){
    const { v1, v2 } = this.state;

    return (
      <div>
        <button onClick={() => this.setState(({ v1 }) => ({ v1: v1 + 1 }))}>{`Increase but do not render: ${v1}`}</button><br />
        <button onClick={() => this.setState(({ v2 }) => ({ v2: v2 + 1 }))}>{`Increase and render: ${v2}`}</button>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
Using case with aggregate function & group by clauses
I have a query using CASE with aggregate function and group by clause, like this

```<code>SELECT
A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C
,<ALIAS>
</code>```

and I got an error "GROUP BY and WITH...BY clauses may not contain aggregate"

then, I change my script (exclude  from group by)

```<code>SELECT
A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C
</code>```

and still got an error "Selected non-aggregate values must be part of the associated group"

please help me to understand why  must be part of group by,
and what do I have to do to fix it?

答:
Maybe try this</p>

```<code>SELECT  A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C
,<COLUMN_NAME_A>
</code>```

Body:
I have a query using CASE with aggregate function and group by clause, like this

SELECT
A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C
,<ALIAS>

and I got an error "GROUP BY and WITH...BY clauses may not contain aggregate"

then, I change my script (exclude  from group by)

SELECT
A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C

and still got an error "Selected non-aggregate values must be part of the associated group"

please help me to understand why  must be part of group by,
and what do I have to do to fix it?

Body:
Maybe try this

SELECT  A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C
,<COLUMN_NAME_A>


问:
How return a dictionary from WebAPI?
I have a MVC project that, from a view  upload one or more files to a server,
then , when i click submit a provate web service is recalled and i pass a collection of files to upload.
The upload workings fine, but form webapi i have an object (class Store) that i would return.

I do not know if I am wrong to return the "raw" object from the web api or wrong to read it.

this is my model

    public class Store
    {
        public IDictionary<string, string> dictionaryOfStores = new Dictionary<string, string>();
        public string CodeText { get; set; }
    }
```

<p>this i have my web api method:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<ActionResult<Store>> UploadAsync()
        {
            dictStores = new Store();
            foreach (var formFile in form.Files)
                    {

                        dictStores.dictionaryOfStores.Add(formFile.FileName, codefilename);
                        // also CodeText is filled here
                    }
                }
            }

            // return dictionary
            //

            return dictStores;
        }
</code>```

this is my controller of mvc that recall private webservice

  public async Task<IActionResult> Upload(List<IFormFile> files)
        {

                    using (var client = new HttpClient())
                    {

                            var model = new FilesViewModel();
                            MultipartFormDataContent multiContent = new MultipartFormDataContent();
                            foreach (var formfile in files)
                            {
                                client.BaseAddress = new Uri(BaseAddress);
                                byte[] data;
                                using (var br = new BinaryReader(formfile.OpenReadStream()))
                                    data = br.ReadBytes((int)formfile.OpenReadStream().Length);
                                ByteArrayContent bytes = new ByteArrayContent(data);

                                multiContent.Add(bytes, "file", formfile.FileName);
                                model.Files.Add(new FileDetails { Name = formfile.GetFilename() });
                            }
                            var result = await client.PostAsync("api/Load/Upload", multiContent); //
                            // here i have try to read result.Content but doesn't have my data
                            var res = await result.Content.ReadAsStreamAsync();
                            // here i have to put res in my model
                            return View("Summary", model);

                    }
```

im use asp net core 2.2
Thanks for the help

答:
I solved by seeing the answer: How to get object using Httpclient with response Ok in Web Api
I was able to read the data :

await result.Content.ReadAsAsync<Store>()
```

Title: How return a dictionary from WebAPI?

Body:
I have a MVC project that, from a view  upload one or more files to a server,
then , when i click submit a provate web service is recalled and i pass a collection of files to upload.
The upload workings fine, but form webapi i have an object (class Store) that i would return.

I do not know if I am wrong to return the "raw" object from the web api or wrong to read it.

this is my model

    public class Store
    {
        public IDictionary<string, string> dictionaryOfStores = new Dictionary<string, string>();
        public string CodeText { get; set; }
    }

this i have my web api method:

public async Task<ActionResult<Store>> UploadAsync()
        {
            dictStores = new Store();
            foreach (var formFile in form.Files)
                    {

                        dictStores.dictionaryOfStores.Add(formFile.FileName, codefilename);
                        // also CodeText is filled here
                    }
                }
            }

            // return dictionary
            //

            return dictStores;
        }

this is my controller of mvc that recall private webservice

  public async Task<IActionResult> Upload(List<IFormFile> files)
        {

                    using (var client = new HttpClient())
                    {

                            var model = new FilesViewModel();
                            MultipartFormDataContent multiContent = new MultipartFormDataContent();
                            foreach (var formfile in files)
                            {
                                client.BaseAddress = new Uri(BaseAddress);
                                byte[] data;
                                using (var br = new BinaryReader(formfile.OpenReadStream()))
                                    data = br.ReadBytes((int)formfile.OpenReadStream().Length);
                                ByteArrayContent bytes = new ByteArrayContent(data);

                                multiContent.Add(bytes, "file", formfile.FileName);
                                model.Files.Add(new FileDetails { Name = formfile.GetFilename() });
                            }
                            var result = await client.PostAsync("api/Load/Upload", multiContent); //
                            // here i have try to read result.Content but doesn't have my data
                            var res = await result.Content.ReadAsStreamAsync();
                            // here i have to put res in my model
                            return View("Summary", model);

                    }

im use asp net core 2.2
Thanks for the help


问:
SQL: a set of results inside each result
I have a table articles, and it has a structure like this:

```<code>id, name, date, contents
</code>```

And I have a table authors, and it has a structure like this:

```<code>id, article_id, name, email
</code>```

A single article can have many authors.

How can I get a list of articles, with each row showing the multiple authors for that article (almost like a set of results inside each article row)

I feel like this is a simple thing to do with SQL, but I don't know the correct terms to look for.  I have been searching around all afternoon with to no avail.  Can anyone help?

答:
You can use the following solution using GROUP_CONCAT:

```<code>SELECT articles.id, articles.name, GROUP_CONCAT(authors.name) AS authors
FROM articles LEFT JOIN authors ON articles.id = authors.article_id
GROUP BY articles.id, articles.name
</code>```

demo on dbfiddle.uk

Body:
I have a table articles, and it has a structure like this:

id, name, date, contents

And I have a table authors, and it has a structure like this:

id, article_id, name, email

A single article can have many authors.

How can I get a list of articles, with each row showing the multiple authors for that article (almost like a set of results inside each article row)

I feel like this is a simple thing to do with SQL, but I don't know the correct terms to look for.  I have been searching around all afternoon with to no avail.  Can anyone help?

Body:
You can use the following solution using GROUP_CONCAT:

SELECT articles.id, articles.name, GROUP_CONCAT(authors.name) AS authors
FROM articles LEFT JOIN authors ON articles.id = authors.article_id
GROUP BY articles.id, articles.name

demo on dbfiddle.uk


问:
How to create a TopoJSON geomap using Altair library for Python?
I am trying to create a geomap of a state using Altair package for Python. I will then plot let's say dots representing some event at a location specified by its latitude & longitude. I follow the Altair's example gallery here. The TopoJSON file is located in the GitHub repository deldersveld/topojson. However, I can't get it to draw the map of Michigan. Is this file missing something? Anyone who can help me?

Environment:

Windows 10

python 3

jupyter-lab 1.0.0a3

altair 3.0

答:
You can do something like this:

```<code>import altair as alt

url = "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/us-states/MI-26-michigan-counties.json"

source = alt.topo_feature(url, "cb_2015_michigan_county_20m")

alt.Chart(source).mark_geoshape().encode(
    tooltip='properties.NAME:N'
)
</code>```

The key is to look in the "objects" and "properties" entries of the TopoJSON file to figure out what to use for features and encodings.

Body:
You can do something like this:

import altair as alt

url = "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/us-states/MI-26-michigan-counties.json"

source = alt.topo_feature(url, "cb_2015_michigan_county_20m")

alt.Chart(source).mark_geoshape().encode(
    tooltip='properties.NAME:N'
)

The key is to look in the "objects" and "properties" entries of the TopoJSON file to figure out what to use for features and encodings.


问:
link_to method and click event in Rails
How do I create a link of this type:

```<code><a href="#" onclick="document.getElementById('search').value=this.value">
</code>```

using method link_to in Rails?

I couldn't figure it out from Rails docs.

答:
another solution is catching onClick event and for aggregate data to js function you can

.hmtl.erb

```<code><%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
</code>```

.js

```<code>// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});
</code>```

OwnerDisplayName: Yud

Title: link_to method and click event in Rails

Body:
How do I create a link of this type:

using method link_to in Rails?

I couldn't figure it out from Rails docs.

Body:
another solution is catching onClick event and for aggregate data to js function you can

.hmtl.erb

<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>

.js

// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});


问:
Inner function not affecting variable outside function
So I am using AsyncHTTPClient to make a call and check if a user is authenticated. I have a Boolean "authenticated" to check if they are, and want to change its value inside the onSuccess, however the onSuccess does not seem to be affecting the value of authenticated outside and I am very confused as to why.

I can confirm that it does indeed go into the if statement, so the response i am getting is correct. I am new to Kotlin, however something similar in Java does work as I am now transitioning.

This is my code:

```<code>    fun authenticate(username: String, password: String): Boolean? {
        var params = RequestParams()
        params.put("username", username)
        params.put("password", password)
        var authenticated: Boolean? = null
        var a: Int = 1

        //Encrypt password and stuff

        restClient.get("/authenticate", params, object : JsonHttpResponseHandler(){
            override fun onSuccess(statusCode: Int, headers: kotlin.Array<out Header>?, response: JSONObject?) {
                if(response == null) {Log.d("no response", "404")}
                else if (response.get("success").toString() == "true") {
                    authenticated = true
                    a = a + 1
                    Log.d("authenticatedInside", a.toString())
                    Log.d("authenticatedInside", authenticated.toString())
                }
            }
        })

        Log.d("authenticated", a.toString())
        Log.d("authenticated", authenticated.toString())
        return authenticated
    }
</code>```

AuthenticatedInside gives the right values.

a is just a test integer, the result here is a is still 1, authenticated is still null and it returns null as well.

答:
It is null because onSuccess method is called asynchronously, what that means is that method isn't called before you try to access value of authenticated and as such it still isn't initialized.

One of the ways to fix this is to create another function for example:

```<code>fun onAuthenticateResult(authenticated : Boolean){
   // Write what you want to do with authenticated here
}
</code>```

Then call that method from onSuccess method, of course this won't be called on UI thread so be careful not to directly modify any part of your UI inside this method.

Body:
So I am using AsyncHTTPClient to make a call and check if a user is authenticated. I have a Boolean "authenticated" to check if they are, and want to change its value inside the onSuccess, however the onSuccess does not seem to be affecting the value of authenticated outside and I am very confused as to why.

I can confirm that it does indeed go into the if statement, so the response i am getting is correct. I am new to Kotlin, however something similar in Java does work as I am now transitioning.

This is my code:

    fun authenticate(username: String, password: String): Boolean? {
        var params = RequestParams()
        params.put("username", username)
        params.put("password", password)
        var authenticated: Boolean? = null
        var a: Int = 1

        //Encrypt password and stuff

        restClient.get("/authenticate", params, object : JsonHttpResponseHandler(){
            override fun onSuccess(statusCode: Int, headers: kotlin.Array<out Header>?, response: JSONObject?) {
                if(response == null) {Log.d("no response", "404")}
                else if (response.get("success").toString() == "true") {
                    authenticated = true
                    a = a + 1
                    Log.d("authenticatedInside", a.toString())
                    Log.d("authenticatedInside", authenticated.toString())
                }
            }
        })

        Log.d("authenticated", a.toString())
        Log.d("authenticated", authenticated.toString())
        return authenticated
    }

AuthenticatedInside gives the right values.

a is just a test integer, the result here is a is still 1, authenticated is still null and it returns null as well.

Body:
It is null because onSuccess method is called asynchronously, what that means is that method isn't called before you try to access value of authenticated and as such it still isn't initialized.

One of the ways to fix this is to create another function for example:

fun onAuthenticateResult(authenticated : Boolean){
   // Write what you want to do with authenticated here
}

Then call that method from onSuccess method, of course this won't be called on UI thread so be careful not to directly modify any part of your UI inside this method.


问:
Cypress - Visit a URL obtained from a 3rd party(email)
In my test, I want to visit a URL that is sent in an email. I can successfully save the URL in a variable, but am unable to get cypress to go to that URL. I keep getting the below error. I don't fully understand cypress being "promise-like", so I'm not sure how to resolve the issue

Uncaught (in promise) CypressError: Cypress detected that you returned
  a promise from a command while also invoking one or more cy commands
  in that promise.

The command that returned the promise was:

cy.get()

The cy command you invoked inside the promise was:

cy.request()

Because Cypress commands are already promise-like, you don't need to
  wrap them or return your own promise.

Cypress will resolve your command with whatever the final Cypress
  command yields.

```<code>Cypress.Commands.add("clickForgotPwdLink", (emailaddress) => {
    const MailosaurClient = require('mailosaur');
    const client = new MailosaurClient('1234');
    let latestEmail;
    var emailLower = emailaddress.toLowerCase();
    client.messages.search('abc', {
        sentTo: emailLower
    }).then((results) => {
        latestEmail = results.items[0];
        let email = latestEmail.id;
        client.messages.get(email)
            .then((newlink) => {
                var forgotpwd = newlink.html.links[0].href;
                console.log(forgotpwd)
                cy.request(''+forgotpwd+'');
            })
    })
});
</code>```

答:
I also tried like you but Cypress doens't allowed.
You have to do it via cy.request() to Mailosaur API.

Try something like this:

```<code>cy.request({
  method: 'POST',
  url: 'https://mailosaur.com/api/messages/search',
  auth: {
    username: 'API_key',
  },
  body: {
    sentTo: 'yourEmail',
  },
  qs: {
    server: 'yourServer',
    page: 0,
    itemsPerPage: 50,
  },
});
</code>```

Body:
In my test, I want to visit a URL that is sent in an email. I can successfully save the URL in a variable, but am unable to get cypress to go to that URL. I keep getting the below error. I don't fully understand cypress being "promise-like", so I'm not sure how to resolve the issue

Uncaught (in promise) CypressError: Cypress detected that you returned
  a promise from a command while also invoking one or more cy commands
  in that promise.

The command that returned the promise was:

cy.get()

The cy command you invoked inside the promise was:

cy.request()

Because Cypress commands are already promise-like, you don't need to
  wrap them or return your own promise.

Cypress will resolve your command with whatever the final Cypress
  command yields.

Cypress.Commands.add("clickForgotPwdLink", (emailaddress) => {
    const MailosaurClient = require('mailosaur');
    const client = new MailosaurClient('1234');
    let latestEmail;
    var emailLower = emailaddress.toLowerCase();
    client.messages.search('abc', {
        sentTo: emailLower
    }).then((results) => {
        latestEmail = results.items[0];
        let email = latestEmail.id;
        client.messages.get(email)
            .then((newlink) => {
                var forgotpwd = newlink.html.links[0].href;
                console.log(forgotpwd)
                cy.request(''+forgotpwd+'');
            })
    })
});

Body:
I also tried like you but Cypress doens't allowed.
You have to do it via cy.request() to Mailosaur API.

Try something like this:

cy.request({
  method: 'POST',
  url: 'https://mailosaur.com/api/messages/search',
  auth: {
    username: 'API_key',
  },
  body: {
    sentTo: 'yourEmail',
  },
  qs: {
    server: 'yourServer',
    page: 0,
    itemsPerPage: 50,
  },
});


问:
When to duplicate data in noSQL?
I'm working on a project where Firebase Firestore will be used. I've not had experience with noSQL so I work on understanding this technology.

The application lets an user to select a movie category and download an associated movie to let him movie edition.

The category and movie won't be change by the users and will be fixed or change by the owner. Think this like a Netflix catalog where the user can only watches the movies

There are several categories but for the moment only one movie is inside a category (may have more later).
Each movie has related metadata.

In the future:
- an user object will be used to rank each user regarding their score (information related to the application).
- some movie will be available with localisation restriction, i.e a movie would be available for US user only.

In my first thought, the data structure will look like this:

```<code>// Collection
Category: {
    name: "drama" // Could be action, or other
}

// Collection
Movie: {
    name: "Matrix"
    description: "Best movie ever"
    duration: 1321312
    url: "https://www....."
    allowedCountry: "us" // is it the right place for this field?
    category: "drama" // is it ok to duplicate data here?
}

//Collection
user: {
    ranking: 3
    withMovie: "Matrix" // is it ok to duplicate data here?
}
</code>```

I'm not sure if it's the right data structure for this problem.

The flow of the app would present in the first time all the possible categories (so I create a separated collection in order to avoid to iterate on all the song to get the categories)

Then when the user select a category the possible movies are display and the app download the selected one.

Is is okay to iterate on all possible movies to show the movies related to the category?
Or should I put the movies as a sub collection of the category collection?

答:
I'd typically indeed keep the category directly in the movie document in this scenario, since it makes the queries much easier to read.

```<code>firebase.firestore().collection("movies").where("category", "==", "drama")
</code>```

In fact, consider if your movies can really only have a single category (as you've modeled it now), or whether they may have multiple categories in the future (as Netflix does as far as I know).  You'd model the latter as an array of categories:

```<code>categories: ["drama", "sci-fi"]
</code>```

And then query it with:

```<code>firebase.firestore().collection("movies").where("categories", "array-contains", "drama")
</code>```

Title: When to duplicate data in noSQL?

Body:
I'm working on a project where Firebase Firestore will be used. I've not had experience with noSQL so I work on understanding this technology.

The application lets an user to select a movie category and download an associated movie to let him movie edition.

The category and movie won't be change by the users and will be fixed or change by the owner. Think this like a Netflix catalog where the user can only watches the movies

There are several categories but for the moment only one movie is inside a category (may have more later).
Each movie has related metadata.

In the future:
- an user object will be used to rank each user regarding their score (information related to the application).
- some movie will be available with localisation restriction, i.e a movie would be available for US user only.

In my first thought, the data structure will look like this:

// Collection
Category: {
    name: "drama" // Could be action, or other
}

// Collection
Movie: {
    name: "Matrix"
    description: "Best movie ever"
    duration: 1321312
    url: "https://www....."
    allowedCountry: "us" // is it the right place for this field?
    category: "drama" // is it ok to duplicate data here?
}

//Collection
user: {
    ranking: 3
    withMovie: "Matrix" // is it ok to duplicate data here?
}

I'm not sure if it's the right data structure for this problem.

The flow of the app would present in the first time all the possible categories (so I create a separated collection in order to avoid to iterate on all the song to get the categories)

Then when the user select a category the possible movies are display and the app download the selected one.

Is is okay to iterate on all possible movies to show the movies related to the category?
Or should I put the movies as a sub collection of the category collection?

Body:
I'd typically indeed keep the category directly in the movie document in this scenario, since it makes the queries much easier to read.

firebase.firestore().collection("movies").where("category", "==", "drama")

In fact, consider if your movies can really only have a single category (as you've modeled it now), or whether they may have multiple categories in the future (as Netflix does as far as I know).  You'd model the latter as an array of categories:

categories: ["drama", "sci-fi"]

And then query it with:

firebase.firestore().collection("movies").where("categories", "array-contains", "drama")


问:
How can I convert a list to return a Json?
I have the following code and need to retrieve faq type questions from a bd, how can I convert the list returned to a json, the following code presents: Object of type 'Question' is not JSON serializable

I'm using flask and Python3

```<code>@app.route("/faq/<question>")

@app.route("/faq/",defaults={"question":None})

def teste(question):
   r=Question.query.all()

   return jsonify(r)
</code>```

Object of type 'Question' is not JSON serializable

答:
Your list contains Question objects that aren't serializable as JSON. If you want the output to be a list of strings, you should use

```<code>jsonify(list(map(str, r)))
</code>```

(This assumes that the question objects can be converted to string.)

Body:
I have the following code and need to retrieve faq type questions from a bd, how can I convert the list returned to a json, the following code presents: Object of type 'Question' is not JSON serializable

I'm using flask and Python3

@app.route("/faq/<question>")

@app.route("/faq/",defaults={"question":None})

def teste(question):
   r=Question.query.all()

   return jsonify(r)

Object of type 'Question' is not JSON serializable

Body:
Your list contains Question objects that aren't serializable as JSON. If you want the output to be a list of strings, you should use

jsonify(list(map(str, r)))

(This assumes that the question objects can be converted to string.)


问:
How load data after all computed data from vuex store was loaded?
Working with Laravel 5.7 / Vuejs 2.6 / Vuex 3.1 app I use "vue-select": "^2.6.4" and when I open form with existing data I need
to fill my select component with variable

```<code>selection_status = {key: ‘key’, label: ‘label’}

<v-select
      v-model="selection_status"
      data-vv-name="userRow.status"
      :options="customerStatusValueArray"
      v-validate="'required'"
      id="status"
      name="status"
      class="form-control editable_field"
      placeholder="Select option"
></v-select>

        data() {
            return {
                ...
                selection_status: null,

        mounted() {
            this.loadCustomer();
        }, // mounted() {

        loadCustomer() {
            axios.get(window.API_VERSION_LINK + 'personal/customers/' + this.user_id).then((response) => {
               this.userRow = response.data.user;

               this.customerStatusValueArray.map((nextCustomerStatusValue, index) => {
                   if (nextCustomerStatusValue.key == this.userRow.status) {
                       this.selection_status = {key: this.userRow.status, label: nextCustomerStatusValue.label};
                  }
               });
        ...

    computed: {
        customerStatusValueArray() {
            return this.$store.getters.customerStatusValueArray;
        },
</code>```

I get customerStatusValueArray array from vuex store and I found that it is filled AFTER method loadCustomer from mounted is loaded,
so this.selection_status is null.

Is there is a way to run

```<code>    this.loadCustomer();
</code>```

after all computed data from vuex store is loaded?

Thanks!

答:
You probably should use a loading state,
also consider using created() to call this.loadCustomer()
because mounted() its called after the component has been rendered.

```<code><v-select v-if="loaded' />
<my-loader v-else/>

data() {
  loaded: false,
}

loadCustomer() {
  axios.get('url').then((response) => {
   this.loaded = true;
  });
}
</code>```

update:

You can observe when your computed changes,
once customerStatusValueArray isn't empty you can call this.loadCustomer()

export default {
  watch: {
    customerStatusValueArray: (newVal, oldVal) {
      if (newVal.length > 0)
        this.loadCustomer()
    }
  }
  computed: {
    customerStatusValueArray() {
      return this.$store.getters.customerStatusValueArray;
    },
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script></code>```

Body:
Working with Laravel 5.7 / Vuejs 2.6 / Vuex 3.1 app I use "vue-select": "^2.6.4" and when I open form with existing data I need
to fill my select component with variable

selection_status = {key: ‘key’, label: ‘label’}

<v-select
      v-model="selection_status"
      data-vv-name="userRow.status"
      :options="customerStatusValueArray"
      v-validate="'required'"
      id="status"
      name="status"
      class="form-control editable_field"
      placeholder="Select option"
></v-select>

        data() {
            return {
                ...
                selection_status: null,

        mounted() {
            this.loadCustomer();
        }, // mounted() {

        loadCustomer() {
            axios.get(window.API_VERSION_LINK + 'personal/customers/' + this.user_id).then((response) => {
               this.userRow = response.data.user;

               this.customerStatusValueArray.map((nextCustomerStatusValue, index) => {
                   if (nextCustomerStatusValue.key == this.userRow.status) {
                       this.selection_status = {key: this.userRow.status, label: nextCustomerStatusValue.label};
                  }
               });
        ...

    computed: {
        customerStatusValueArray() {
            return this.$store.getters.customerStatusValueArray;
        },

I get customerStatusValueArray array from vuex store and I found that it is filled AFTER method loadCustomer from mounted is loaded,
so this.selection_status is null.

Is there is a way to run

    this.loadCustomer();

after all computed data from vuex store is loaded?

Thanks!

Body:
You probably should use a loading state,
also consider using created() to call this.loadCustomer()
because mounted() its called after the component has been rendered.

<v-select v-if="loaded' />
<my-loader v-else/>

data() {
  loaded: false,
}

loadCustomer() {
  axios.get('url').then((response) => {
   this.loaded = true;
  });
}

update:

You can observe when your computed changes,
once customerStatusValueArray isn't empty you can call this.loadCustomer()

export default {
  watch: {
    customerStatusValueArray: (newVal, oldVal) {
      if (newVal.length > 0)
        this.loadCustomer()
    }
  }
  computed: {
    customerStatusValueArray() {
      return this.$store.getters.customerStatusValueArray;
    },
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


问:
How to allow underscore and dash with ctype_alnum()?
How can I add the exception of _ and - as valid characters when using ctype_alnum() ?

I have the following code:

```<code>if ( ctype_alnum ($username) ) {

  return TRUE;

} elseif (!ctype_alnum  ($username)) {

  $this->form_validation->set_message(
    '_check_username',
    'Invalid username! Alphanumerics only.'
  );

  return FALSE;
}
</code>```

答:
The regex equivalent is very brief and easy to read.

~^[\w-]+$~ This pattern requires the whole string to be comprised of one or more letters, numbers, underscores, or hyphens.

Regex allows you to skip the data preparation step and directly access the evaluation -- resulting in cleaner, leaner, more direct, professional-looking code.

```<code>if (preg_match('~^[\w-]+$~', $username)) {
    return true;
} else {
    $this->form_validation->set_message(
        '_check_username',
        'Invalid username! Alphanumerics, underscores, and hyphens only.'
    );
    return false;
}
</code>```

Body:
How can I add the exception of _ and - as valid characters when using ctype_alnum() ?

I have the following code:

if ( ctype_alnum ($username) ) {

  return TRUE;

} elseif (!ctype_alnum  ($username)) {

  $this->form_validation->set_message(
    '_check_username',
    'Invalid username! Alphanumerics only.'
  );

  return FALSE;
}

Body:
The regex equivalent is very brief and easy to read.

~^[\w-]+$~ This pattern requires the whole string to be comprised of one or more letters, numbers, underscores, or hyphens.

Regex allows you to skip the data preparation step and directly access the evaluation -- resulting in cleaner, leaner, more direct, professional-looking code.

if (preg_match('~^[\w-]+$~', $username)) {
    return true;
} else {
    $this->form_validation->set_message(
        '_check_username',
        'Invalid username! Alphanumerics, underscores, and hyphens only.'
    );
    return false;
}