问:
Hide div on click with Javascript (a click that already show other div)
I've built a feedback function to be used on the bottom of pages on our company website. The visitor can vote YES or NO on the question, "Was this information useful to you?" The click show a div (feedbackDiv1/feedbackDiv2) via Javascript.

The function works, but I want the question and the answer buttons to disappear after the visitor has voted, I.e. hide the div #pagefeedback.

I've tried all my tools, but I cant get this to work.

Help would be very much appreciated!

This is the JavaScript used:

```<code>function showFeedback1() {
   document.getElementById('feedbackDiv1').style.display = "block";

function showFeedback2() {
   document.getElementById('feedbackDiv2').style.display = "block";}
</code>```

This is the HTML used:

```<code><div class="greycontentbox">

<div id="pagefeedback">
<h4 style="text-align: center;">Was this information useful to you?</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
  <tbody>
    <tr>
      <td align="center"><a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback1()"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES</a></td>
      <td align="center"><a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback2()"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO</a></td>
    </tr>
  </tbody>
</table></div>

<div align="center"><div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">POSITIVE FEEDBACK</div></div>
<div align="center"><div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">NEGATIVE FEEDBACK</div></div>
</div>
</code>```

Kind regards,
Pete

答:
Based on Robert's answer, you could do a simple function which receive the ID of the element that has to be shown.

function showFeedback(feedback) {
   document.getElementById(feedback).style.display = "block";
   document.getElementById('options').style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="greycontentbox">

<div id="pagefeedback">
<h4 style="text-align: center;">Was this information useful to you?</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
  <tbody id="options">
    <tr>
      <td align="center"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES</td>
      <td align="center"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO</td>
    </tr>
  </tbody>
</table></div>

<div align="center">
<div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">POSITIVE FEEDBACK</div></div>
<div align="center"><div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">NEGATIVE FEEDBACK</div>
</div>
</div></code>```

Body:
I've built a feedback function to be used on the bottom of pages on our company website. The visitor can vote YES or NO on the question, "Was this information useful to you?" The click show a div (feedbackDiv1/feedbackDiv2) via Javascript.

The function works, but I want the question and the answer buttons to disappear after the visitor has voted, I.e. hide the div #pagefeedback.

I've tried all my tools, but I cant get this to work.

Help would be very much appreciated!

This is the JavaScript used:

function showFeedback1() {
   document.getElementById('feedbackDiv1').style.display = "block";

function showFeedback2() {
   document.getElementById('feedbackDiv2').style.display = "block";}

This is the HTML used:

Was this information useful to you?

      YES
      NO

POSITIVE FEEDBACK

NEGATIVE FEEDBACK

Kind regards,
Pete

Body:
Based on Robert's answer, you could do a simple function which receive the ID of the element that has to be shown.

function showFeedback(feedback) {
   document.getElementById(feedback).style.display = "block";
   document.getElementById('options').style.display = "none";
}

<div class="greycontentbox">

<div id="pagefeedback">
<h4 style="text-align: center;">Was this information useful to you?</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
  <tbody id="options">
    <tr>
      <td align="center"><a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback('feedbackDiv1')"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES</a></td>
      <td align="center"><a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback('feedbackDiv2')"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO</a></td>
    </tr>
  </tbody>
</table></div>

<div align="center">
<div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">POSITIVE FEEDBACK</div></div>
<div align="center"><div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">NEGATIVE FEEDBACK</div>
</div>
</div>


来源: stackexchange

问:
Why doesn't my template accept an initializer list
I have created a template as follows

```<code>template<typename T>
void f(T const& t) { }
</code>```

I wanted for this to be callable by containers but also by initializer lists. I thought it would be initializer_list<int>, when called as follows.

```<code>f({1, 2, 3});
</code>```

But GCC behaves as if it's not Standards compliant

```<code>m.cpp: In function 'int main()':
m.cpp:6:25: warning: deducing 'const T' as 'const std::initializer_list<int>'
m.cpp:4:6: warning:   in call to 'void f(const T&) [with T = std::initializer_list<int>]'
m.cpp:6:25: warning:   (you can disable this with -fno-deduce-init-list)
</code>```

Can anyone explain how I can make this work without warnings? Thanks!

答:
A "thing" like {1,2,3} does not qualify as an expression. It has no type. Therefore, no type deduction is done. But C++0x makes an explicit exception for 'auto', so

```<code>auto x = {1,2,3};
</code>```

actually works and decltype(x) will be initializer_list<int>. But this is a special rule that only applies to auto. I guess they wanted to make loops like these

```<code>for (int x : {2,3,5,7,11}) {
   ...
}
</code>```

work since this kind of loop exploits the special rule.

As for solving the problem, you could add an initializer_list<T> overload as a "wrapper":

```<code>template<class T>
inline void outer(initializer_list<T> il) {
   inner(il);
}
</code>```

I didn't test this but my current understanding is that it should work.

ContentLicense: CC BY-SA 2.5

Body:
I have created a template as follows

template<typename T>
void f(T const& t) { }

I wanted for this to be callable by containers but also by initializer lists. I thought it would be initializer_list<int>, when called as follows.

f({1, 2, 3});

But GCC behaves as if it's not Standards compliant

m.cpp: In function 'int main()':
m.cpp:6:25: warning: deducing 'const T' as 'const std::initializer_list<int>'
m.cpp:4:6: warning:   in call to 'void f(const T&) [with T = std::initializer_list<int>]'
m.cpp:6:25: warning:   (you can disable this with -fno-deduce-init-list)

Can anyone explain how I can make this work without warnings? Thanks!

Body:
A "thing" like {1,2,3} does not qualify as an expression. It has no type. Therefore, no type deduction is done. But C++0x makes an explicit exception for 'auto', so

auto x = {1,2,3};

actually works and decltype(x) will be initializer_list<int>. But this is a special rule that only applies to auto. I guess they wanted to make loops like these

for (int x : {2,3,5,7,11}) {
   ...
}

work since this kind of loop exploits the special rule.

As for solving the problem, you could add an initializer_list<T> overload as a "wrapper":

template<class T>
inline void outer(initializer_list<T> il) {
   inner(il);
}

I didn't test this but my current understanding is that it should work.


问:
Can't scroll to top of flex item that is overflowing container
In attempting to make a useful modal using flexbox, I found what seems to be a browser issue and am wondering if there is a known fix or workaround -- or ideas on how to resolve it.

The thing I'm trying to solve has two aspects. First, getting the modal window vertically centered, which works as expected. The second is to get the modal window to scroll -- externally, so the whole modal window scrolls, not the contents within it (this is so you can have dropdowns and other UI elements that can extend outside of the bounds of the modal -- like a custom date picker, etc.)

However, when combining the vertical centering with scroll bars, the top of the modal can become inaccessible as it begins to overflow. In the above example, you can resize to force the overflow, and in doing so it allows you to scroll to the bottom of the modal, but not to the top (first paragraph is cut off).

.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  overflow-x: auto;
}
.modal-container .modal-window {
  display: -ms-flexbox;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* Optional support to confirm scroll behavior makes sense in IE10
  //-ms-flex-direction: column;
  //-ms-flex-align: center;
  //-ms-flex-pack: center; */
  height: 100%;
}
.modal-container .modal-window .modal-content {
  border: 1px solid #ccc;
  border-radius: 4px;
  background: #fff;
  width: 100%;
  max-width: 500px;
  padding: 10px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal-container">
    <div class="modal-window">
        <div class="modal-content">
            <p class="p3">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            <p class="p3">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            <p class="p3">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        </div>
    </div>
</div></code>```

This affects (current) Firefox, Safari, Chrome, and Opera. It does interestingly behave correctly in IE10 if you comment in the IE10 vendor prefixed CSS -- I did not bother testing in IE11 yet, but assume the behavior matches that of IE10.

Here's the link to the example code (highly simplified)

https://jsfiddle.net/dh9k18k0/2/

答:
According to MDN, the safe value can now be provided to properties like align-items and justify-content. It's described as follows:

If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start.

So, it might be used as follows.

```<code>.rule
{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: safe center;
}
</code>```

However, it's unclear how much browser support it has, I could not find any examples of its use, and I have been having some issues with it myself. Mentioning it here to draw more attention to it.

ContentLicense: CC BY-SA 4.0

Body:
In attempting to make a useful modal using flexbox, I found what seems to be a browser issue and am wondering if there is a known fix or workaround -- or ideas on how to resolve it.

The thing I'm trying to solve has two aspects. First, getting the modal window vertically centered, which works as expected. The second is to get the modal window to scroll -- externally, so the whole modal window scrolls, not the contents within it (this is so you can have dropdowns and other UI elements that can extend outside of the bounds of the modal -- like a custom date picker, etc.)

However, when combining the vertical centering with scroll bars, the top of the modal can become inaccessible as it begins to overflow. In the above example, you can resize to force the overflow, and in doing so it allows you to scroll to the bottom of the modal, but not to the top (first paragraph is cut off).

.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  overflow-x: auto;
}
.modal-container .modal-window {
  display: -ms-flexbox;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* Optional support to confirm scroll behavior makes sense in IE10
  //-ms-flex-direction: column;
  //-ms-flex-align: center;
  //-ms-flex-pack: center; */
  height: 100%;
}
.modal-container .modal-window .modal-content {
  border: 1px solid #ccc;
  border-radius: 4px;
  background: #fff;
  width: 100%;
  max-width: 500px;
  padding: 10px
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

This affects (current) Firefox, Safari, Chrome, and Opera. It does interestingly behave correctly in IE10 if you comment in the IE10 vendor prefixed CSS -- I did not bother testing in IE11 yet, but assume the behavior matches that of IE10.

Here's the link to the example code (highly simplified)

https://jsfiddle.net/dh9k18k0/2/

Body:
According to MDN, the safe value can now be provided to properties like align-items and justify-content. It's described as follows:

If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start.

So, it might be used as follows.

.rule
{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: safe center;
}

However, it's unclear how much browser support it has, I could not find any examples of its use, and I have been having some issues with it myself. Mentioning it here to draw more attention to it.

ContentLicense: CC BY-SA 3.0


问:
Creating an array of digits in base 10, starting from an array of words
So, starting from an array of words, I have to create an array to include the digits of each given word, written in base 10.

So if I have

```<code>s DW 12345, 20778, 4596
</code>```

the result should be this BYTE array

```<code>t DB 1, 2, 3, 4, 5, 2, 0, 7, 7, 8, 4, 5, 9, 6
</code>```

I've been suggested how to do it, I've tried implementing it, but I get the following errors

Argument to operation or instruction has illegal size"

(regarding the "push al" and "pop al" lines)

Here's the code I've tried implementing:

```<code>ASSUME cs:text_,ds:data_

data_ SEGMENT

s dw 12345, 20778, 4596
l equ $-sir
d db (l/2)*5 dup (?)

data_ ENDS

text_ SEGMENT
start:
    mov ax, data_
    mov ds, ax
    mov es, ax
    mov si, offset s
    mov di, offset d
    mov cx, l    ;storing the length of s
    mov dl, 10
    mov ax, [si] ;storing the data of si into ax so that the division can be made
    cld          ;setting the direction flag
    jmp loop1
    cloop1:
        div dl   ;divide by 10 so we can get the remainder
        push al  ;ERROR LINE ;my plan was to store the value of al into the stack, so I can store the remainder into al
        mov al, ah
        stosb    ;we add the remainder to the final line
        pop al   ;ERROR LINE ;my plan was to get the value of al from the stack and do the instruction once againq
    loop cloop1
    loop1:        ;the role of this loop is to repeat the instruction as long as there are words left (similar to while instruction in C++)
        cmp ax, 0
        jg cloop1  ;if there are words left, the code keeps on being executed
    loop loop1
    mov ax, 4c00h
    int 21h
    text_ ENDS
    end start
</code>```

And here's the idea it's based on (represented in C++):

```<code>nr=0;
while(x>0)
 {c=x%10;
  nr=nr+x*10;
  x=x/10;
 }
cout<<nr;
</code>```

Thanks in advance and sorry for any mistakes. Any advice regarding my problem would be much appreciated

答: You can't push an 8 bit register onto the stack.  In 16 bit mode, you can only push and pop 16 or 32 bit registers.  Try to replace push al and pop al with push ax and pop ax.

Body:
So, starting from an array of words, I have to create an array to include the digits of each given word, written in base 10.

So if I have

s DW 12345, 20778, 4596

the result should be this BYTE array

t DB 1, 2, 3, 4, 5, 2, 0, 7, 7, 8, 4, 5, 9, 6

I've been suggested how to do it, I've tried implementing it, but I get the following errors

Argument to operation or instruction has illegal size"

(regarding the "push al" and "pop al" lines)

Here's the code I've tried implementing:

ASSUME cs:text_,ds:data_

data_ SEGMENT

s dw 12345, 20778, 4596
l equ $-sir
d db (l/2)*5 dup (?)

data_ ENDS

text_ SEGMENT
start:
    mov ax, data_
    mov ds, ax
    mov es, ax
    mov si, offset s
    mov di, offset d
    mov cx, l    ;storing the length of s
    mov dl, 10
    mov ax, [si] ;storing the data of si into ax so that the division can be made
    cld          ;setting the direction flag
    jmp loop1
    cloop1:
        div dl   ;divide by 10 so we can get the remainder
        push al  ;ERROR LINE ;my plan was to store the value of al into the stack, so I can store the remainder into al
        mov al, ah
        stosb    ;we add the remainder to the final line
        pop al   ;ERROR LINE ;my plan was to get the value of al from the stack and do the instruction once againq
    loop cloop1
    loop1:        ;the role of this loop is to repeat the instruction as long as there are words left (similar to while instruction in C++)
        cmp ax, 0
        jg cloop1  ;if there are words left, the code keeps on being executed
    loop loop1
    mov ax, 4c00h
    int 21h
    text_ ENDS
    end start

And here's the idea it's based on (represented in C++):

nr=0;
while(x>0)
 {c=x%10;
  nr=nr+x*10;
  x=x/10;
 }
cout<<nr;

Thanks in advance and sorry for any mistakes. Any advice regarding my problem would be much appreciated


问:
Accessing form's button field
I have a button on my form, but I am unable to access it from my code. My code (from Program.cs):

Form1.button1.Text = "Button text"
```

I cannot access it due to it's protection level. What shall I do to change this field protection level or something?

答:
On the properties window you can change the privacy of the components. You need to change the button privacy to public.

--EDIT

What fildor wrote is a better aproach

Title: Accessing form's button field

Body:
I have a button on my form, but I am unable to access it from my code. My code (from Program.cs):

Form1.button1.Text = "Button text"

I cannot access it due to it's protection level. What shall I do to change this field protection level or something?


问:
QQ Plot for Poisson Distribution in Python
I've been trying to make a QQ plot in python for a poisson distribution. Here is what I have so far:

```<code>import numpy as np
import statsmodels.api as sm
import scipy.stats as stats
pois = np.random.poisson(2.5, 100)  #creates random Poisson distribution with mean = 2.5
fig =sm.qqplot(pois, stats.poisson, line = 's')
plt.show()
</code>```

Whenever I do this, I get "AttributeError: 'poisson_gen' object has no attribute 'fit'"

When googling that error, I found a lot of people saying that there is no Poisson.fit available. I'm pretty sure that the qqplot function is calling Poisson.fit. Does this mean that the qqplot function will not work with the Poisson distribution? If the qqplot function does not work with Poisson distributions, how would you recommend generating this plot? Any recommendations would be appreciated.

答:
I had the same error. The following seemed to work for me:</p>

```<code>import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
data=np.random.poisson(2.5, 100)
stats.probplot(data, dist='poisson', sparams=(2.5,), plot=plt)
plt.show()
</code>```

Body:
I've been trying to make a QQ plot in python for a poisson distribution. Here is what I have so far:

import numpy as np
import statsmodels.api as sm
import scipy.stats as stats
pois = np.random.poisson(2.5, 100)  #creates random Poisson distribution with mean = 2.5
fig =sm.qqplot(pois, stats.poisson, line = 's')
plt.show()

Whenever I do this, I get "AttributeError: 'poisson_gen' object has no attribute 'fit'"

When googling that error, I found a lot of people saying that there is no Poisson.fit available. I'm pretty sure that the qqplot function is calling Poisson.fit. Does this mean that the qqplot function will not work with the Poisson distribution? If the qqplot function does not work with Poisson distributions, how would you recommend generating this plot? Any recommendations would be appreciated.

Body:
I had the same error. The following seemed to work for me:

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
data=np.random.poisson(2.5, 100)
stats.probplot(data, dist='poisson', sparams=(2.5,), plot=plt)
plt.show()


问:
How to keep imports neat in Django?
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.

I'm looking for  a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?

Update

On request, here is an example from one of my views.py files.

```<code>from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from django.core.urlresolvers import reverse

from models import Listing, LocationData

from django.template import RequestContext

import sys
import urllib
if sys.version_info <= (2, 5):
    import simplejson as json
else:
    import json

import forms
import sanitize

from models import RentListing, VacationListing, SaleListing

from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory

from django.core.urlresolvers import reverse
</code>```

which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Keeping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.

Is it worth breaking the style guideline of not using the * import for the sake of shorter, more maintainable import sections in the actual file?

答:
You're right that it's easy to ignore DRY when working Django imports, or with python imports in general.

It's sometimes beneficial to separate common imports by domain, then create a module for managing those imports.  The next step is one of the few exceptions I make to my personal rule of "Don't use import *"

stuff_i_always_use.py

```<code>import django.templates as templates
import tagalog.tagalog_appengine as tagalog
#etc
</code>```

Then in some file:

```<code>from stuff_i_aways_use import *
</code>```

Title: How to keep imports neat in Django?

Body:
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.

I'm looking for  a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?

Update

On request, here is an example from one of my views.py files.

from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from django.core.urlresolvers import reverse

from models import Listing, LocationData

from django.template import RequestContext

import sys
import urllib
if sys.version_info <= (2, 5):
    import simplejson as json
else:
    import json

import forms
import sanitize

from models import RentListing, VacationListing, SaleListing

from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory

from django.core.urlresolvers import reverse

which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Keeping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.

Is it worth breaking the style guideline of not using the * import for the sake of shorter, more maintainable import sections in the actual file?

Body:
You're right that it's easy to ignore DRY when working Django imports, or with python imports in general.

It's sometimes beneficial to separate common imports by domain, then create a module for managing those imports.  The next step is one of the few exceptions I make to my personal rule of "Don't use import *"

stuff_i_always_use.py

import django.templates as templates
import tagalog.tagalog_appengine as tagalog
#etc

Then in some file:

from stuff_i_aways_use import *


问:
How to place the last
 on the right side of my page?
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
                <li>
                    <div class="flagChangeCountry">
                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div></code>```

i want to move this image to right side which is in div. here it is.

```<code><li>
    <div class="flagChangeCountry">
        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
    </div>
</li>
</code>```

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

答:
I would use display: flex instead of float. You have more control over your elements in display flex. In display flex you can easily adjust your element inside the box. Use flex grow to make an element bigger or smaller.

Please take a look at this guide-to-flexbox.

Title: How to place the last <li> on the right side of my page?

Body:
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

Home

About

Contact

                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

i want to move this image to right side which is in div. here it is.

        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.


问:
Open a custom busy indicator while a main window is busy or doing some task
My application is based on WPF.

Task is I need to show a custom busy indicator while something is working in the main window ( because the app UI will be freezed untill it complete the task). So what I particularly want is as below

```<code>// Code in main window
CustomBusyIndicator.ShowDialog();
//....
//..code that takes time
//....
CustomBusyIndicator.Close();
</code>```

So I must implement a window which must be flexible to call anywhere in my main application to indicate busy.

Here two points should be kept in mind,
1. When i show CustomBusyIndicator,  in background the main window should be running it's task
2. When i show CustomBusyIndicator, the CustomBusyIndicator should be always on top of main window, user must not be able to use the main window, if he switch to other application using Start+tab or something and again when he switch back to my application,the CustomBusyIndicator should be on top(if it is not closed).

When the task is completed I should be able call just close() method to close the CustomBusyIndicator from the main window as shown in code.

答:
If you don't know how to work with async await, just move your long running logic in a backgroundworker. There are several options for making the backgroundworker communicate without problems with the main GUI thread.
Based on your question and your level of experience I think you are way over your head with async wait. But Rufo's solution is fine too.

Google is your friend, There is a lot of information about using the backgroundworker and about async await too. It will just take a bit longer to fully grasp the potential of async await. Async await is btw not a solution for everything. I ran into a situation today where I ran in a database with EF6 that simply says it does not support async operations. Works perfectly well with sql server but this was pervasive. Total dissapointment because now me too have to use a backgroundworker where my first idea was async await.

The idea behind async await, is that the gui thread is not blocked if you are doing a long running task. It is more like a waitpoint where it will continue if that long operation is finished.

Other options are to use RX, but that difficulty level increases again.

Use the backgroundworker and you are fine, and your gui is never blocked. You can even cancel the work of the backgroundworker. Excellent solution for you.

Body:
My application is based on WPF.

Task is I need to show a custom busy indicator while something is working in the main window ( because the app UI will be freezed untill it complete the task). So what I particularly want is as below

// Code in main window
CustomBusyIndicator.ShowDialog();
//....
//..code that takes time
//....
CustomBusyIndicator.Close();

So I must implement a window which must be flexible to call anywhere in my main application to indicate busy.

Here two points should be kept in mind,
1. When i show CustomBusyIndicator,  in background the main window should be running it's task
2. When i show CustomBusyIndicator, the CustomBusyIndicator should be always on top of main window, user must not be able to use the main window, if he switch to other application using Start+tab or something and again when he switch back to my application,the CustomBusyIndicator should be on top(if it is not closed).

When the task is completed I should be able call just close() method to close the CustomBusyIndicator from the main window as shown in code.


问:
Twitter Authentication on Swift and SafariServices.framework
I am trying to implment Twitter authentication on my Swift based app by following the doc https://dev.twitter.com/twitterkit/ios/log-in-with-twitter

At the "Prerequisites" Section:

3.Add SafariServices.framework to use SFSafariViewController.

My understanding is, it will use Safari in my App to register or login with Twitter, if the Twitter App is not installed.

However, what I don't understand is:

If I add the following to my ViewController, meaning the same as SafariServices.framework?

import SafariServices

What does it exactly mean by

"to use SFSafariViewController"?

Do I need to add additional inheritance in my ViewController class?

答:
It seems that in IOS 11 and xCode 9, you can safely ignore this step.

Without importing SafariServices and inheritance additional views in the class, twitter button is able to handle calling safari for register/login.


问:
error Unable to open sql file
I am trying to execute a batch file from windows task scheduler . After opening command prompt  it showing error unable to open SQL file. but when i am trying to run batch file by double clicking it is running smoothly and updating the database properly .

code used -->  Sqlplus -s %userid%/%password%@%database% @"abc.sql"

答: Try checking access rights for the SQL file</p>

Title: error Unable to open sql file


问:
Scrambling/Unscrambling a string in Classic ASP
I'm wanting to send a string that has some meaning through the URL.

I know that I could probably do other things to send a string, but this is the only way in this situation.

I'm wanting send it and an unreadable format and be able to get the original string back later. I'm trying to avoid the words encrypt/decrypt because I've done research and It seems a bit more envolved than what I'm wanting in classic ASP( unless I'm missing something ). So I'm not really wanting to IMPLEMENT a encrypt/decrypt algorithm. I'm hoping there is something built into ASP that will allow me to do this.

I'm looking for both the way to scramble the message and a way to get it back.

Any suggestions?

答:
No, there's not a default built in implementation for encrypting/decrypting a string in classic ASP.  That's why there are a million custom examples on how to encrypt/decrypt strings in classic ASP.  It's really not as "involved" as you would think.  For example, check out this example from 2002:

Encrypting/Decrypting Classic ASP querystrings


问:
Error when copying ssh keys from another computer
I copied my ssh keys from one computer to another to grant access to all servers without update them all.

I simply copied over the id_rsa and the id_rsa.pub files into the ~/.ssh directory.

I then tried to use Git and got this issue:

```<code>$ git pull
sign_and_send_pubkey: signing failed: agent refused operation
</code>```

答:
I found a solution. I just needed to run:

```<code>$ ssh-add
</code>```

And, the git commands worked perfectly.

Body:
I copied my ssh keys from one computer to another to grant access to all servers without update them all.

I simply copied over the id_rsa and the id_rsa.pub files into the ~/.ssh directory.

I then tried to use Git and got this issue:

$ git pull
sign_and_send_pubkey: signing failed: agent refused operation

Body:
I found a solution. I just needed to run:

$ ssh-add

And, the git commands worked perfectly.


问:
MySQL Multi JOIN extremely slow
This is a problem that I'm not sure exactly where the root cause could be, so I'm going to provide details and the trouble points I've thought of. Any help would be awesome (beer on me if you live nearby). I have these three tables:

practices:

```<code>`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(125) NOT NULL,
`description` text,
`deleted` int(11) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(70) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_update_by` varchar(70) NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
</code>```

locations:

```<code>`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`practice_fk` int(11) unsigned NOT NULL,
`phone` char(12) DEFAULT NULL,
`fax` char(12) DEFAULT NULL,
`address` varchar(125) DEFAULT NULL,
`address_two` varchar(125) DEFAULT NULL,
`city` varchar(40) NOT NULL,
`state` char(2) NOT NULL,
`zip` char(5) DEFAULT NULL,
`lat` decimal(7,5) DEFAULT NULL,
`lng` decimal(7,5) DEFAULT NULL,
`deleted` int(11) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(70) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_update_by` varchar(70) NOT NULL,
`email` varchar(150) DEFAULT NULL,
`practice_name_temp` text,
PRIMARY KEY (`id`)
</code>```

contacts:

```<code>`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`location_fk` int(11) unsigned NOT NULL,
`practice_fk` int(11) unsigned NOT NULL,
`fname` varchar(25) NOT NULL,
`lname` varchar(45) NOT NULL,
`phone` varchar(35) DEFAULT NULL,
`mobile` char(12) DEFAULT NULL,
`email` varchar(125) DEFAULT NULL,
`title` varchar(100) DEFAULT NULL,
`description` text,
`deleted` int(11) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(70) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_update_by` varchar(70) NOT NULL,
PRIMARY KEY (`id`)
</code>```

The basic idea behind the architecture is there is a list of practices. A practice can have multiple locations, but a location cannot exist without being associated with a practice. Then, a practice can also have multiple contacts, but a contact must be associated with a practice and a location. [This is where one part of the problem may begin]. So, I have this query:

```<code>SELECT DISTINCT p.id AS practice_id,
                p.name,
                l.id AS location_id,
                address AS location_address,
                l.phone AS disp_phone,
                CONCAT(pc.fname, ' ', pc.lname) AS practiceContact,
                CONCAT(lc.fname, ' ', lc.lname) AS locationContact,
                pcc.qty AS practice_only_contact_qty,
                lcc.qty AS location_contact_qty,
                (pcc.qty + lcc.qty) AS contactQty
            FROM practices p
            LEFT JOIN practice_locations l on l.practice_fk=p.id
            LEFT JOIN (
                SELECT count(id) AS qty, practice_fk
                FROM practice_contacts
                GROUP BY practice_fk
            ) pcc ON pcc.practice_fk=p.id
            LEFT JOIN practice_contacts pc ON pc.practice_fk=pcc.practice_fk AND pcc.qty=1
            LEFT JOIN (
                SELECT count(id) AS qty, location_fk
                FROM practice_contacts
                GROUP BY location_fk
            ) lcc ON lcc.location_fk=l.id
            LEFT JOIN practice_contacts lc ON lc.location_fk=lcc.location_fk AND lcc.qty=1
            WHERE p.name IS NOT NULL AND p.deleted IS NULL
            GROUP BY p.id
            ORDER BY p.name ASC, l.state, l.city, l.address;
</code>```

What this query is supposed to do is:

Gather the practice ID and name.

If there is a single location, grab it's address. Otherwise, grab the first location's address

If there is a single contact associated with the practice, grab their name. Otherwise, grab the first contact's name

Count how many contacts there are associated with the practice

Count how many locations are associated with the practice

Group all this together by the practice ID, then order it alphabetically according to the practice name, then by location

So, it does all of that right now. REALLLLLLLYYY SLOWLY. When I only had five records in the practices table, and less than 20 in the other two tables, the query worked great. Now I've imported data into these tables (~9,000 records in practices, 14,000+ in locations, and 25,000+ in contacts), and this query takes over 28 seconds to return what I need. If I pull the group by's out, we're looking at 33+ seconds. Screw me, right?!

Obviously, this is unacceptable. This dataset is relatively small, and this application is only going to grow with potentially millions of contacts being in here at some point. So, I'm wondering if this is in fact a three plus part issue:

First part: should I introduce a reference table [kind of like a view], to store these relationships -- something like:

```<code>`id` int(11) unsigned not null,
`practice_fk` int(11) unsigned not null,
`location_fk` int(11) unsigned not null,
`contact_fk` int(11) unsigned not null,
PRIMARY KEY(id),
KEY(practice_fk),
KEY(location_fk),
KEY(contact_fk)
</code>```

But if I do that, I'm unsure of how I would construct the query to pull the data as I need? And would it offer any performance benefits.

Second Part: I don't have the proper indexes in place. After scouring the MySQL docs and stumbling across this post (https://dba.stackexchange.com/questions/75091/why-are-simple-selects-on-innodb-100x-slower-than-on-myisam) I've come to understand InnoDB is a slow pig. This is unacceptable from a UX perspective but from an architecture perspective, I'm locked into this engine. How would I set up the indexes properly to get this query back to the sub-second range?

Third part: my query is garbage. I think this is probably the biggest culprit. I'm still learning how to structure these more complex SQL queries, and this is took some effort to craft in itself, so any pointers on how to make this thing less of a pig would be great.

I've tried a variety of manipulations on my query (pulling out group by's, dropping the order by, etc) and there's hardly any change. The query consistently is running at between 28 and 33 seconds. Any guidance will be beyond appreciated.

答:
It seems you don't really need to order by anything in the subqueries. Therefore, you can explicitly set ORDER BY NULL to improve performance of the subqueries.

Modified query:

```<code>SELECT
        DISTINCT p.id AS practice_id,
        p.name,
        l.id AS location_id,
        l.address AS location_address,
        l.phone AS disp_phone,
        CONCAT(pc.fname,
        ' ',
        pc.lname) AS practiceContact,
        CONCAT(lc.fname,
        ' ',
        lc.lname) AS locationContact,
        pcc.qty AS practice_only_contact_qty,
        lcc.qty AS location_contact_qty,
        (pcc.qty + lcc.qty) AS contactQty
    FROM
        practices p
    LEFT JOIN
        practice_locations l
            ON l.practice_fk = p.id
    LEFT JOIN
        (
            SELECT
                COUNT(practice_contacts.id) AS qty,
                practice_contacts.practice_fk
            FROM
                practice_contacts
            GROUP BY
                practice_contacts.practice_fk
            ORDER BY
                NULL
        ) pcc
            ON pcc.practice_fk = p.id
    LEFT JOIN
        practice_contacts pc
            ON pc.practice_fk = pcc.practice_fk
            AND pcc.qty = 1
    LEFT JOIN
        (
            SELECT
                COUNT(practice_contacts.id) AS qty,
                practice_contacts.location_fk
            FROM
                practice_contacts
            GROUP BY
                practice_contacts.location_fk
            ORDER BY
                NULL
        ) lcc
            ON lcc.location_fk = l.id
    LEFT JOIN
        practice_contacts lc
            ON lc.location_fk = lcc.location_fk
            AND lcc.qty = 1
    WHERE
        p.name IS NOT NULL
        AND p.deleted IS NULL
    GROUP BY
        p.id
    ORDER BY
        p.name ASC,
        l.state,
        l.city,
        l.address
</code>```

Also, add the following indexes which might optimize your query:

```<code>ALTER TABLE `practices` ADD INDEX `practices_index_1` (`deleted`,`id`,`name`);
ALTER TABLE `practice_contacts` ADD INDEX `practice_contacts_index_1` (`practice_fk`,`location_fk`);
ALTER TABLE `practice_contacts` ADD INDEX `practice_contacts_index_2` (`location_fk`);
ALTER TABLE `practice_locations` ADD INDEX `practice_locations_index_1` (`practice_fk`,`id`);
</code>```

Title: MySQL Multi JOIN extremely slow

Body:
This is a problem that I'm not sure exactly where the root cause could be, so I'm going to provide details and the trouble points I've thought of. Any help would be awesome (beer on me if you live nearby). I have these three tables:

practices:

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(125) NOT NULL,
`description` text,
`deleted` int(11) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(70) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_update_by` varchar(70) NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)

locations:

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`practice_fk` int(11) unsigned NOT NULL,
`phone` char(12) DEFAULT NULL,
`fax` char(12) DEFAULT NULL,
`address` varchar(125) DEFAULT NULL,
`address_two` varchar(125) DEFAULT NULL,
`city` varchar(40) NOT NULL,
`state` char(2) NOT NULL,
`zip` char(5) DEFAULT NULL,
`lat` decimal(7,5) DEFAULT NULL,
`lng` decimal(7,5) DEFAULT NULL,
`deleted` int(11) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(70) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_update_by` varchar(70) NOT NULL,
`email` varchar(150) DEFAULT NULL,
`practice_name_temp` text,
PRIMARY KEY (`id`)

contacts:

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`location_fk` int(11) unsigned NOT NULL,
`practice_fk` int(11) unsigned NOT NULL,
`fname` varchar(25) NOT NULL,
`lname` varchar(45) NOT NULL,
`phone` varchar(35) DEFAULT NULL,
`mobile` char(12) DEFAULT NULL,
`email` varchar(125) DEFAULT NULL,
`title` varchar(100) DEFAULT NULL,
`description` text,
`deleted` int(11) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(70) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_update_by` varchar(70) NOT NULL,
PRIMARY KEY (`id`)

The basic idea behind the architecture is there is a list of practices. A practice can have multiple locations, but a location cannot exist without being associated with a practice. Then, a practice can also have multiple contacts, but a contact must be associated with a practice and a location. [This is where one part of the problem may begin]. So, I have this query:

SELECT DISTINCT p.id AS practice_id,
                p.name,
                l.id AS location_id,
                address AS location_address,
                l.phone AS disp_phone,
                CONCAT(pc.fname, ' ', pc.lname) AS practiceContact,
                CONCAT(lc.fname, ' ', lc.lname) AS locationContact,
                pcc.qty AS practice_only_contact_qty,
                lcc.qty AS location_contact_qty,
                (pcc.qty + lcc.qty) AS contactQty
            FROM practices p
            LEFT JOIN practice_locations l on l.practice_fk=p.id
            LEFT JOIN (
                SELECT count(id) AS qty, practice_fk
                FROM practice_contacts
                GROUP BY practice_fk
            ) pcc ON pcc.practice_fk=p.id
            LEFT JOIN practice_contacts pc ON pc.practice_fk=pcc.practice_fk AND pcc.qty=1
            LEFT JOIN (
                SELECT count(id) AS qty, location_fk
                FROM practice_contacts
                GROUP BY location_fk
            ) lcc ON lcc.location_fk=l.id
            LEFT JOIN practice_contacts lc ON lc.location_fk=lcc.location_fk AND lcc.qty=1
            WHERE p.name IS NOT NULL AND p.deleted IS NULL
            GROUP BY p.id
            ORDER BY p.name ASC, l.state, l.city, l.address;

What this query is supposed to do is:

Gather the practice ID and name.

If there is a single location, grab it's address. Otherwise, grab the first location's address

If there is a single contact associated with the practice, grab their name. Otherwise, grab the first contact's name

Count how many contacts there are associated with the practice

Count how many locations are associated with the practice

Group all this together by the practice ID, then order it alphabetically according to the practice name, then by location

So, it does all of that right now. REALLLLLLLYYY SLOWLY. When I only had five records in the practices table, and less than 20 in the other two tables, the query worked great. Now I've imported data into these tables (~9,000 records in practices, 14,000+ in locations, and 25,000+ in contacts), and this query takes over 28 seconds to return what I need. If I pull the group by's out, we're looking at 33+ seconds. Screw me, right?!

Obviously, this is unacceptable. This dataset is relatively small, and this application is only going to grow with potentially millions of contacts being in here at some point. So, I'm wondering if this is in fact a three plus part issue:

First part: should I introduce a reference table [kind of like a view], to store these relationships -- something like:

`id` int(11) unsigned not null,
`practice_fk` int(11) unsigned not null,
`location_fk` int(11) unsigned not null,
`contact_fk` int(11) unsigned not null,
PRIMARY KEY(id),
KEY(practice_fk),
KEY(location_fk),
KEY(contact_fk)

But if I do that, I'm unsure of how I would construct the query to pull the data as I need? And would it offer any performance benefits.

Second Part: I don't have the proper indexes in place. After scouring the MySQL docs and stumbling across this post (https://dba.stackexchange.com/questions/75091/why-are-simple-selects-on-innodb-100x-slower-than-on-myisam) I've come to understand InnoDB is a slow pig. This is unacceptable from a UX perspective but from an architecture perspective, I'm locked into this engine. How would I set up the indexes properly to get this query back to the sub-second range?

Third part: my query is garbage. I think this is probably the biggest culprit. I'm still learning how to structure these more complex SQL queries, and this is took some effort to craft in itself, so any pointers on how to make this thing less of a pig would be great.

I've tried a variety of manipulations on my query (pulling out group by's, dropping the order by, etc) and there's hardly any change. The query consistently is running at between 28 and 33 seconds. Any guidance will be beyond appreciated.

Body:
It seems you don't really need to order by anything in the subqueries. Therefore, you can explicitly set ORDER BY NULL to improve performance of the subqueries.

Modified query:

SELECT
        DISTINCT p.id AS practice_id,
        p.name,
        l.id AS location_id,
        l.address AS location_address,
        l.phone AS disp_phone,
        CONCAT(pc.fname,
        ' ',
        pc.lname) AS practiceContact,
        CONCAT(lc.fname,
        ' ',
        lc.lname) AS locationContact,
        pcc.qty AS practice_only_contact_qty,
        lcc.qty AS location_contact_qty,
        (pcc.qty + lcc.qty) AS contactQty
    FROM
        practices p
    LEFT JOIN
        practice_locations l
            ON l.practice_fk = p.id
    LEFT JOIN
        (
            SELECT
                COUNT(practice_contacts.id) AS qty,
                practice_contacts.practice_fk
            FROM
                practice_contacts
            GROUP BY
                practice_contacts.practice_fk
            ORDER BY
                NULL
        ) pcc
            ON pcc.practice_fk = p.id
    LEFT JOIN
        practice_contacts pc
            ON pc.practice_fk = pcc.practice_fk
            AND pcc.qty = 1
    LEFT JOIN
        (
            SELECT
                COUNT(practice_contacts.id) AS qty,
                practice_contacts.location_fk
            FROM
                practice_contacts
            GROUP BY
                practice_contacts.location_fk
            ORDER BY
                NULL
        ) lcc
            ON lcc.location_fk = l.id
    LEFT JOIN
        practice_contacts lc
            ON lc.location_fk = lcc.location_fk
            AND lcc.qty = 1
    WHERE
        p.name IS NOT NULL
        AND p.deleted IS NULL
    GROUP BY
        p.id
    ORDER BY
        p.name ASC,
        l.state,
        l.city,
        l.address

Also, add the following indexes which might optimize your query:

ALTER TABLE `practices` ADD INDEX `practices_index_1` (`deleted`,`id`,`name`);
ALTER TABLE `practice_contacts` ADD INDEX `practice_contacts_index_1` (`practice_fk`,`location_fk`);
ALTER TABLE `practice_contacts` ADD INDEX `practice_contacts_index_2` (`location_fk`);
ALTER TABLE `practice_locations` ADD INDEX `practice_locations_index_1` (`practice_fk`,`id`);


问:
SQL Server Database Project
I want to use database project for script deployment in Azure SQL Server, I don't want to import full database. I just want to use database project for delta script. I added a project and included one script file with none as build action that contains create table statement , I am publishing the project, It's completing successfully but create statement is not executing. What is wrong here? Is there any other way to do this?</p>

答:
TLDR: Set your build action to "Post Deployment Script".

Longer:

What happens in SSDT is that all the files that have a build action of "Build" are built into a model of what the database should look like. When the deploy happens that model is compared to the target database and if there are any changes, a change script it generated and then optionally deployed.

If you have any file marked pre or post deployment script then they are either prepended or appended to the change script and will be run as part of the deployment.

If you have any files with a build action of "None" then SSDT ignores them, you could put anything in there, even an ascii picture of a donkey and the project will still build and deploy (obviously your ascii donkey won't get deployed anywhere).

If you just want to use SSDT to do your deployments you can just set the build action to pre or post deploy and it will be included. This is pretty odd though, either don't use SSDT or use SSDT and put the model of your entire database in there.

Personally, I would use SSDT properly and live the dream.

Ed

Title: SQL Server Database Project


问:
React native card (native base) onPress doesn't work
I want to display cards with news from a JSON file.
Getting the JSON works fine, but I want to add a onPress event, so I can click the card and navigate to the article.

My card view:

```<code><Card>
  <CardItem button onPress={this._OnButtonPress(news.id)}>
    <Left>
      <Body>
        <Text style={styles.cardText}>{news.title}</Text>
      </Body>
    </Left>
  </CardItem>
  <CardItem>
    <Left>
        <Icon style={styles.icon} name="chatbubbles" />
        <Text>{news.comments} comments</Text>
    </Left>
    <Right>
      <Text>{news.published}</Text>
    </Right>
  </CardItem>
</Card>
</code>```

I am trying to pass a variable to the onButtonPress() function

```<code>_OnButtonPress(newsID) {
  Alert.alert(newsID.toString());
}
</code>```

To test the onPress event, all I did is alert the parameter.

I don't see anything wrong, but still I got this error

Does anyone know how I can fix this and what Im doing wrong here.
Thanks in advance.

Update

My updated class:

```<code>import React, { Component } from "react";
import {
  Image,
  ListView,
  StyleSheet,
  Text,
  View,
  Alert
} from 'react-native';

import {
  Container,
  Header,
  Left,
  Right,
  Button,
  Card,
  CardItem,
  Icon,
  Body,
  Content,
  Logo
} from 'native-base';

import styles from "./styles";

const logo = require("../../../img/f1today.png");

var REQUEST_URL = 'http://v2.first-place.nl/test/news.json';

class News extends Component {
  constructor(props) {
    super(props);

    this._OnButtonPress = this._OnButtonPress.bind(this);

    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  }

  _OnButtonPress(newsID) {
    Alert.alert(newsID.toString());
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(responseData.articles),
          loaded: true,
        });
      })
      .done();
  }

  render() {

    if (!this.state.loaded) {
      return this.renderLoadingView();
    }

    return (
      <Container style={styles.container}>
        <Header
          style={{ backgroundColor: "#fff" }}
          androidStatusBarColor="#f05423"
          iosBarStyle="light-content">

        <Left>
          <Button
            transparent
            onPress={() => this.props.navigation.navigate("DrawerOpen")}
          >
            <Icon name="ios-menu" style={{color: 'black'}} />
          </Button>
        </Left>
        <Body>
          <Image source={logo} style={styles.headerLogo} />
        </Body>
        <Right />

      </Header>

      <Content padder>

        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderNews}
          style={styles.listView}
        />

      </Content>
    </Container>
    );
  }

  renderLoadingView() {
    return (
      <View style={styles.loading}>
        <Text>
          Loading news...
        </Text>
      </View>
    );
  }

  renderNews(news) {
    return (
      <Card>
        <CardItem button onPress={()=> this._OnButtonPress(news.id)}>
          <Left>
            <Body>
              <Text style={styles.cardText}>{news.title}</Text>
            </Body>
          </Left>
        </CardItem>
        <CardItem>
          <Left>
              <Icon style={styles.icon} name="chatbubbles" />
              <Text>{news.comments} comments</Text>
          </Left>
          <Right>
            <Text>{news.published}</Text>
          </Right>
        </CardItem>
      </Card>
    );
  }
}

export default News;
</code>```

答:
For me i left the button={true} prop off, when i added it works. See example below.</p>

```<code>  <CardItem
       button={true}
       onPress={() => {this.cardSelected(item.name)}}
       style={{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:0}}>
      <Image  source={item.img} style={{flex:1,resizeMode: 'cover',height: 175}} />
      <Text style={styles.cardheading}>{item.name}</Text>
        <Image source={cardline} style={styles.cardline}/>
        <Text style={styles.cardtext}> {item.text}</Text>

      </CardItem>
</code>```

Body:
I want to display cards with news from a JSON file.
Getting the JSON works fine, but I want to add a onPress event, so I can click the card and navigate to the article.

My card view:

<Card>
  <CardItem button onPress={this._OnButtonPress(news.id)}>
    <Left>

        <Text style={styles.cardText}>{news.title}</Text>

    </Left>
  </CardItem>
  <CardItem>
    <Left>
        <Icon style={styles.icon} name="chatbubbles" />
        <Text>{news.comments} comments</Text>
    </Left>
    <Right>
      <Text>{news.published}</Text>
    </Right>
  </CardItem>
</Card>

I am trying to pass a variable to the onButtonPress() function

_OnButtonPress(newsID) {
  Alert.alert(newsID.toString());
}

To test the onPress event, all I did is alert the parameter.

I don't see anything wrong, but still I got this error

Does anyone know how I can fix this and what Im doing wrong here.
Thanks in advance.

Update

My updated class:

import React, { Component } from "react";
import {
  Image,
  ListView,
  StyleSheet,
  Text,
  View,
  Alert
} from 'react-native';

import {
  Container,
  Header,
  Left,
  Right,
  Button,
  Card,
  CardItem,
  Icon,
  Body,
  Content,
  Logo
} from 'native-base';

import styles from "./styles";

const logo = require("../../../img/f1today.png");

var REQUEST_URL = 'http://v2.first-place.nl/test/news.json';

class News extends Component {
  constructor(props) {
    super(props);

    this._OnButtonPress = this._OnButtonPress.bind(this);

    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  }

  _OnButtonPress(newsID) {
    Alert.alert(newsID.toString());
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(responseData.articles),
          loaded: true,
        });
      })
      .done();
  }

  render() {

    if (!this.state.loaded) {
      return this.renderLoadingView();
    }

    return (
      <Container style={styles.container}>

        <Left>
          <Button
            transparent
            onPress={() => this.props.navigation.navigate("DrawerOpen")}
          >
            <Icon name="ios-menu" style={{color: 'black'}} />
          </Button>
        </Left>

          <Image source={logo} style={styles.headerLogo} />

        <Right />

      <Content padder>

        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderNews}
          style={styles.listView}
        />

      </Content>
    </Container>
    );
  }

  renderLoadingView() {
    return (
      <View style={styles.loading}>
        <Text>
          Loading news...
        </Text>
      </View>
    );
  }

  renderNews(news) {
    return (
      <Card>
        <CardItem button onPress={()=> this._OnButtonPress(news.id)}>
          <Left>

              <Text style={styles.cardText}>{news.title}</Text>

          </Left>
        </CardItem>
        <CardItem>
          <Left>
              <Icon style={styles.icon} name="chatbubbles" />
              <Text>{news.comments} comments</Text>
          </Left>
          <Right>
            <Text>{news.published}</Text>
          </Right>
        </CardItem>
      </Card>
    );
  }
}

export default News;

Body:
For me i left the button={true} prop off, when i added it works. See example below.

  <CardItem
       button={true}
       onPress={() => {this.cardSelected(item.name)}}
       style={{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:0}}>
      <Image  source={item.img} style={{flex:1,resizeMode: 'cover',height: 175}} />
      <Text style={styles.cardheading}>{item.name}</Text>
        <Image source={cardline} style={styles.cardline}/>
        <Text style={styles.cardtext}> {item.text}</Text>

      </CardItem>


问:
How to change message of success when adding product to cart in Woocommerce?
Well, the functionality of adding the product to the cart via ajax is 100% working, however a message below appears like this

Well, the code generated is this, automatic whenever the product is added to the cart successfully

```<code><a href="http://www.shopurl.com/cart/" class="added_to_cart wc-forward" title="View Cart">View Cart</a>
</code>```

I want to know how you can edit this particular line

答:
This works for me every time. Let me know if it works for you.</p>

```<code>/**
 * @snippet       Edit "successfully added to your cart"
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=494
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 2.5.2
 */

add_filter( 'wc_add_to_cart_message', 'bbloomer_custom_add_to_cart_message' );

function bbloomer_custom_add_to_cart_message() {

global $woocommerce;
$return_to  = get_permalink(woocommerce_get_page_id('shop'));
$message    = sprintf('<a href="%s" class="button wc-forwards">%s</a> %s', $return_to, __('Continue Shopping', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
return $message;
}
</code>```

Body:
Well, the functionality of adding the product to the cart via ajax is 100% working, however a message below appears like this

Well, the code generated is this, automatic whenever the product is added to the cart successfully

View Cart

I want to know how you can edit this particular line

Body:
This works for me every time. Let me know if it works for you.

/**
 * @snippet       Edit "successfully added to your cart"
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=494
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 2.5.2
 */

add_filter( 'wc_add_to_cart_message', 'bbloomer_custom_add_to_cart_message' );

function bbloomer_custom_add_to_cart_message() {

global $woocommerce;
$return_to  = get_permalink(woocommerce_get_page_id('shop'));
$message    = sprintf('<a href="%s" class="button wc-forwards">%s</a> %s', $return_to, __('Continue Shopping', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
return $message;
}


问:
How do bash's logical operators work (or why don't they work here)?
I have the following wrapper script:

```<code>#!/bin/bash

$local_time=`date +%H%M`
if [ $local_time -ge 1430 ] && [ $local_time -le 2230 ] ||
   [ $local_time -ge 0300 ] && [ $local_time -le 0400 ]
then
   echo 'pass'
else
   echo 'skip'
fi
</code>```

The idea being to create a wrapper script that runs a script between two disjoint time intervals. Each of the expressions being OR'd is evaluated correctly, however, when I OR both expressions, the test fails.

How do I fix this?

答:
You have two problems

You don't prefix your variables with a $ when you assign to them, only when you expand them

You need to enforce operator precedence with parens ( )

Also, since you're already using bash, might as well use its better syntax with the (( )) construct that allows you to use the comparison operators < > == != and you can use $() for command substitution instead of the backticks/gravemarks

```<code>#!/bin/bash

local_time=$(( 10#$( date +'%H%M' ) ))
if (( ( local_time >=    1430 && local_time <=    2230 ) ||
      ( local_time >= 10#0300 && local_time <= 10#0400 )    ))
then
  echo 'pass'
else
  echo 'skip'
fi
</code>```

Numbers that start with a zero are interpreted as octal.

Also, any number that start with 0 and contains an 8 or 9 will print an error.

Prefixing (10#) solves that.

Body:
I have the following wrapper script:

#!/bin/bash

$local_time=`date +%H%M`
if [ $local_time -ge 1430 ] && [ $local_time -le 2230 ] ||
   [ $local_time -ge 0300 ] && [ $local_time -le 0400 ]
then
   echo 'pass'
else
   echo 'skip'
fi

The idea being to create a wrapper script that runs a script between two disjoint time intervals. Each of the expressions being OR'd is evaluated correctly, however, when I OR both expressions, the test fails.

How do I fix this?

Body:
You have two problems

You don't prefix your variables with a $ when you assign to them, only when you expand them

You need to enforce operator precedence with parens ( )

Also, since you're already using bash, might as well use its better syntax with the (( )) construct that allows you to use the comparison operators < > == != and you can use $() for command substitution instead of the backticks/gravemarks

#!/bin/bash

local_time=$(( 10#$( date +'%H%M' ) ))
if (( ( local_time >=    1430 && local_time <=    2230 ) ||
      ( local_time >= 10#0300 && local_time <= 10#0400 )    ))
then
  echo 'pass'
else
  echo 'skip'
fi

Numbers that start with a zero are interpreted as octal.

Also, any number that start with 0 and contains an 8 or 9 will print an error.

Prefixing (10#) solves that.


问:
Responsive Design Mode vs Resizing browser window
I am trying to change things depending on resolution. So I use for exemple:

```<code>    @mediaquery only screen and (min-width:1125px) and (max-width:1280px) {
      flex-basis: 31.4rem;
    }
</code>```

It works perfectly in the responsive design mode of Mozilla Firefox, but when I am resizing the browser window directly it changes only from 1262px instead of 1280px and so between 1263px and 1280px it does not change. It actually does that for any media query (instead of 560px like in responsive mode it changes only from 540px for example).

Any idea where it could originate from ? How do I unify values from browser resizing and Responsive design mode ?

答: When you are testing the page with any responsive tool it's not counting the vertical scrollbar of the page. But when you actually resize the browser, it will give around 20px width difference, which is because of browser's default scrollbar width.

Body:
I am trying to change things depending on resolution. So I use for exemple:

    @mediaquery only screen and (min-width:1125px) and (max-width:1280px) {
      flex-basis: 31.4rem;
    }

It works perfectly in the responsive design mode of Mozilla Firefox, but when I am resizing the browser window directly it changes only from 1262px instead of 1280px and so between 1263px and 1280px it does not change. It actually does that for any media query (instead of 560px like in responsive mode it changes only from 540px for example).

Any idea where it could originate from ? How do I unify values from browser resizing and Responsive design mode ?


问:
Scanner detect end of file Java
I am trying to read in data from a text file and inserting it into an array, one line gap in the file means that a new array will be created. Two lines and the scanner should be closed. Here is the text file:

```<code>`Test
test
test
Telephone
Cardiology

Test Doctor 2
Test
20 Test
Telephone
Cardiology
`

  public Object[][] readData() throws FileNotFoundException{
  Scanner sc = new Scanner(new File("DoctorRecordsFile.txt"));
  String line;
  int emptyFile = 0 ;

  int i = 0;
  int x = 0;
  String[][] doctor = new String[100][5];
  while (emptyFile <= 1){
  line = sc.nextLine() ;

  if ((!line.isEmpty())){
        doctor[i][x] = line;
        System.out.println(doctor[i][x]);

        x++;
        emptyFile = 0;
  }
  else{
      System.out.println("PRE call emptyFile: " + emptyFile);
       emptyFile++;
      System.out.println("Post call emptyFile: " + emptyFile);
    if(emptyFile >= 2){
       sc.close();
    }
    else{
       i++;
       x = 0;
    }
    }
  }
  return new Object[][]{doctor[0]};
</code>```

The actual result I expect is that the scanner will close and stop reading in data, here are my console errors:

```<code>at java.util.Scanner.nextLine(Scanner.java:1540)
    at medicalsystem.ReadInDoctors.readData(ReadInDoctors.java:35)
    at medicalsystem.MainMenu.View_Doctor_ButtonActionPerformed(MainMenu.java:193)
</code>```

答:
Looking for this?
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()

It should be included in your while statement. This way you would not need the emptyFilevariable.

Title: Scanner detect end of file Java

Body:
I am trying to read in data from a text file and inserting it into an array, one line gap in the file means that a new array will be created. Two lines and the scanner should be closed. Here is the text file:

`Test
test
test
Telephone
Cardiology

Test Doctor 2
Test
20 Test
Telephone
Cardiology
`

  public Object[][] readData() throws FileNotFoundException{
  Scanner sc = new Scanner(new File("DoctorRecordsFile.txt"));
  String line;
  int emptyFile = 0 ;

  int i = 0;
  int x = 0;
  String[][] doctor = new String[100][5];
  while (emptyFile <= 1){
  line = sc.nextLine() ;

  if ((!line.isEmpty())){
        doctor[i][x] = line;
        System.out.println(doctor[i][x]);

        x++;
        emptyFile = 0;
  }
  else{
      System.out.println("PRE call emptyFile: " + emptyFile);
       emptyFile++;
      System.out.println("Post call emptyFile: " + emptyFile);
    if(emptyFile >= 2){
       sc.close();
    }
    else{
       i++;
       x = 0;
    }
    }
  }
  return new Object[][]{doctor[0]};

The actual result I expect is that the scanner will close and stop reading in data, here are my console errors:

at java.util.Scanner.nextLine(Scanner.java:1540)
    at medicalsystem.ReadInDoctors.readData(ReadInDoctors.java:35)
    at medicalsystem.MainMenu.View_Doctor_ButtonActionPerformed(MainMenu.java:193)


问:
Neo4j apoc functions doesn't exist
I have Neo4j Community version installed and I copied the apoc file in the plugins folder in my database. I configured the config file as well to allow all the apoc functions to work.

still RETURN apoc.version() or call apoc.help() functions doesn't exist but some of the apoc funcitons like apoc.load.json et cetera exist. What am i doing wrong??

```<code>dbms.security.allow_csv_import_from_file_urls=true

apoc.export.file.enabled=true
apoc.import.file.enabled=true
apoc.import.file.use_neo4j_config=true
dbms.security.procedures.unrestricted=apoc.*
dbms.security.procedures.white_list=apoc.load.*

dbms.security.procedures.unrestricted=apoc.*
dbms.security.procedures.unrestricted=apoc.cypher.*
dbms.security.procedures.unrestricted=apoc.trigger.*,apoc.meta.*
NEO4J_dbms_security_procedures_unrestricted=apoc.\\\*
dbms.security.procedures.whitelist=apoc.coll.*,apoc.load.*

# Require (or disable the requirement of) auth to access Neo4j
dbms.security.auth_enabled=true
dbms.security.procedures.whitelist=apoc.*
dbms.security.procedures.whitelist=apoc.coll.*,apoc.load.*
dbms.security.procedures.unrestricted=apoc.trigger.*,apoc.meta.*
NEO4J_dbms_security_procedures_unrestricted=apoc.\\\*

# With default configuration Neo4j only accepts local connections.
# To accept non-local connections, uncomment this line:
#dbms.connectors.default_listen_address=0.0.0.0

name    signature   description
"apoc.coll.partition"   "apoc.coll.partition(values :: LIST? OF ANY?, batchSize :: INTEGER?) :: (value :: LIST? OF ANY?)"   "apoc.coll.partition(list,batchSize)"
"apoc.coll.split"   "apoc.coll.split(values :: LIST? OF ANY?, value :: ANY?) :: (value :: LIST? OF ANY?)"   "apoc.coll.split(list,value) | splits collection on given values rows of lists, value itself will not be part of resulting lists"
"apoc.coll.zipToRows"   "apoc.coll.zipToRows(list1 :: LIST? OF ANY?, list2 :: LIST? OF ANY?) :: (value :: LIST? OF ANY?)"   "apoc.coll.zipToRows(list1,list2) - creates pairs like zip but emits one row per pair"
"apoc.load.csv" "apoc.load.csv(url :: STRING?, config :: MAP?) :: (lineNo :: INTEGER?, list :: LIST? OF ANY?, map :: MAP?)" "apoc.load.csv('url',{config}) YIELD lineNo, list, map - load CSV fom URL as stream of values,\n config contains any of: {skip:1,limit:5,header:false,sep:'TAB',ignore:['tmp'],arraySep:';',mapping:{years:{type:'int',arraySep:'-',array:false,name:'age',ignore:false}}"
"apoc.load.driver"  "apoc.load.driver(driverClass :: STRING?) :: VOID"  "apoc.load.driver('org.apache.derby.jdbc.EmbeddedDriver') register JDBC driver of source database"
"apoc.load.jdbc"    "apoc.load.jdbc(jdbc :: STRING?, tableOrSql :: STRING?, params = [] :: LIST? OF ANY?) :: (row :: MAP?)" "apoc.load.jdbc('key or url','table or statement') YIELD row - load from relational database, from a full table or a sql statement"
"apoc.load.jdbcParams"  "apoc.load.jdbcParams(jdbc :: STRING?, sql :: STRING?, params :: LIST? OF ANY?) :: (row :: MAP?)"   "deprecated - please use: apoc.load.jdbc('key or url','statement',[params]) YIELD row - load from relational database, from a sql statement with parameters"
"apoc.load.jdbcUpdate"  "apoc.load.jdbcUpdate(jdbc :: STRING?, query :: STRING?, params = [] :: LIST? OF ANY?) :: (row :: MAP?)"    "apoc.load.jdbcUpdate('key or url','statement',[params]) YIELD row - update relational database, from a SQL statement with optional parameters"
"apoc.load.json"    "apoc.load.json(url :: STRING?, path = :: STRING?, config = {} :: MAP?) :: (value :: MAP?)" "apoc.load.json('url',path, config) YIELD value - import JSON as stream of values if the JSON was an array or a single value if it was a map"
"apoc.load.jsonArray"   "apoc.load.jsonArray(url :: STRING?, path = :: STRING?) :: (value :: ANY?)" "apoc.load.jsonArray('url') YIELD value - load array from JSON URL (e.g. web-api) to import JSON as stream of values"
"apoc.load.jsonParams"  "apoc.load.jsonParams(url :: STRING?, headers :: MAP?, payload :: STRING?, path = :: STRING?, config = {} :: MAP?) :: (value :: MAP?)"  "apoc.load.jsonParams('url',{header:value},payload, config) YIELD value - load from JSON URL (e.g. web-api) while sending headers / payload to import JSON as stream of values if the JSON was an array or a single value if it was a map"
"apoc.load.ldap"    "apoc.load.ldap(connection :: ANY?, search :: MAP?) :: (entry :: MAP?)" "apoc.load.ldap(\"key\" or {connectionMap},{searchMap}) Load entries from an ldap source (yield entry)"
"apoc.load.xml" "apoc.load.xml(url :: STRING?, path = / :: STRING?, config = {} :: MAP?, simple = false :: BOOLEAN?) :: (value :: MAP?)"    "apoc.load.xml('http://example.com/test.xml', 'xPath',config, false) YIELD value as doc CREATE (p:Person) SET p.name = doc.name load from XML URL (e.g. web-api) to import XML as single nested map with attributes and _type, _text and _childrenx fields."
"apoc.load.xmlSimple"   "apoc.load.xmlSimple(url :: STRING?) :: (value :: MAP?)"    "apoc.load.xmlSimple('http://example.com/test.xml') YIELD value as doc CREATE (p:Person) SET p.name = doc.name load from XML URL (e.g. web-api) to import XML as single nested map with attributes and _type, _text and _children fields. This method does intentionally not work with XML mixed content."
</code>```

答:
Ah found it.

when I copied the jar file I removed all the procedures below

```<code># Require (or disable the requirement of) auth to access Neo4j
dbms.security.procedures.whitelist=apoc.*
dbms.security.procedures.whitelist=apoc.coll.*,apoc.load.*
dbms.security.procedures.unrestricted=apoc.trigger.*,apoc.meta.*
NEO4J_dbms_security_procedures_unrestricted=apoc.\\\*
</code>```

and pasted only this

```<code>dbms.security.procedures.unrestricted=apoc.*
</code>```

Title: Neo4j apoc functions doesn't exist

Body:
I have Neo4j Community version installed and I copied the apoc file in the plugins folder in my database. I configured the config file as well to allow all the apoc functions to work.

still RETURN apoc.version() or call apoc.help() functions doesn't exist but some of the apoc funcitons like apoc.load.json et cetera exist. What am i doing wrong??

dbms.security.allow_csv_import_from_file_urls=true

apoc.export.file.enabled=true
apoc.import.file.enabled=true
apoc.import.file.use_neo4j_config=true
dbms.security.procedures.unrestricted=apoc.*
dbms.security.procedures.white_list=apoc.load.*

dbms.security.procedures.unrestricted=apoc.*
dbms.security.procedures.unrestricted=apoc.cypher.*
dbms.security.procedures.unrestricted=apoc.trigger.*,apoc.meta.*
NEO4J_dbms_security_procedures_unrestricted=apoc.\\\*
dbms.security.procedures.whitelist=apoc.coll.*,apoc.load.*

# Require (or disable the requirement of) auth to access Neo4j
dbms.security.auth_enabled=true
dbms.security.procedures.whitelist=apoc.*
dbms.security.procedures.whitelist=apoc.coll.*,apoc.load.*
dbms.security.procedures.unrestricted=apoc.trigger.*,apoc.meta.*
NEO4J_dbms_security_procedures_unrestricted=apoc.\\\*

# With default configuration Neo4j only accepts local connections.
# To accept non-local connections, uncomment this line:
#dbms.connectors.default_listen_address=0.0.0.0

name    signature   description
"apoc.coll.partition"   "apoc.coll.partition(values :: LIST? OF ANY?, batchSize :: INTEGER?) :: (value :: LIST? OF ANY?)"   "apoc.coll.partition(list,batchSize)"
"apoc.coll.split"   "apoc.coll.split(values :: LIST? OF ANY?, value :: ANY?) :: (value :: LIST? OF ANY?)"   "apoc.coll.split(list,value) | splits collection on given values rows of lists, value itself will not be part of resulting lists"
"apoc.coll.zipToRows"   "apoc.coll.zipToRows(list1 :: LIST? OF ANY?, list2 :: LIST? OF ANY?) :: (value :: LIST? OF ANY?)"   "apoc.coll.zipToRows(list1,list2) - creates pairs like zip but emits one row per pair"
"apoc.load.csv" "apoc.load.csv(url :: STRING?, config :: MAP?) :: (lineNo :: INTEGER?, list :: LIST? OF ANY?, map :: MAP?)" "apoc.load.csv('url',{config}) YIELD lineNo, list, map - load CSV fom URL as stream of values,\n config contains any of: {skip:1,limit:5,header:false,sep:'TAB',ignore:['tmp'],arraySep:';',mapping:{years:{type:'int',arraySep:'-',array:false,name:'age',ignore:false}}"
"apoc.load.driver"  "apoc.load.driver(driverClass :: STRING?) :: VOID"  "apoc.load.driver('org.apache.derby.jdbc.EmbeddedDriver') register JDBC driver of source database"
"apoc.load.jdbc"    "apoc.load.jdbc(jdbc :: STRING?, tableOrSql :: STRING?, params = [] :: LIST? OF ANY?) :: (row :: MAP?)" "apoc.load.jdbc('key or url','table or statement') YIELD row - load from relational database, from a full table or a sql statement"
"apoc.load.jdbcParams"  "apoc.load.jdbcParams(jdbc :: STRING?, sql :: STRING?, params :: LIST? OF ANY?) :: (row :: MAP?)"   "deprecated - please use: apoc.load.jdbc('key or url','statement',[params]) YIELD row - load from relational database, from a sql statement with parameters"
"apoc.load.jdbcUpdate"  "apoc.load.jdbcUpdate(jdbc :: STRING?, query :: STRING?, params = [] :: LIST? OF ANY?) :: (row :: MAP?)"    "apoc.load.jdbcUpdate('key or url','statement',[params]) YIELD row - update relational database, from a SQL statement with optional parameters"
"apoc.load.json"    "apoc.load.json(url :: STRING?, path = :: STRING?, config = {} :: MAP?) :: (value :: MAP?)" "apoc.load.json('url',path, config) YIELD value - import JSON as stream of values if the JSON was an array or a single value if it was a map"
"apoc.load.jsonArray"   "apoc.load.jsonArray(url :: STRING?, path = :: STRING?) :: (value :: ANY?)" "apoc.load.jsonArray('url') YIELD value - load array from JSON URL (e.g. web-api) to import JSON as stream of values"
"apoc.load.jsonParams"  "apoc.load.jsonParams(url :: STRING?, headers :: MAP?, payload :: STRING?, path = :: STRING?, config = {} :: MAP?) :: (value :: MAP?)"  "apoc.load.jsonParams('url',{header:value},payload, config) YIELD value - load from JSON URL (e.g. web-api) while sending headers / payload to import JSON as stream of values if the JSON was an array or a single value if it was a map"
"apoc.load.ldap"    "apoc.load.ldap(connection :: ANY?, search :: MAP?) :: (entry :: MAP?)" "apoc.load.ldap(\"key\" or {connectionMap},{searchMap}) Load entries from an ldap source (yield entry)"
"apoc.load.xml" "apoc.load.xml(url :: STRING?, path = / :: STRING?, config = {} :: MAP?, simple = false :: BOOLEAN?) :: (value :: MAP?)"    "apoc.load.xml('http://example.com/test.xml', 'xPath',config, false) YIELD value as doc CREATE (p:Person) SET p.name = doc.name load from XML URL (e.g. web-api) to import XML as single nested map with attributes and _type, _text and _childrenx fields."
"apoc.load.xmlSimple"   "apoc.load.xmlSimple(url :: STRING?) :: (value :: MAP?)"    "apoc.load.xmlSimple('http://example.com/test.xml') YIELD value as doc CREATE (p:Person) SET p.name = doc.name load from XML URL (e.g. web-api) to import XML as single nested map with attributes and _type, _text and _children fields. This method does intentionally not work with XML mixed content."

Body:
Ah found it.

when I copied the jar file I removed all the procedures below

# Require (or disable the requirement of) auth to access Neo4j
dbms.security.procedures.whitelist=apoc.*
dbms.security.procedures.whitelist=apoc.coll.*,apoc.load.*
dbms.security.procedures.unrestricted=apoc.trigger.*,apoc.meta.*
NEO4J_dbms_security_procedures_unrestricted=apoc.\\\*

and pasted only this

dbms.security.procedures.unrestricted=apoc.*


问:
Custom styling pandas dataframe
The documentation shows an example, on how to change the font color of an element conditional on value, which works fine as expected:

```<code>def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)
</code>```

My question is how to implement a function that instead applies the font color change in the whole row?

答:
You working with DataFrame, so it set row to red if at least one value is less as 0 in row:

```<code>def color_negative_red(x):
    c1 = 'background-color: red'
    c2 = 'background-color: black'

    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    df1 = df1.where((x > 0).all(axis=1), c1)
    return df1

df.style.apply(color_negative_red, axis=None)
</code>```

Title: Custom styling pandas dataframe

Body:
The documentation shows an example, on how to change the font color of an element conditional on value, which works fine as expected:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)

My question is how to implement a function that instead applies the font color change in the whole row?

Body:
You working with DataFrame, so it set row to red if at least one value is less as 0 in row:

def color_negative_red(x):
    c1 = 'background-color: red'
    c2 = 'background-color: black'

    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    df1 = df1.where((x > 0).all(axis=1), c1)
    return df1

df.style.apply(color_negative_red, axis=None)


问:
FlatList numColumns doesn't appear to be working correctly?
I'm trying to use a FlatList to show a bunch of user avatars to someone in a grid format, but it ends up looking very strange and I can't seem to figure out how to fix it.

Here's what it looks like

Here's what my FlatList code looks like:

```<code><FlatList
style={{flex: 1}}
data={this.props.usersList}
horizontal={false}
numColumns={3}
columnWrapperStyle={{ marginTop: 10 }}
renderItem={({ item }) => this.renderItem(item)}
keyExtractor={this._keyExtractor}/>
</code>```

and here's what the component looks like for renderItem:

```<code>class UserButton extends React.Component {
render() {
    const { item, onPress } = this.props;
    return (
        <TouchableOpacity style={styles.button} onPress={onPress}>
            <Image
                source={(item.avatar) ? { uri: item.avatar } : require('../assets/images/userplaceholder.png')}
                resizeMode='cover'
                style={styles.imageStyle}
            />
        </TouchableOpacity>
    )
}

const styles = {
    button: {
        height: 100,
        width: 100,
        borderColor: '#aaa',
        backgroundColor: '#aaa',
        borderWidth: 2,
        borderRadius: 50,
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 5,
    },
    imageStyle: {
        height: 96,
        width: 96,
        alignSelf: 'center',
        borderRadius: 48,
        marginTop: (Platform.OS == 'android') ? 0 : 0.4
    }
}

export default UserButton;
</code>```

Anyone have any ideas?

答:
You can take width from Dimensions and set that width for items of your flatlist.</p>

```<code>const {width} = Dimensions.get('window');
const itemWidth = (width) / 4;
</code>```

Body:
I'm trying to use a FlatList to show a bunch of user avatars to someone in a grid format, but it ends up looking very strange and I can't seem to figure out how to fix it.

Here's what it looks like

Here's what my FlatList code looks like:

<FlatList
style={{flex: 1}}
data={this.props.usersList}
horizontal={false}
numColumns={3}
columnWrapperStyle={{ marginTop: 10 }}
renderItem={({ item }) => this.renderItem(item)}
keyExtractor={this._keyExtractor}/>

and here's what the component looks like for renderItem:

class UserButton extends React.Component {
render() {
    const { item, onPress } = this.props;
    return (
        <TouchableOpacity style={styles.button} onPress={onPress}>
            <Image
                source={(item.avatar) ? { uri: item.avatar } : require('../assets/images/userplaceholder.png')}
                resizeMode='cover'
                style={styles.imageStyle}
            />
        </TouchableOpacity>
    )
}

const styles = {
    button: {
        height: 100,
        width: 100,
        borderColor: '#aaa',
        backgroundColor: '#aaa',
        borderWidth: 2,
        borderRadius: 50,
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 5,
    },
    imageStyle: {
        height: 96,
        width: 96,
        alignSelf: 'center',
        borderRadius: 48,
        marginTop: (Platform.OS == 'android') ? 0 : 0.4
    }
}

export default UserButton;

Anyone have any ideas?

Body:
You can take width from Dimensions and set that width for items of your flatlist.

const {width} = Dimensions.get('window');
const itemWidth = (width) / 4;


问:
Are immutable objects good practice?
Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety)
Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them?
Or is it not worth the inconvenience you have to create them?

答:
This is going to be more of an opinion type answer but...

I find that the ease of understanding a program, i.e. maintaining and debugging said application, is inversly proportional to the amount of stateful transitions that occur during the processing of each component.  The less state I need to cart around in my head, the more focus I can pay attention to the logic within the algorithms as it is written.

Title: Are immutable objects good practice?


问:
UITextView don't show text
I have a TextView in my xib file.

After I assign text for it, it doesn't show the text till I double click it, and actually change the selection of the text:

Before double click:

After double click:

After changing selection size:

Do you have any idea, how to show text from the beginning?

Thanks

答: In my case text was long and it was trimming from end. I was setting text first then font and colour. I Set font first then text. It works for me.</p>

Title: UITextView don't show text


问:
How to update the GridView after binded itemsource is updated in UWP?
I need to refresh the GridView when values changed in the List collection. Actually I have bind the List as itemsource for the GridView. Where i have changed the List values but which could not relected in the GridView. How to acheive this in UWP?</p>

答:
use ObserableListCollection

and

```<code>yourGridviewOrListview1.ItemsSource = null;
yourGridviewOrListview1.ItemsSource = SingletonClass.YourObList;
</code>```

Body:
use ObserableListCollection

and

yourGridviewOrListview1.ItemsSource = null;
yourGridviewOrListview1.ItemsSource = SingletonClass.YourObList;


问:
How to call JSP within a folder from servlet that is also within a folder
I have a project in Netbeans. In "Source Packages" I have a servlet, myServlet.java. But it is inside folders. Its com.login.controller. In "Web Pages" I have 2 JSPs, login.jsp and home.jsp. login.jsp is inside of folder "jsp/login/login.jsp" while home.jsp is at "jsp/home/home.jsp".

Now my question is what is the best way of invoking JSP page from servlet when using getRequestDispatcher? In my login.jsp when I clicked login button it call myServlet.java and then it will process if the inputs are valid it should then directed in home.jsp using getRequestDispatcher. What Should I enter in its parameter as path? What I thought are the ff:

```<code>getRequestDispatcher("home.jsp");
getRequestDispatcher("jsp/home/home.jsp");
getRequestDispatcher("../../../jsp/home/home.jsp"); //Getting back of
</code>```

directory 3x because I thought my servlet is inside 3 folders that's why.

But all of these 3 did not work. What should I do? I don't know. Please help me. Thanks in advance.

答:
Make use of contextpath, it will give you root path.

```<code>request.getContextPath()
</code>```

So if you want to access home.jsp, navigate from Web-Content folder i.e

```<code>getRequestDispatcher(request.getContextPath()+"/jsp/home/home.jsp");
</code>```

Similarly, when you want to send request to Servlet, you can use

```<code> getRequestDispatcher(request.getContextPath()+"/myServlet.java");
</code>```

Body:
I have a project in Netbeans. In "Source Packages" I have a servlet, myServlet.java. But it is inside folders. Its com.login.controller. In "Web Pages" I have 2 JSPs, login.jsp and home.jsp. login.jsp is inside of folder "jsp/login/login.jsp" while home.jsp is at "jsp/home/home.jsp".

Now my question is what is the best way of invoking JSP page from servlet when using getRequestDispatcher? In my login.jsp when I clicked login button it call myServlet.java and then it will process if the inputs are valid it should then directed in home.jsp using getRequestDispatcher. What Should I enter in its parameter as path? What I thought are the ff:

getRequestDispatcher("home.jsp");
getRequestDispatcher("jsp/home/home.jsp");
getRequestDispatcher("../../../jsp/home/home.jsp"); //Getting back of

directory 3x because I thought my servlet is inside 3 folders that's why.

But all of these 3 did not work. What should I do? I don't know. Please help me. Thanks in advance.

Body:
Make use of contextpath, it will give you root path.

request.getContextPath()

So if you want to access home.jsp, navigate from Web-Content folder i.e

getRequestDispatcher(request.getContextPath()+"/jsp/home/home.jsp");

Similarly, when you want to send request to Servlet, you can use

 getRequestDispatcher(request.getContextPath()+"/myServlet.java");