问:
Erlang: whether two lists have a common element
```<code>a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],
</code>```

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

答:
You can make fast solution using erlang:--/2 operator:

```<code>has_common_element(A, B) when length(B) > length(A) ->
    has_common_element(B, A); % not necessary optimization but helps for very uneven sets
has_common_element(A, B) ->
    A =/= A -- B.
</code>```

It will be O(N*M) in older versions but since OTP21 I think it becomes O((N+M)*logM) (I can't find relevant release note just now). Benchmark for yourself in the version you are using and choose properly.

Anyway You can make still pretty fast O((N+M)*logM) solution using maps:

```<code>has_common_element(A, B) when length(B) > length(A) ->
    has_common_element(B, A); % not necessary optimization but helps for very uneven sets
has_common_element(A, B) ->
    M = maps:from_list([{X,[]} || X <- B]),
    any_in_map(M, A).

any_in_map(_, []) -> false;
any_in_map(M, [H|T]) ->
    maps:is_key(H, M) orelse any_in_map(M, T).
</code>```

And there is a nasty slightly faster version of previous using process_dictionary. You can use it directly when you have good control over list elements and process_dictionary doesn't bother you (usually not good idea in OTP process).

```<code>has_common_element_dirty(A, B) when length(B) > length(A) ->
    has_common_element_dirty(B, A); % not necessary optimization but helps for very uneven sets
has_common_element_dirty(A, B) ->
    [put(X, []) || X <- B],
    any_in_dict(A).

any_in_dict([]) -> false;
any_in_dict([H|T]) ->
    [] =:= get(H) orelse any_in_dict(T).
</code>```

You can wrap it in the linked process and make it safe:

```<code>has_common_element(A, B) ->
    Self = self(),
    Ref = make_ref(),
    Pid = spawn_link(fun() -> Self ! {Ref, has_common_element_dirty(A, B)} end),
    receive {Ref, Result} -> Result end.
</code>```

Benchmark for your application and list sizes and choose accordingly because all those solutions have different GC and raw performance characteristics. Usually, the first one should be sufficient.

```<code>Erlang/OTP 22 [erts-10.4] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Eshell V10.4  (abort with ^G)
1> Size=100000, A = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)], B = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)], C = [rand:uniform(Size*10000)+Size*10000 || _ <- lists:duplicate(Size, 0)], ok.
ok
2> timer:tc(fun() -> A =/= A -- B end).
{77943,true}
3> timer:tc(fun() -> A =/= A -- C end).
{44325,false}
</code>```

It's less than 100ms for comparing two 100k lists. It's on par or better than the best (s2) from Pascal's solutions. Note OTP22 version.

Body:
a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

Body:
You can make fast solution using erlang:--/2 operator:

has_common_element(A, B) when length(B) > length(A) ->
    has_common_element(B, A); % not necessary optimization but helps for very uneven sets
has_common_element(A, B) ->
    A =/= A -- B.

It will be O(N*M) in older versions but since OTP21 I think it becomes O((N+M)*logM) (I can't find relevant release note just now). Benchmark for yourself in the version you are using and choose properly.

Anyway You can make still pretty fast O((N+M)*logM) solution using maps:

has_common_element(A, B) when length(B) > length(A) ->
    has_common_element(B, A); % not necessary optimization but helps for very uneven sets
has_common_element(A, B) ->
    M = maps:from_list([{X,[]} || X <- B]),
    any_in_map(M, A).

any_in_map(_, []) -> false;
any_in_map(M, [H|T]) ->
    maps:is_key(H, M) orelse any_in_map(M, T).

And there is a nasty slightly faster version of previous using process_dictionary. You can use it directly when you have good control over list elements and process_dictionary doesn't bother you (usually not good idea in OTP process).

has_common_element_dirty(A, B) when length(B) > length(A) ->
    has_common_element_dirty(B, A); % not necessary optimization but helps for very uneven sets
has_common_element_dirty(A, B) ->
    [put(X, []) || X <- B],
    any_in_dict(A).

any_in_dict([]) -> false;
any_in_dict([H|T]) ->
    [] =:= get(H) orelse any_in_dict(T).

You can wrap it in the linked process and make it safe:

has_common_element(A, B) ->
    Self = self(),
    Ref = make_ref(),
    Pid = spawn_link(fun() -> Self ! {Ref, has_common_element_dirty(A, B)} end),
    receive {Ref, Result} -> Result end.

Benchmark for your application and list sizes and choose accordingly because all those solutions have different GC and raw performance characteristics. Usually, the first one should be sufficient.

Erlang/OTP 22 [erts-10.4] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Eshell V10.4  (abort with ^G)
1> Size=100000, A = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)], B = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)], C = [rand:uniform(Size*10000)+Size*10000 || _ <- lists:duplicate(Size, 0)], ok.
ok
2> timer:tc(fun() -> A =/= A -- B end).
{77943,true}
3> timer:tc(fun() -> A =/= A -- C end).
{44325,false}

It's less than 100ms for comparing two 100k lists. It's on par or better than the best (s2) from Pascal's solutions. Note OTP22 version.


来源: stackexchange

问:
Why is there a difference between the views I've included as images?
(I have edited the question to describe it more clearly and short.)

Why there is a key as 20.42 when expending but it not presented in the folded view(in the red circle).
See screenshot below, It's weird that there is one index of the array is 20.42 in expended view.

It happened on this situation:

I use push method to add element to an empty array.

Then console.log the array.

Did some assign 20.42 to the array by mistake.

答:
JavaScript arrays are objects that assign special behavior to properties whose names are array indexes (strings that convert to integers in a given range¹), have a special length property, and are backed by Array.prototype. They're still objects, which means they can have properties whose entries aren't array indexes, too:

const a = [];
a[0] = "zero, normal array entry";
a[20.42] = "20.42, normal object property, not an array entry";
console.log(a);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Look in the real console</code>```

Both 0 and 20.42 above are (in specification terms) converted to string and used as property names. (The JavaScript engine can and will optimize that when you're dealing with normal array indexes.)

So somewhere, your code is assigning a BigNumber to the property name "20.42".

¹ From the spec:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253 - 1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232 - 1.

ContentLicense: CC BY-SA 4.0

Body:
JavaScript arrays are objects that assign special behavior to properties whose names are array indexes (strings that convert to integers in a given range¹), have a special length property, and are backed by Array.prototype. They're still objects, which means they can have properties whose entries aren't array indexes, too:

const a = [];
a[0] = "zero, normal array entry";
a[20.42] = "20.42, normal object property, not an array entry";
console.log(a);

Look in the real console

Both 0 and 20.42 above are (in specification terms) converted to string and used as property names. (The JavaScript engine can and will optimize that when you're dealing with normal array indexes.)

So somewhere, your code is assigning a BigNumber to the property name "20.42".

¹ From the spec:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253 - 1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232 - 1.


问:
How to create DICOM MWL query using dcm4che3 in Java?
I am building a DICOM client using the dcm4che3 library and it's a bit confusing to me how I'm supposed to create the dicom query. I'm calling the CFIND method on the Association class.

I've figured out how to create a basic query (eg search by PatientID) as follows:

```<code>Attributes query = new Attributes();
query.setString(Tag.PatientID, VR.LO, "12345");
</code>```

So far so good.

But when I want to query using something like ScheduledProcedureStepStartDate, I have to create a Sequence with a sub query something like this:

```<code>Attributes query = new Attributes();
Sequence sequence = query.newSequence(Tag.ScheduledProcedureStepSequence, 1);
Attributes subQuery = new Attributes();
subQuery.setDate(Tag.ScheduledProcedureStepStartDate, VR.DA, date);
sequence.add(subQuery);
</code>```

I don't know the DICOM format in detail. So I figured this out quite by trial and error and using another DICOM client emulator and intercepting it's queries to try and figure out how it works.

So from this I have 3 questions:

How can I query for ScheduledProcedureStepStartDate between two dates (i.e. using a From and To date).

When creating the query, is it possible to have the dcm4che3 library figure out how to make the Sequences, so I can just specify the Tag, VR and value I want in the query?

When I query using the Sequence elements (eg ScheduledProcedureStepSequence -> Modality) it doesn't seem to work. Is there any trick to make this work?

答:
How can I query for ScheduledProcedureStepStartDate between two dates (i.e. using a From and To date).

The Scheduled Procedure Step Start Date (0040,0002) element is part of Scheduled Procedure Step Sequence (0040,0100). This supports Combined Range Matching.

Matching keys for Date and Time are combined. For example, a Study Date of "20060705-20060707" and a Study Time of "1000-1800" will match the time period of July 5, 10am until July 7, 6pm, rather than the three time periods of 10am until 6pm on each of July 5, July 6 and July 7.

So, you can specify two dates separated by dash (-) to search between two dates. Example is given in quote above.

When creating the query, is it possible to have the dcm4che3 library figure out how to make the Sequences, so I can just specify the Tag, VR and value I want in the query?

DICOM element hierarchy is very simple; caller can easily create sequences as needed. In majority of the cases, MWL query contain only one sequence that you mentioned.

What you are asking needs a wrapper over basic Data Set class. Most widely used tool kits does not support wrapper over DICOM Data Set to simplify sequence handling; I know few does. I am not expert in the toolkit; but AFAIK, such wrapper does not exist for dcm4che. You have to create and manage sequence elements yourself.

When I query using the Sequence elements (eg ScheduledProcedureStepSequence -> Modality) it doesn't seem to work. Is there any trick to make this work?

This is not clear; "it doesn't seem to work" does not explain it. Sequence element contains an Item. The Item contains further elements. Each Item can be treated as Data Set again.

Following is how your query should something look like:

The article from Roni may be helpful to you. The source code there does not use your toolkit; hope you will get an idea.

Body:
I am building a DICOM client using the dcm4che3 library and it's a bit confusing to me how I'm supposed to create the dicom query. I'm calling the CFIND method on the Association class.

I've figured out how to create a basic query (eg search by PatientID) as follows:

Attributes query = new Attributes();
query.setString(Tag.PatientID, VR.LO, "12345");

So far so good.

But when I want to query using something like ScheduledProcedureStepStartDate, I have to create a Sequence with a sub query something like this:

Attributes query = new Attributes();
Sequence sequence = query.newSequence(Tag.ScheduledProcedureStepSequence, 1);
Attributes subQuery = new Attributes();
subQuery.setDate(Tag.ScheduledProcedureStepStartDate, VR.DA, date);
sequence.add(subQuery);

I don't know the DICOM format in detail. So I figured this out quite by trial and error and using another DICOM client emulator and intercepting it's queries to try and figure out how it works.

So from this I have 3 questions:

How can I query for ScheduledProcedureStepStartDate between two dates (i.e. using a From and To date).

When creating the query, is it possible to have the dcm4che3 library figure out how to make the Sequences, so I can just specify the Tag, VR and value I want in the query?

When I query using the Sequence elements (eg ScheduledProcedureStepSequence -> Modality) it doesn't seem to work. Is there any trick to make this work?


问:
Why a:active pseudo class does not working
Am using css for some site. I noticed that the a:active style definition in my css file does not work at all. I was told by someone that I have to put the definitions in this order

```<code>a:link {...}
a:visited {...}
a:hover {...}
a:active {...}
</code>```

I have done so but it's still not working. Please could someone tell me why it is not working and a possible workaround. Thanks

答:
Here is a working example:

http://jsfiddle.net/BMHUz/

Click and hold on the anchor tag and you will see it turn orange.

ContentLicense: CC BY-SA 3.0

Body:
Am using css for some site. I noticed that the a:active style definition in my css file does not work at all. I was told by someone that I have to put the definitions in this order

a:link {...}
a:visited {...}
a:hover {...}
a:active {...}

I have done so but it's still not working. Please could someone tell me why it is not working and a possible workaround. Thanks


问:
CV2 starts taking emty images after some time
i am new to python and i have a small problem. I am supposed to take images every 10 seconds with a webcam over a long period of time. My code works for about 5 hours or 1800 pictures, then all of a sudden the pictures i am saving are emty. I don't know whats causing the error and i don't get an error message, the skript keeps running.

I am using spyder with python 2.7. When i restart the kernel, my skript works again for a few hours. Here is my code:

```<code>import cv2
import time
import datetime
import os
data_path = 'V:\\Database\\Pictures'
try:
  while True:

       cam = cv2.VideoCapture(0)
       cam.set(3,1280) #set height
       cam.set(4,720) #set width
       s, im = cam.read() # captures image
    # Write date and time to image

       date_string = time.strftime("%Y-%m-%d %H:%M:%S")
       font                   = cv2.FONT_HERSHEY_SIMPLEX
       bottomLeftCornerOfText = (10,710)
       fontScale              = 1
       fontColor              = (255,255,255)
       lineType               = 2

       cv2.putText(im,date_string,
           bottomLeftCornerOfText,
           font,
           fontScale,
           fontColor,
           lineType)

       temp = datetime.datetime.fromtimestamp(time.time())
       year = temp.year
       month = temp.month
       day = temp.day
       hour = temp.hour
       minute = temp.minute
       second = temp.second

       imagename = year+'-'+month+'-'+day+'_'+hour+'-'+minute+'-   '+second+'.jpg'

         # writes image  to disk
       cv2.imwrite(os.path.join(data_path,imagename),im)
       cam.release()
       time.sleep(10)

finally:
  cam.release()
</code>```

Is this a problem with my memory? Size of one picture is 261KB.

答:
Hard disk full? Not sure if this solves the problem but you should re-arrange your code. No need to re-initialize the camera every time:</p>

```<code>import cv2
import time
import datetime
import os
data_path = 'V:\\Database\\Pictures'

cam = cv2.VideoCapture(0)
cam.set(3,1280) #set height
cam.set(4,720) #set width

font                   = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,710)
fontScale              = 1
fontColor              = (255,255,255)
lineType               = 2

while True:

    try:
        s, im = cam.read() # captures image
    except:
        # something here
        pass

    now = datetime.datetime.now()

    date_string = now.strftime("%Y-%m-%d %H:%M:%S")

    cv2.putText(im,date_string,
        bottomLeftCornerOfText,
        font,
        fontScale,
        fontColor,
        lineType)

    imagename = now.strftime("%Y-%m-%d_%H-%M-%S") + '.jpg'

    # writes image  to disk
    cv2.imwrite(os.path.join(data_path,imagename),im)
    time.sleep(10)

cam.release()
</code>```

Body:
i am new to python and i have a small problem. I am supposed to take images every 10 seconds with a webcam over a long period of time. My code works for about 5 hours or 1800 pictures, then all of a sudden the pictures i am saving are emty. I don't know whats causing the error and i don't get an error message, the skript keeps running.

I am using spyder with python 2.7. When i restart the kernel, my skript works again for a few hours. Here is my code:

import cv2
import time
import datetime
import os
data_path = 'V:\\Database\\Pictures'
try:
  while True:

       cam = cv2.VideoCapture(0)
       cam.set(3,1280) #set height
       cam.set(4,720) #set width
       s, im = cam.read() # captures image
    # Write date and time to image

       date_string = time.strftime("%Y-%m-%d %H:%M:%S")
       font                   = cv2.FONT_HERSHEY_SIMPLEX
       bottomLeftCornerOfText = (10,710)
       fontScale              = 1
       fontColor              = (255,255,255)
       lineType               = 2

       cv2.putText(im,date_string,
           bottomLeftCornerOfText,
           font,
           fontScale,
           fontColor,
           lineType)

       temp = datetime.datetime.fromtimestamp(time.time())
       year = temp.year
       month = temp.month
       day = temp.day
       hour = temp.hour
       minute = temp.minute
       second = temp.second

       imagename = year+'-'+month+'-'+day+'_'+hour+'-'+minute+'-   '+second+'.jpg'

         # writes image  to disk
       cv2.imwrite(os.path.join(data_path,imagename),im)
       cam.release()
       time.sleep(10)

finally:
  cam.release()

Is this a problem with my memory? Size of one picture is 261KB.

Body:
Hard disk full? Not sure if this solves the problem but you should re-arrange your code. No need to re-initialize the camera every time:

import cv2
import time
import datetime
import os
data_path = 'V:\\Database\\Pictures'

cam = cv2.VideoCapture(0)
cam.set(3,1280) #set height
cam.set(4,720) #set width

font                   = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,710)
fontScale              = 1
fontColor              = (255,255,255)
lineType               = 2

while True:

    try:
        s, im = cam.read() # captures image
    except:
        # something here
        pass

    now = datetime.datetime.now()

    date_string = now.strftime("%Y-%m-%d %H:%M:%S")

    cv2.putText(im,date_string,
        bottomLeftCornerOfText,
        font,
        fontScale,
        fontColor,
        lineType)

    imagename = now.strftime("%Y-%m-%d_%H-%M-%S") + '.jpg'

    # writes image  to disk
    cv2.imwrite(os.path.join(data_path,imagename),im)
    time.sleep(10)

cam.release()


问:
RDBMS: Is there a performance hit for co-locating columns that are not usually queried together?
Example: We have columns id, A1, A2, A3, B1, B2, B3. The A columns are usually queried together, as are the B columns, but A are not usually queried at the same time as B.

Is there a performance hit for (1) storing all columns in one table, vs. (2) splitting one table for A columns and one table for B columns (which requires duplicating the id column)?

I am using Postgres.

答:
1) Yes: All columns in one table makes reading each row more expensive because there are fewer rows per page, therefore more pages need to be read - more I/O.

2) Yes: Two separate tables is slower when you do need both As and Bs as you would need to join them together.  This typically has more I/O.

Generally you're going to be trading off one for another.  If you're always going to be consuming or using a small, well-indexed set, it probably won't matter.  If you're going to trawl through a large number of rows, either because of no useful indexing or a large output, then you'd be better of measuring it with your specific scenarios than guessing or even applying rules of thumb.


问:
Type mismatch.Required: MutableList<out ExpandableGroup<Parcelable>>
I'm trying to do expandale recyclerview and I use thoughtbot/expandable-recycler-view, but I've problem with adapter. Maybe someone had similar problem and can help me to solve this problem

1) code of my Parent Class

```<code>/****** parent ******/
class Item(title: String?, items: MutableList<ItemDetail>?) :
ExpandableGroup<ItemDetail>(title, items)
</code>```

2)Child class (here I used parcelize. but now I use :Parcelable)

```<code> // @Parcelize
 // data class ItemDetail(
 // var i_size: String,
 // var i_qty: Int
 //): Parcelable
 class ItemDetail (val i_size: String, val i_qty: Int): Parcelable{
    constructor(parcel: Parcel):this(
     parcel.readString(),
     parcel.readInt()){

   }

   override fun writeToParcel(parcel: Parcel, flags: Int) {
      parcel.writeString(i_size)
      parcel.writeInt(i_qty)
   }

   override fun describeContents(): Int {
     return 0
    }

  companion object CREATOR : Parcelable.Creator<ItemDetail> {
     override fun createFromParcel(parcel: Parcel): ItemDetail {
       return ItemDetail(parcel)
     }

     override fun newArray(size: Int): Array<ItemDetail?> {
      return arrayOfNulls(size)
     }
 }
 }
</code>```

3) Fragment - Adapter

```<code>

    /**** fragment ****/
    val groups: MutableList<Item> = ArrayList<Item>()

    val childs : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs.add(ItemDetail("200x200",4))
    childs.add(ItemDetail("300x300",6))
    childs.add(ItemDetail("400x300",2))
    groups.add(Item("Item ISFAKHAN",childs))

    val childs2 : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs2.add(ItemDetail("200x200",42))
    childs2.add(ItemDetail("300x300",62))
    childs2.add(ItemDetail("400x300",22))
    groups.add(Item("Item DASTAN",childs2))
    /***  error ***/
    cAdapter = CartAdapter(groups)
    /*** Type mismatch.Required: MutableList<out ExpandableGroup<Parcelable>>? Found: MutableList<Item> ***/

      /****** adapter *****/
    class CartAdapter(groups: MutableList<out ExpandableGroup<Parcelable>>?) :
    ExpandableRecyclerViewAdapter<ItemVH, ItemDetailVH>(groups) {

}
</code>```

答:
SOLVED. just changed

```<code>CartAdapter(groups: MutableList<out ExpandableGroup<Parcelable>>?)
</code>```

to

```<code>CartAdapter(groups: List<out ExpandableGroup<*>>)
</code>```

Body:
I'm trying to do expandale recyclerview and I use thoughtbot/expandable-recycler-view, but I've problem with adapter. Maybe someone had similar problem and can help me to solve this problem

1) code of my Parent Class

/****** parent ******/
class Item(title: String?, items: MutableList<ItemDetail>?) :
ExpandableGroup<ItemDetail>(title, items)

2)Child class (here I used parcelize. but now I use :Parcelable)

 // @Parcelize
 // data class ItemDetail(
 // var i_size: String,
 // var i_qty: Int
 //): Parcelable
 class ItemDetail (val i_size: String, val i_qty: Int): Parcelable{
    constructor(parcel: Parcel):this(
     parcel.readString(),
     parcel.readInt()){

   }

   override fun writeToParcel(parcel: Parcel, flags: Int) {
      parcel.writeString(i_size)
      parcel.writeInt(i_qty)
   }

   override fun describeContents(): Int {
     return 0
    }

  companion object CREATOR : Parcelable.Creator<ItemDetail> {
     override fun createFromParcel(parcel: Parcel): ItemDetail {
       return ItemDetail(parcel)
     }

     override fun newArray(size: Int): Array<ItemDetail?> {
      return arrayOfNulls(size)
     }
 }
 }

3) Fragment - Adapter

    /**** fragment ****/
    val groups: MutableList<Item> = ArrayList<Item>()

    val childs : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs.add(ItemDetail("200x200",4))
    childs.add(ItemDetail("300x300",6))
    childs.add(ItemDetail("400x300",2))
    groups.add(Item("Item ISFAKHAN",childs))

    val childs2 : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs2.add(ItemDetail("200x200",42))
    childs2.add(ItemDetail("300x300",62))
    childs2.add(ItemDetail("400x300",22))
    groups.add(Item("Item DASTAN",childs2))
    /***  error ***/
    cAdapter = CartAdapter(groups)
    /*** Type mismatch.Required: MutableList<out ExpandableGroup<Parcelable>>? Found: MutableList<Item> ***/

      /****** adapter *****/
    class CartAdapter(groups: MutableList<out ExpandableGroup<Parcelable>>?) :
    ExpandableRecyclerViewAdapter<ItemVH, ItemDetailVH>(groups) {

}

Body:
SOLVED. just changed

CartAdapter(groups: MutableList<out ExpandableGroup<Parcelable>>?)

to

CartAdapter(groups: List<out ExpandableGroup<*>>)


问:
Run application after click on the Finish button (not after install)
I have a setup for installing my application, and I need to run the application after successfully installing. I used postinstall to do this.

but it shows a checkbox and the user can uncheck it. I need to run the application without asking because of it kinda service which needs to runs at startup. if the user unchecked it he needs to restart the PC to launch.

So I can use the Filename: "{app}\myapp.exe" code without any flags in the Run section to launch the application but the problem is, It runs immediately after installing not after the finish button clicked.

The first issue is my application has an instruction window. it shows up at the launch so the setup window goes to the back. And the second issue is my application does not allow terminating unless uninstall becouse it need to run in the background. Setup waiting to process end to finish.

Is there any way to run the application after the finish button click in inno setup?

答:
Simplifying the answer from Run Files and Programs according to custom checkboxes after clicking on Finish Button in Inno Setup, you can use a code like this:

[Code]

function NextButtonClick(CurPageID: Integer): Boolean;
var
  ResultCode: Integer;
  Path, Msg: string;
begin
  if CurPageID = wpFinished then
  begin
    Path := ExpandConstant('{app}\MyProg.exe');
    if ExecAsOriginalUser(Path, '', '', SW_SHOW, ewNoWait, ResultCode) then
    begin
      Log('Executed MyProg');
    end
      else
    begin
      Msg := 'Error executing MyProg - ' + SysErrorMessage(ResultCode);
      MsgBox(Msg, mbError, MB_OK);
    end;
  end;
  Result := True;
end;
```

Replace ExecAsOriginalUser with Exec, if you want to run the program with elevated/Administrator privileges (if the installer uses them at all).

Body:
Simplifying the answer from Run Files and Programs according to custom checkboxes after clicking on Finish Button in Inno Setup, you can use a code like this:

[Code]

function NextButtonClick(CurPageID: Integer): Boolean;
var
  ResultCode: Integer;
  Path, Msg: string;
begin
  if CurPageID = wpFinished then
  begin
    Path := ExpandConstant('{app}\MyProg.exe');
    if ExecAsOriginalUser(Path, '', '', SW_SHOW, ewNoWait, ResultCode) then
    begin
      Log('Executed MyProg');
    end
      else
    begin
      Msg := 'Error executing MyProg - ' + SysErrorMessage(ResultCode);
      MsgBox(Msg, mbError, MB_OK);
    end;
  end;
  Result := True;
end;

Replace ExecAsOriginalUser with Exec, if you want to run the program with elevated/Administrator privileges (if the installer uses them at all).


问:
Button auto adjust in when media query resize
I'm having problem this 5 button in mobile view. In my desktop the 5 button are all inline. And if its in mobile the last 2 button needs to be at the bottom of 3. The result I need is it needs to be fixed even if it was resize to smaller view. And the button occupied all the space. Please see the image attached. Thank you.

HMTL

```<code><div class="cont6">
    <button type="button" onclick="location.href='#date_2019'">2019 AAA</button>
    <button type="button" onclick="location.href='#date_2018'">2018 AAA</button>
    <button type="button" onclick="location.href='#date_2017'">2017 AAA</button>
    <button type="button" onclick="location.href='#date_2016'">2016 AAA</button>
    <button type="button" onclick="location.href='#date_2015'">2015 AAA</button>
</div>
</code>```

CSS

```<code>.cont6 { margin:0 2%; display:flex; justify-content:space-between; width:96%; }
.cont6 button {
    background-color:#EEE;
    border:1px solid #E5E5E5;
    color:#BF0000;
    font-weight:bold;
    font-size:17px;
    padding:1% 1% 1% 3%;
    cursor:pointer;
}
.cont6 button:after { content:'\2BC6'; margin-left:40px; }

@media only screen and (max-width:640px){
    .cont6 { width:auto; display:block; }
    .cont6 button { margin-bottom:15px; margin-right:2%; font-size:16px; }
}
</code>```

答:
You can use flexbox. Just clean your current code and try this.

body {
  margin: 0;
  background: #333;
}

header {
  padding: .5vw;
  font-size: 0;
  display: -ms-flexbox;
  flex-flow: row wrap;
  display: -webkit-box;
  display: flex;
}

header div {
  flex: auto;
  width: 200px;
  margin: .5vw;
}

header div img {
  width: 100%;
  height: auto;
}

@media screen and (max-width: 400px) {

  header div {
    margin: 1px;
  }

  header {
    padding: 0;
  }

}

button {
  width: 100%;
  border: 0;
  background: purple;
  color: #fff;
  border-radius: 5px;
  height: 60px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div><button>Button1</button></div>
  <div><button>Button1</button></div>
  <div><button>Button1</button></div>
  <div><button>Button1</button></div>
</header></code>```

or see this link

Body:
I'm having problem this 5 button in mobile view. In my desktop the 5 button are all inline. And if its in mobile the last 2 button needs to be at the bottom of 3. The result I need is it needs to be fixed even if it was resize to smaller view. And the button occupied all the space. Please see the image attached. Thank you.

HMTL

    <button type="button" onclick="location.href='#date_2019'">2019 AAA</button>
    <button type="button" onclick="location.href='#date_2018'">2018 AAA</button>
    <button type="button" onclick="location.href='#date_2017'">2017 AAA</button>
    <button type="button" onclick="location.href='#date_2016'">2016 AAA</button>
    <button type="button" onclick="location.href='#date_2015'">2015 AAA</button>

CSS

.cont6 { margin:0 2%; display:flex; justify-content:space-between; width:96%; }
.cont6 button {
    background-color:#EEE;
    border:1px solid #E5E5E5;
    color:#BF0000;
    font-weight:bold;
    font-size:17px;
    padding:1% 1% 1% 3%;
    cursor:pointer;
}
.cont6 button:after { content:'\2BC6'; margin-left:40px; }

@media only screen and (max-width:640px){
    .cont6 { width:auto; display:block; }
    .cont6 button { margin-bottom:15px; margin-right:2%; font-size:16px; }
}

Body:
You can use flexbox. Just clean your current code and try this.

body {
  margin: 0;
  background: #333;
}

header {
  padding: .5vw;
  font-size: 0;
  display: -ms-flexbox;
  flex-flow: row wrap;
  display: -webkit-box;
  display: flex;
}

header div {
  flex: auto;
  width: 200px;
  margin: .5vw;
}

header div img {
  width: 100%;
  height: auto;
}

@media screen and (max-width: 400px) {

  header div {
    margin: 1px;
  }

  header {
    padding: 0;
  }

}

button {
  width: 100%;
  border: 0;
  background: purple;
  color: #fff;
  border-radius: 5px;
  height: 60px;
}

<header>
  <div><button>Button1</button></div>
  <div><button>Button1</button></div>
  <div><button>Button1</button></div>
  <div><button>Button1</button></div>
</header>

or see this link


问:
What's this error about while adding postgis in docker
Part of my Dockerfile is as:

```<code>RUN apt-get install -yqq software-properties-common
RUN add-apt-repository ppa:ubuntugis/ppa && apt-get update -yqq
RUN apt-get install -yqq gdal-bin
RUN apt-get install -yqq postgis
</code>```

I installed postgis repo, then installing postgis, but when it got to the installation step of postgis, I get this prompt on the screen & it's stuck there.

```<code>debconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
Configuring tzdata
------------------

Please select the geographic area in which you live. Subsequent configuration
questions will narrow this down by presenting a list of cities, representing
the time zones in which they are located.

  1. Africa      4. Australia  7. Atlantic  10. Pacific  13. Etc
  2. America     5. Arctic     8. Europe    11. SystemV
  3. Antarctica  6. Asia       9. Indian    12. US
Geographic area:
</code>```

Does anyone has any idea??

答:
Use RUN DEBIAN_FRONTEND=noninteractive apt-get install -yqq postgis when install postgis to suppress the dialog, or use ARG DEBIAN_FRONTEND=noninteractive which will also not persist to container but still have same effect.

Maybe also refers to https://github.com/docker/docker/issues/4032

Body:
Part of my Dockerfile is as:

RUN apt-get install -yqq software-properties-common
RUN add-apt-repository ppa:ubuntugis/ppa && apt-get update -yqq
RUN apt-get install -yqq gdal-bin
RUN apt-get install -yqq postgis

I installed postgis repo, then installing postgis, but when it got to the installation step of postgis, I get this prompt on the screen & it's stuck there.

debconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
Configuring tzdata
------------------

Please select the geographic area in which you live. Subsequent configuration
questions will narrow this down by presenting a list of cities, representing
the time zones in which they are located.

  1. Africa      4. Australia  7. Atlantic  10. Pacific  13. Etc
  2. America     5. Arctic     8. Europe    11. SystemV
  3. Antarctica  6. Asia       9. Indian    12. US
Geographic area:

Does anyone has any idea??


问:
Paint a circular image with border
I want to do something like

```<code>new BoxDecoration(
        color: const Color(0xff7c94b6),
        image: new DecorationImage(
          image: new ExactAssetImage('assets/images/restaurant.jpg'),
          fit: BoxFit.cover,
        ),
        borderRadius: new BorderRadius.all(new Radius.circular(50.0)),
        border: new Border.all(
          color: Colors.red,
          width: 4.0,

        ),
</code>```

The visual I am looking for is like the way gmail shows the user's image. This code - which is from the docs - works fine, but my image should be loaded from a url, and is not in the assets.

答:
```<code> Container(
        height: 150.0,
        width: 150.0,
        child: Padding(
            padding: EdgeInsets.all(15),
            child: CircleAvatar(
              backgroundColor: Colors.transparent,
              radius: 10,
              child: new Image.asset('images/logo.png'),
            )),
        decoration: new BoxDecoration(
          shape: BoxShape.circle,
          border: new Border.all(
            color: Colors.indigo,
            width: 2.0,
          ),
        ));
</code>```

Title: Paint a circular image with border

Body:
I want to do something like

new BoxDecoration(
        color: const Color(0xff7c94b6),
        image: new DecorationImage(
          image: new ExactAssetImage('assets/images/restaurant.jpg'),
          fit: BoxFit.cover,
        ),
        borderRadius: new BorderRadius.all(new Radius.circular(50.0)),
        border: new Border.all(
          color: Colors.red,
          width: 4.0,

        ),

The visual I am looking for is like the way gmail shows the user's image. This code - which is from the docs - works fine, but my image should be loaded from a url, and is not in the assets.


问:
Compare proportions and Statistical significance between more than 2 groups
I created a dataframe to compare the proportions of three or more groups (Real data has more than 50,000 rows). In the left column, 0 indicates survival, 1 indicates death, and 0,1,2,3 in the right column indicates the grade.

In the example dataframe, the proportions by grade do not seem to differ, but I want to derive the p-value whether this is actually statistically significant or not.

The survival rates obtained from the examples are as follows.

grade 0 57.14%

grade 1 66.66%

grade 2 50.0%

grade 3 60.0%

I tried to use both Kai and Anova tests. However, I don't know exactly which method is correct.

```<code>ex_df = pd.DataFrame({"Survive":[0,0,0,0,0,0,0,1,1,1,0,1,1,1,0,0,0,1,1,1,0,0,0,1],
              "grade":[2,1,2,3,0,0,0,3,0,2,1,1,0,0,0,1,2,3,1,2,1,3,3,2]})
</code>```

I want to calculate the p-value

p-value : 0.xxxx ....

答: An Anova test requires your data to be normally distributed, which yours is clearly not (just 0's and 1's). You could try a binomial test by taking the hypothesized probability of survival to be the total number of 1's in your data divided by the total number of measurements, regardless of the grade. Then do a binomial test for each grade. The python function I linked to returns the p-value.</p>

Body:
I created a dataframe to compare the proportions of three or more groups (Real data has more than 50,000 rows). In the left column, 0 indicates survival, 1 indicates death, and 0,1,2,3 in the right column indicates the grade.

In the example dataframe, the proportions by grade do not seem to differ, but I want to derive the p-value whether this is actually statistically significant or not.

The survival rates obtained from the examples are as follows.

grade 0 57.14%

grade 1 66.66%

grade 2 50.0%

grade 3 60.0%

I tried to use both Kai and Anova tests. However, I don't know exactly which method is correct.

ex_df = pd.DataFrame({"Survive":[0,0,0,0,0,0,0,1,1,1,0,1,1,1,0,0,0,1,1,1,0,0,0,1],
              "grade":[2,1,2,3,0,0,0,3,0,2,1,1,0,0,0,1,2,3,1,2,1,3,3,2]})

I want to calculate the p-value

p-value : 0.xxxx ....


问:
Fragment view pager default primary card till response is received is lagging
I am setting FragmentStatePagerAdapter to ViewPager in android. getItem() method is returning count after response is received. I need to show primary item / fragment which will load till user receives the response. I am returning default count as 1 if list is empty. I am setting view pager adapter in onViewCreated() method. But whenever I am launching activity which contains the view pager it is lagging the screen to show default primary data.

Below is my code for state pager adapter :

```<code>private class TestAdapter extends FragmentStatePagerAdapter {
        TestAdapter (FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new AnyFragment();;
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
           return listData == null ? 1 : listData.size();
        }

    }
</code>```

How can solve this issue?

答: I think that You can check listData dynamically with a listener or new thread, null returned because getCount method run once when program started, you can send me full program to help you</p>

Body:
I am setting FragmentStatePagerAdapter to ViewPager in android. getItem() method is returning count after response is received. I need to show primary item / fragment which will load till user receives the response. I am returning default count as 1 if list is empty. I am setting view pager adapter in onViewCreated() method. But whenever I am launching activity which contains the view pager it is lagging the screen to show default primary data.

Below is my code for state pager adapter :

private class TestAdapter extends FragmentStatePagerAdapter {
        TestAdapter (FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new AnyFragment();;
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
           return listData == null ? 1 : listData.size();
        }

    }

How can solve this issue?


问:
get a dimensional array from n lists
I'm trying to get my predictions from my x_test data of one svm classifier:

```<code>maduros = []
ma_predecido = []

pintones = []
pi_predecido = []

verdes = []
ve_predecido = []
print("[INFO] Realizando clasificaciones de en los ejemplos de test (20%)")
for i in range(len(x_test)):
    #Predecir la clase para la imágen actual
    prediccion = svm.predict([x_test[i]])
    if y_test[i] == 0: #Maduro class
        maduros.append(0) #save the class
        ma_predecido.append(int(prediccion)) #save his output
    if y_test[i] == 1: #Pintones class
        pintones.append(1)
        pi_predecido.append(int(prediccion))
    if y_test[i] == 2: #Verdes class
        verdes.append(2)
        ve_predecido.append(int(prediccion))
#Concatenate the lists in an array
test_results = np.array(np.concatenate([maduros, ma_predecido, pintones, pi_predecido, verdes, ve_predecido]))

df = pd.DataFrame(test_results)
filepath = args["salida"]+str('/pruebas_test.xlsx')
df.to_excel(filepath, index=False)
</code>```

i.g maduros[] list is the name of clase and ma_predecido[] will save the outputs for this class.

My classes are:

```<code>"Maduro" one-hot encode = 0
"Pinton"  one-hot encode = 1
"Verde  one-hot encode = 2
</code>```

Anyways my code is giving me a one dimensional array, i could check it in the file .xlsx that i got using pandas library:

I wanto get something like this:

My goal is try to make a confusion matrix from scratch, I would like compare my results with the sklearn confusion matrix o pycm. By the moment i would like to save the class and his result (TP/FP).. I would like improve it:

```<code> test_results = np.array(np.concatenate([maduros, ma_predecido, pintones, pi_predecido, verdes, ve_predecido]))
</code>```

to get a 2d array like the last picture.
thanks

This is my confusion matrix:

```<code>[[74  2  0]
 [ 1 64  1]
 [ 0  0 68]]
</code>```

According to pycm:

```<code>TPR(Sensitivity)         0.97368       0.9697        1.0
TNR(Specificity)                            0.99254       0.98611       0.99296
ACC(Accuracy)   0.98571       0.98095       0.99524
PPV(Precision or positive predictive value)  0.98667       0.9697        0.98551
</code>```

答:
You could construct your confusion matrix using numpy functions : np.where to find where you predicted a label and then to know where you were right. It could look like something like that :

```<code>from sklearn.metrics import confusion_matrix
import numpy
y_test = np.array([0,1,2,0,1,2,0,1,2])
y_pred = np.array([0, 0, 2, 0, 0, 2, 0, 0, 2])

# Expected output is the scikit learn confusion matrix
sk_cm = confusion_matrix(y_test, y_pred)
</code>```

Out :

```<code>array([[3, 0, 0],
       [3, 0, 0],
       [0, 0, 3]])
</code>```

Now we construct our own confusion matrix :

```<code>confusion_matrix = []
precision = []
succ_pred = 0
nmb = 0
TP = []
FN = []
for i in range(3):
    indices = np.where(y_test == i)
    new_row = []
    # Rows where we predicted 0
    new_row.append(len(np.where(y_pred[indices] == 0)[0]))
    # Rows where we predicted 1
    new_row.append(len(np.where(y_pred[indices] == 1)[0]))
    # Rows where we predicted 2
    new_row.append(len(np.where(y_pred[indices] == 2)[0]))
    precision.append(new_row[i]/np.sum(new_row))
    succ_pred += new_row[i]
    TP.append(new_row[i])
    FN.append(np.sum(new_row)-new_row[i])
    nmb += np.sum(new_row)
    confusion_matrix.append(new_row)
accuracy = succ_pred/nmb
</code>```

Output :

```<code>[[3, 0, 0], [3, 0, 0], [0, 0, 3]]
</code>```

Finally you can put this array in a df and save it to excel :

```<code>df = pd.DataFrame({'0' : confusion_matrix[0], '1' :confusion_matrix[1], '2': confusion_matrix[2]})
df.to_excel('test.xls')
</code>```

Title: get a dimensional array from n lists

Body:
I'm trying to get my predictions from my x_test data of one svm classifier:

maduros = []
ma_predecido = []

pintones = []
pi_predecido = []

verdes = []
ve_predecido = []
print("[INFO] Realizando clasificaciones de en los ejemplos de test (20%)")
for i in range(len(x_test)):
    #Predecir la clase para la imágen actual
    prediccion = svm.predict([x_test[i]])
    if y_test[i] == 0: #Maduro class
        maduros.append(0) #save the class
        ma_predecido.append(int(prediccion)) #save his output
    if y_test[i] == 1: #Pintones class
        pintones.append(1)
        pi_predecido.append(int(prediccion))
    if y_test[i] == 2: #Verdes class
        verdes.append(2)
        ve_predecido.append(int(prediccion))
#Concatenate the lists in an array
test_results = np.array(np.concatenate([maduros, ma_predecido, pintones, pi_predecido, verdes, ve_predecido]))

df = pd.DataFrame(test_results)
filepath = args["salida"]+str('/pruebas_test.xlsx')
df.to_excel(filepath, index=False)

i.g maduros[] list is the name of clase and ma_predecido[] will save the outputs for this class.

My classes are:

"Maduro" one-hot encode = 0
"Pinton"  one-hot encode = 1
"Verde  one-hot encode = 2

Anyways my code is giving me a one dimensional array, i could check it in the file .xlsx that i got using pandas library:

I wanto get something like this:

My goal is try to make a confusion matrix from scratch, I would like compare my results with the sklearn confusion matrix o pycm. By the moment i would like to save the class and his result (TP/FP).. I would like improve it:

 test_results = np.array(np.concatenate([maduros, ma_predecido, pintones, pi_predecido, verdes, ve_predecido]))

to get a 2d array like the last picture.
thanks

This is my confusion matrix:

[[74  2  0]
 [ 1 64  1]
 [ 0  0 68]]

According to pycm:

TPR(Sensitivity)         0.97368       0.9697        1.0
TNR(Specificity)                            0.99254       0.98611       0.99296
ACC(Accuracy)   0.98571       0.98095       0.99524
PPV(Precision or positive predictive value)  0.98667       0.9697        0.98551

Body:
You could construct your confusion matrix using numpy functions : np.where to find where you predicted a label and then to know where you were right. It could look like something like that :

from sklearn.metrics import confusion_matrix
import numpy
y_test = np.array([0,1,2,0,1,2,0,1,2])
y_pred = np.array([0, 0, 2, 0, 0, 2, 0, 0, 2])

# Expected output is the scikit learn confusion matrix
sk_cm = confusion_matrix(y_test, y_pred)

Out :

array([[3, 0, 0],
       [3, 0, 0],
       [0, 0, 3]])

Now we construct our own confusion matrix :

confusion_matrix = []
precision = []
succ_pred = 0
nmb = 0
TP = []
FN = []
for i in range(3):
    indices = np.where(y_test == i)
    new_row = []
    # Rows where we predicted 0
    new_row.append(len(np.where(y_pred[indices] == 0)[0]))
    # Rows where we predicted 1
    new_row.append(len(np.where(y_pred[indices] == 1)[0]))
    # Rows where we predicted 2
    new_row.append(len(np.where(y_pred[indices] == 2)[0]))
    precision.append(new_row[i]/np.sum(new_row))
    succ_pred += new_row[i]
    TP.append(new_row[i])
    FN.append(np.sum(new_row)-new_row[i])
    nmb += np.sum(new_row)
    confusion_matrix.append(new_row)
accuracy = succ_pred/nmb

Output :

[[3, 0, 0], [3, 0, 0], [0, 0, 3]]

Finally you can put this array in a df and save it to excel :

df = pd.DataFrame({'0' : confusion_matrix[0], '1' :confusion_matrix[1], '2': confusion_matrix[2]})
df.to_excel('test.xls')


问:
I want to get data from 3 tables
I have 3 tables employee, jobs and department as below,

```<code>-------------------    ----------------    ------------------
| employee        |    |    jobs      |    |   department    |
-------------------    ----------------    ------------------
| empId           |    | jobId        |    |  deptId         |
| fname           |    | jobTitle     |    |  deptName       |
| lname           |    |              |    |  managerId      |
| jobId           |    |              |    |                 |
| managerId       |    |              |    |                 |
| departmentId    |    |              |    |                 |
-------------------    ----------------    -------------------
</code>```

I want to select all data from employee, the job title through jobId, the deptName through deptId and manager name through managerId and employeeId

```<code>SELECT EMPLOYEES.EMPLOYEE_ID, EMPLOYEES.FIRST_NAME, EMPLOYEES.LAST_NAME,
EMPLOYEES.JOB_ID, JOBS.JOB_TITLE AS JOB_TITLE, EMPLOYEES.SALARY,
DEPARTMENTS.DEPARTMENT_ID, DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME
FROM EMPLOYEES
LEFT JOIN JOBS ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
</code>```

what should I do to get the name of the manager using the empId?
or is there any other way to simplify this block of code?

答:
Just Add another LEFT JOIN to the EMPLOYEES table, but give it an alias, say MANAGERS.</p>

```<code>SELECT
    EMPLOYEES.EMPLOYEE_ID,
    EMPLOYEES.FIRST_NAME,
    EMPLOYEES.LAST_NAME,
    EMPLOYEES.JOB_ID,
    JOBS.JOB_TITLE AS JOB_TITLE,
    EMPLOYEES.SALARY,
    DEPARTMENTS.DEPARTMENT_ID,
    DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME,
    MANAGERS.FIRST_NAME AS MANAGER_FIRST_NAME,
    MANAGERS.LAST_NAME AS MANAGER_LAST_NAME
FROM EMPLOYEES
LEFT JOIN EMPLOYEES MANAGERS
    ON EMPLOYEES.MANAGER_ID = MANAGERS.EMPLOYEE_ID
LEFT JOIN JOBS
    ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS
    ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
</code>```

Title: I want to get data from 3 tables

Body:
I have 3 tables employee, jobs and department as below,

-------------------    ----------------    ------------------
| employee        |    |    jobs      |    |   department    |
-------------------    ----------------    ------------------
| empId           |    | jobId        |    |  deptId         |
| fname           |    | jobTitle     |    |  deptName       |
| lname           |    |              |    |  managerId      |
| jobId           |    |              |    |                 |
| managerId       |    |              |    |                 |
| departmentId    |    |              |    |                 |
-------------------    ----------------    -------------------

I want to select all data from employee, the job title through jobId, the deptName through deptId and manager name through managerId and employeeId

SELECT EMPLOYEES.EMPLOYEE_ID, EMPLOYEES.FIRST_NAME, EMPLOYEES.LAST_NAME,
EMPLOYEES.JOB_ID, JOBS.JOB_TITLE AS JOB_TITLE, EMPLOYEES.SALARY,
DEPARTMENTS.DEPARTMENT_ID, DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME
FROM EMPLOYEES
LEFT JOIN JOBS ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID

what should I do to get the name of the manager using the empId?
or is there any other way to simplify this block of code?

Body:
Just Add another LEFT JOIN to the EMPLOYEES table, but give it an alias, say MANAGERS.

SELECT
    EMPLOYEES.EMPLOYEE_ID,
    EMPLOYEES.FIRST_NAME,
    EMPLOYEES.LAST_NAME,
    EMPLOYEES.JOB_ID,
    JOBS.JOB_TITLE AS JOB_TITLE,
    EMPLOYEES.SALARY,
    DEPARTMENTS.DEPARTMENT_ID,
    DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME,
    MANAGERS.FIRST_NAME AS MANAGER_FIRST_NAME,
    MANAGERS.LAST_NAME AS MANAGER_LAST_NAME
FROM EMPLOYEES
LEFT JOIN EMPLOYEES MANAGERS
    ON EMPLOYEES.MANAGER_ID = MANAGERS.EMPLOYEE_ID
LEFT JOIN JOBS
    ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS
    ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID


问:
Disable browsers' back button, completely
Need to prevent users going to the previous page, completely.

When I use the following code it works but it's not what I need exactly. When pressing the back button it says "Document Expired":

```<code>Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
</code>```

Another idea - to open a new window without toolbar:

```<code><script>
    function PopupWithoutToolbar(link) {
        var w = window.open(link.href,
            link.target || "_blank",
            'menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,dependent,width=800,height=620,left=0,top=0');
        return w ? false : true;
    }
</script>

<a href="http://www.google.com" onclick="return PopupWithoutToolbar(this)">yahoo</a>
</code>```

But, still... If the user presses the backspace button on a keyboard he can go back. It seems that this approach is only for hiding and not disabling buttons.

Is there any way to simply ignore the back button?

答:
To disable the back button in the browser you can use use the following code in your JavaScript on the page on which you want to disable the back button.</p>

```<code><script>
history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };
</script>
</code>```

Body:
Need to prevent users going to the previous page, completely.

When I use the following code it works but it's not what I need exactly. When pressing the back button it says "Document Expired":

Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

Another idea - to open a new window without toolbar:

yahoo

But, still... If the user presses the backspace button on a keyboard he can go back. It seems that this approach is only for hiding and not disabling buttons.

Is there any way to simply ignore the back button?

Body:
To disable the back button in the browser you can use use the following code in your JavaScript on the page on which you want to disable the back button.

<script>
history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };
</script>


问:
Subset a dataframe based on quantiles
If I have this data frame:

```<code>df <- data.frame(time = seq(as.Date('2000-01-01'), length.out = 200, by = 'days'),
             a = rnorm(200,8.4, 22), b=rnorm(200,8.4, 22), d= rnorm(200,8.4, 22),
e=rnorm(200,8.4, 22))
</code>```

What would be the easiest way to subset this df so that the values from each columns should be higher than 10th% percentile but lower than 90th% one?

I could do this using a loop, i.e:

```<code>for (i in names(df[,2:5])){
  print(i)
  column <- df[,c('time', i)]
  q <- unname(quantile(column[,2], probs = c(0.1, 0.9))) # just for one column
  column <- column[column[,2] > q[1] &column[,2] < q[2],]
  df <- merge(df, column, by = 'time', all.x = T)
}
</code>```

But there are more simple and more elegant ways to do that using functions or packages like dplyr. Thanks!

答:
Use sapply over columns and filter the values that are in the range.

```<code>sapply(df[-1], function(x) x[x > quantile(x, 0.1) & x < quantile(x, 0.9)])
</code>```

To add time column back could be tricky as we have filtered the values every row potentially could be representing different time.

Better option as suggested by @Sotos is to convert those values to NA instead of filtering

```<code>cbind(df[1], sapply(df[-1], function(i)
            replace(i, i < quantile(i, 0.1) | i > quantile(i, 0.9), NA)))
</code>```

Title: Subset a dataframe based on quantiles

Body:
If I have this data frame:

df <- data.frame(time = seq(as.Date('2000-01-01'), length.out = 200, by = 'days'),
             a = rnorm(200,8.4, 22), b=rnorm(200,8.4, 22), d= rnorm(200,8.4, 22),
e=rnorm(200,8.4, 22))

What would be the easiest way to subset this df so that the values from each columns should be higher than 10th% percentile but lower than 90th% one?

I could do this using a loop, i.e:

for (i in names(df[,2:5])){
  print(i)
  column <- df[,c('time', i)]
  q <- unname(quantile(column[,2], probs = c(0.1, 0.9))) # just for one column
  column <- column[column[,2] > q[1] &column[,2] < q[2],]
  df <- merge(df, column, by = 'time', all.x = T)
}

But there are more simple and more elegant ways to do that using functions or packages like dplyr. Thanks!

Body:
Use sapply over columns and filter the values that are in the range.

sapply(df[-1], function(x) x[x > quantile(x, 0.1) & x < quantile(x, 0.9)])

To add time column back could be tricky as we have filtered the values every row potentially could be representing different time.

Better option as suggested by @Sotos is to convert those values to NA instead of filtering

cbind(df[1], sapply(df[-1], function(i)
            replace(i, i < quantile(i, 0.1) | i > quantile(i, 0.9), NA)))


答:
try using aliases and join back to employee on the manager id.

SELECT
  E.EMPLOYEE_ID, E.FIRST_NAME, E.LAST_NAME,
  E.JOB_ID, J.JOB_TITLE AS JOB_TITLE, E.SALARY,
  D.DEPARTMENT_ID, D.DEPARTMENT_NAME AS DEPARTMENT_NAME,
  M.EMPLOYEE_ID as mgr_id, M.FIRST_NAME as mgr_name, M.LAST_NAME as mgr_lname
FROM EMPLOYEES E LEFT JOIN JOBS J ON
        E.JOB_ID = J.JOB_ID
    LEFT JOIN DEPARTMENTS D ON
        E.DEPARTMENT_ID = D.DEPARTMENT_ID
    join employees M ON
        E.manager_ID = M.employee_ID
```

<p>The reason this query works is because I am doing a self join back to the Employees table from the main result set that you already established. To put it simply, imagine you made an exact copy of the employees table and called it M. If you took your original query and joined to the M table using the original query's Employee.manager_id to the employee_ID in the M table, then you would have the manager for the employee.</p>

<p>There is no need to create an exact copy of the employee table just to look up the manager. We can just reference the employee table a second time and use an alias (I used M for manager). Then we join from your list of employees using the manager_id to get the employee's manager.</p>

<p>You could do this again to get the manager's manager if you need to. Here is that query:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
  E.EMPLOYEE_ID, E.FIRST_NAME, E.LAST_NAME,
  E.JOB_ID, J.JOB_TITLE AS JOB_TITLE, E.SALARY,
  D.DEPARTMENT_ID, D.DEPARTMENT_NAME AS DEPARTMENT_NAME,
  M.EMPLOYEE_ID as mgr_id, M.FIRST_NAME as mgr_name, M.LAST_NAME as mgr_lname
FROM EMPLOYEES E LEFT JOIN JOBS J ON
        E.JOB_ID = J.JOB_ID
    LEFT JOIN DEPARTMENTS D ON
        E.DEPARTMENT_ID = D.DEPARTMENT_ID
    join employees M ON  /* The employee's manager */
        E.manager_ID = M.employee_ID
    LEFT join employees MM ON /* The employee's manager's manager */
        M.manager_ID = MM.employee_ID
</code>```

I used a left join for this last one, because at some point you will get to the top of the management hierarchy and might find that there are no more managers. You could also put a left join on the join employees M

Here it is in Tabular form

```<code>Employee_id   |   Name     |   manager_id
     1        | Fred       |       10
     2        | Jane       |       10
    10        | Bob        |       20
    20        | Betty      |       Null
</code>```

Looking at employee # 1. The values of E.employee_id = 1,  E.Name = Fred and E.manager_id = 10.

So the relevant lines of the query evaluate as follows:

    ...
    join employees M ON  /* The employee's manager */
        E.manager_ID /* i.e. 10 */ = M.employee_ID
    ...
```

So the M alias now refers to the employee record where M.employee_ID = 10 and as such, M.Name = Bob and M.employee_id = 20.

Using the last version of the query, we could then work out that Fred's manager's manager (i.e. Fred's manager is Bob and Bob's manager is Betty) will have an employee_id of 20 (i.e. M.manager_ID = 20), so the MM.employee_id would be 20 and hence refer to Betty who doesn't seem to have a manager.

Title: I want to get data from 3 tables

Body:
try using aliases and join back to employee on the manager id.

SELECT
  E.EMPLOYEE_ID, E.FIRST_NAME, E.LAST_NAME,
  E.JOB_ID, J.JOB_TITLE AS JOB_TITLE, E.SALARY,
  D.DEPARTMENT_ID, D.DEPARTMENT_NAME AS DEPARTMENT_NAME,
  M.EMPLOYEE_ID as mgr_id, M.FIRST_NAME as mgr_name, M.LAST_NAME as mgr_lname
FROM EMPLOYEES E LEFT JOIN JOBS J ON
        E.JOB_ID = J.JOB_ID
    LEFT JOIN DEPARTMENTS D ON
        E.DEPARTMENT_ID = D.DEPARTMENT_ID
    join employees M ON
        E.manager_ID = M.employee_ID

The reason this query works is because I am doing a self join back to the Employees table from the main result set that you already established. To put it simply, imagine you made an exact copy of the employees table and called it M. If you took your original query and joined to the M table using the original query's Employee.manager_id to the employee_ID in the M table, then you would have the manager for the employee.

There is no need to create an exact copy of the employee table just to look up the manager. We can just reference the employee table a second time and use an alias (I used M for manager). Then we join from your list of employees using the manager_id to get the employee's manager.

You could do this again to get the manager's manager if you need to. Here is that query:

SELECT
  E.EMPLOYEE_ID, E.FIRST_NAME, E.LAST_NAME,
  E.JOB_ID, J.JOB_TITLE AS JOB_TITLE, E.SALARY,
  D.DEPARTMENT_ID, D.DEPARTMENT_NAME AS DEPARTMENT_NAME,
  M.EMPLOYEE_ID as mgr_id, M.FIRST_NAME as mgr_name, M.LAST_NAME as mgr_lname
FROM EMPLOYEES E LEFT JOIN JOBS J ON
        E.JOB_ID = J.JOB_ID
    LEFT JOIN DEPARTMENTS D ON
        E.DEPARTMENT_ID = D.DEPARTMENT_ID
    join employees M ON  /* The employee's manager */
        E.manager_ID = M.employee_ID
    LEFT join employees MM ON /* The employee's manager's manager */
        M.manager_ID = MM.employee_ID

I used a left join for this last one, because at some point you will get to the top of the management hierarchy and might find that there are no more managers. You could also put a left join on the join employees M

Here it is in Tabular form

Employee_id   |   Name     |   manager_id
     1        | Fred       |       10
     2        | Jane       |       10
    10        | Bob        |       20
    20        | Betty      |       Null

Looking at employee # 1. The values of E.employee_id = 1,  E.Name = Fred and E.manager_id = 10.

So the relevant lines of the query evaluate as follows:

    ...
    join employees M ON  /* The employee's manager */
        E.manager_ID /* i.e. 10 */ = M.employee_ID
    ...

So the M alias now refers to the employee record where M.employee_ID = 10 and as such, M.Name = Bob and M.employee_id = 20.

Using the last version of the query, we could then work out that Fred's manager's manager (i.e. Fred's manager is Bob and Bob's manager is Betty) will have an employee_id of 20 (i.e. M.manager_ID = 20), so the MM.employee_id would be 20 and hence refer to Betty who doesn't seem to have a manager.


问:
Median array index in an array of 5 values
I have an array of 5 numbers in Excel VBA.

Each array index number is an x coordinate and the array value at each index is the Y coordinate/value. I'm trying to find the "median" x coordinate in the array based on the y values within the array.

Example 1:

```<code>Array(1) = 1, Array(2) = 0, Array(3) = 1, Array(4) = 1, Array(5) = 2
</code>```

I envisage the x coordinate median would be (after rounding) index 4 - are there functions in Excel would support determining this or perhaps some suggested code please?

Example 2:

```<code>Array(1) = 7, Array(2) = 1, Array(3) = 4, Array(4) = 7, Array(5) = 1
</code>```

I envisage the x coordinate median would be (after rounding) index 3?

Example 3:

```<code>Array(1) = 1, Array(2) = 0, Array(3) = 0, Array(4) = 0, Array(5) = 6
</code>```

I envisage the x coordinate median would be (after rounding) index 5?

Example 4:

```<code>Array(1) = 5, Array(2) = 0, Array(3) = 7, Array(4) = 0, Array(5) = 6
</code>```

I envisage the x coordinate median would be (after rounding) index 3?

Thanks in advance!

答:
I don't think your definitions above are an accurate description, namely the x and y co ords.

Nonetheless, you are dealing with a 1 dimensional array and you are trying to find the median within it. As such, by the definition of a median, you need to reorganise your array in numerical order and find the number that divides the array in it's "upper" half and "lower" half. Once you establish this, you can either reference this number by it's orginal index value (x co ord by your definition), or it's new index value.

Let's go through your first example above for clarity.

Example 1 above:

```<code>Array(1) = 1, Array(2) = 0, Array(3) = 1, Array(4) = 1, Array(5) = 2
</code>```

As such:

```<code>Array = Array(1, 0, 1, 1, 2)
</code>```

Reordered:

```<code>Array(0, 1, 1, 1, 2)
</code>```

As can be seen from above the only transformation that needs to occur is that the original index 1 and 2 need reordering to achieve this. If this is the route you have taken then index 3 (x co ord) will be your median index for the values within the array.

In closing, I think your median value will rely on a) the transformation you do from non-ordered to ordered, and b) the index value of the NEW array.

Hope this helps!

Body:
I have an array of 5 numbers in Excel VBA.

Each array index number is an x coordinate and the array value at each index is the Y coordinate/value. I'm trying to find the "median" x coordinate in the array based on the y values within the array.

Example 1:

Array(1) = 1, Array(2) = 0, Array(3) = 1, Array(4) = 1, Array(5) = 2

I envisage the x coordinate median would be (after rounding) index 4 - are there functions in Excel would support determining this or perhaps some suggested code please?

Example 2:

Array(1) = 7, Array(2) = 1, Array(3) = 4, Array(4) = 7, Array(5) = 1

I envisage the x coordinate median would be (after rounding) index 3?

Example 3:

Array(1) = 1, Array(2) = 0, Array(3) = 0, Array(4) = 0, Array(5) = 6

I envisage the x coordinate median would be (after rounding) index 5?

Example 4:

Array(1) = 5, Array(2) = 0, Array(3) = 7, Array(4) = 0, Array(5) = 6

I envisage the x coordinate median would be (after rounding) index 3?

Thanks in advance!

Body:
I don't think your definitions above are an accurate description, namely the x and y co ords.

Nonetheless, you are dealing with a 1 dimensional array and you are trying to find the median within it. As such, by the definition of a median, you need to reorganise your array in numerical order and find the number that divides the array in it's "upper" half and "lower" half. Once you establish this, you can either reference this number by it's orginal index value (x co ord by your definition), or it's new index value.

Let's go through your first example above for clarity.

Example 1 above:

Array(1) = 1, Array(2) = 0, Array(3) = 1, Array(4) = 1, Array(5) = 2

As such:

Array = Array(1, 0, 1, 1, 2)

Reordered:

Array(0, 1, 1, 1, 2)

As can be seen from above the only transformation that needs to occur is that the original index 1 and 2 need reordering to achieve this. If this is the route you have taken then index 3 (x co ord) will be your median index for the values within the array.

In closing, I think your median value will rely on a) the transformation you do from non-ordered to ordered, and b) the index value of the NEW array.

Hope this helps!


问:
How to replace properties which are defined in .componentType file using deployment config plan?
Is there a way to replace preferences which are configured in BPEL componentType file during deployment config plan? Let's say
(If I move these properties in <component> in composite.xml, config plan works fine. I am looking solution for componentType preferences)

My .componentType file as follows

```<code><componentType ..............>
    <property name="preference.somePreference" type="xs:string">actualValue</property>
</componentType>
</code>```

and my deployment_config_plan.xml as follows

```<code><component name="orderProcessor">
<property name="preference.somePreference"><replace>someValue</replace>
</property>
</component>
</code>```

答:
There are no way to replacing such a thing on config plan. You need to move your preferences inside de tag

The same thing happens when you have references on a .componentType file. You need to wrapp this references in a Wrapper.wsdl file. Afterwards you  can change references of this Wrapper.wsdl on cfgplan.xml file.

Body:
Is there a way to replace preferences which are configured in BPEL componentType file during deployment config plan? Let's say
(If I move these properties in <component> in composite.xml, config plan works fine. I am looking solution for componentType preferences)

My .componentType file as follows

<componentType ..............>
    <property name="preference.somePreference" type="xs:string">actualValue</property>
</componentType>

and my deployment_config_plan.xml as follows

<component name="orderProcessor">
<property name="preference.somePreference"><replace>someValue</replace>
</property>
</component>


问:
Why is there a difference between the views I've included as images?
(I have edited the question to describe it more clearly and short.)

Why there is a key as 20.42 when expending but it not presented in the folded view(in the red circle).
See screenshot below, It's weird that there is one index of the array is 20.42 in expended view.

It happened on this situation:

I use push method to add element to an empty array.

Then console.log the array.

Did some assign 20.42 to the array by mistake.

答:
This is how you can get a decimal.

Its not the index btw. The console.log output and the array length property says it all. Still confused? You need to revisit basic JavaScript programming.


问:
Problem adding values stored as variables to a java list
I am going to create a list that I want to add elements to.  I have obtained the elements from clients via them completing 3 dialogue boxes indicating their preferences for a new car, and now I want to add these entries to the list.

I have declared my instance variables and here is the constructor for my list:

```<code> public Car(String aMaker, String aModel, int aYearBuilt);
    {
        super();
        this.maker = aMaker;
        this.model = aModel;
        this.year = aYearBuilt;
    }
</code>```

I have successfully put the return from my first client's dialogue boxes into 3 variables, created thus:

```<code> String inputMaker;
 String inputModel;
 int inputYear;
</code>```

(I remembered to use Integer.parseInt to convert the dialogue input string to an int).

Now I want to put the values in a list:

```<code>List<Car> newCarDetails = new ArrayList<Car>();
</code>```

This is where I start to go wrong:

```<code> newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
    return newCarDetails;
</code>```

Only I have clearly underestimated the task, because it doesn't work.  I just get a hashCode back.  Any help greatly appreciated.

答:
Use a typed list:</p>

```<code>List<Car> newCarDetails = new ArrayList<Car>();

newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
</code>```

Body:
I am going to create a list that I want to add elements to.  I have obtained the elements from clients via them completing 3 dialogue boxes indicating their preferences for a new car, and now I want to add these entries to the list.

I have declared my instance variables and here is the constructor for my list:

 public Car(String aMaker, String aModel, int aYearBuilt);
    {
        super();
        this.maker = aMaker;
        this.model = aModel;
        this.year = aYearBuilt;
    }

I have successfully put the return from my first client's dialogue boxes into 3 variables, created thus:

 String inputMaker;
 String inputModel;
 int inputYear;

(I remembered to use Integer.parseInt to convert the dialogue input string to an int).

Now I want to put the values in a list:

List<Car> newCarDetails = new ArrayList<Car>();

This is where I start to go wrong:

 newCarDetails.add(new Car(inputMaker, inputModel, inputYear));
    return newCarDetails;

Only I have clearly underestimated the task, because it doesn't work.  I just get a hashCode back.  Any help greatly appreciated.

Body:
Use a typed list:

List<Car> newCarDetails = new ArrayList<Car>();

newCarDetails.add(new Car(inputMaker, inputModel, inputYear));


问:
Deleting Buckets in Google Cloud Storage
I have followed the directions provided by Google to delete some old buckets in the in my account ... it is very straight forward process listed however after confirming the deletion to occur the "Preparing  to Delete" pops up on the bottom left, but the system never deletes the files and bucket ?

I have posted this several times but no one have suggested a solution or a reason why the process does not work.

答:
In my experience, when the bucket has lots of objects, using the web interface or gsutil alone is not the best way.

What I did, was that I added a life cycle rule, to have Google delete all the object in the bucket.

Then, coming back after a day, the bucket can easily be deleted.


问:
Django retrieve key of group ChoiceField
retrieve key of group ChoiceField

```<code>MEDIA_CHOICES = (
('Audio', (
        ('vinyl', 'Vinyl'),
        ('cd', 'CD'),
    )
),
('Video', (
        ('vhs', 'VHS Tape'),
        ('dvd', 'DVD'),
    )
),
('unknown', 'Unknown'),
</code>```

)

```<code>class ressource(models.Model):
....

media = models.CharField(max_length=50, choices=MEDIA_CHOICES)
</code>```

in field media i have vinyl or cd or vhs or dvd...but how retrieve audio,video, unknown ?

答:
You should prove us more details. First of all choices should be iterable object (tuple for example as it's in your case), but your tuple is very complicated in your case (Django can not process this). You should pass something like this as a choices.

choices example (This is good tuple code)

```<code>CHOICES = (
    ('key', 'value') # key will be inserted in database (and validation purposes), and  value is just for representation purposes.
)
LANGUAGES = (
    ('python', 'Python'),
    ('js', 'JS'),
    ('ruby', 'Ruby'),
)
</code>```

Imagine that, you are trying to retrieving object from database.

```<code>class ressource(models.Model):
    ''' This is your model '''
    media = models.CharField(max_length=50, choices=MEDIA_CHOICES)

res = ressource.objects.get(pk=1) # retrieve data from database.
print(res.media) # returns string object. you will read actual value of media field
''' But if you want to read all available choices on this field, Django provide as _meta api. You can use it very nice way '''
res = ressource.objects.get(pk=1)
fields = res._meta.fields # This will return tuple-like object.
for field in fields:
    if field.name == 'media':
        # you want to find "media" field
        print(field.choices) # This will return all available choices on your media field
</code>```

Hope, it helps you. Good luck.

Body:
retrieve key of group ChoiceField

MEDIA_CHOICES = (
('Audio', (
        ('vinyl', 'Vinyl'),
        ('cd', 'CD'),
    )
),
('Video', (
        ('vhs', 'VHS Tape'),
        ('dvd', 'DVD'),
    )
),
('unknown', 'Unknown'),

)

class ressource(models.Model):
....

media = models.CharField(max_length=50, choices=MEDIA_CHOICES)

in field media i have vinyl or cd or vhs or dvd...but how retrieve audio,video, unknown ?

Body:
You should prove us more details. First of all choices should be iterable object (tuple for example as it's in your case), but your tuple is very complicated in your case (Django can not process this). You should pass something like this as a choices.

choices example (This is good tuple code)

CHOICES = (
    ('key', 'value') # key will be inserted in database (and validation purposes), and  value is just for representation purposes.
)
LANGUAGES = (
    ('python', 'Python'),
    ('js', 'JS'),
    ('ruby', 'Ruby'),
)

Imagine that, you are trying to retrieving object from database.

class ressource(models.Model):
    ''' This is your model '''
    media = models.CharField(max_length=50, choices=MEDIA_CHOICES)

res = ressource.objects.get(pk=1) # retrieve data from database.
print(res.media) # returns string object. you will read actual value of media field
''' But if you want to read all available choices on this field, Django provide as _meta api. You can use it very nice way '''
res = ressource.objects.get(pk=1)
fields = res._meta.fields # This will return tuple-like object.
for field in fields:
    if field.name == 'media':
        # you want to find "media" field
        print(field.choices) # This will return all available choices on your media field

Hope, it helps you. Good luck.


问:
How to find the value of a multidimensional array by key
How I can search array key from multidimensional array and return found key value with parent array key if it's exist. For example I've custom array:

```<code>$array = [
    'type' => 'vacancy',
    'needs' => ['root' => 'active'],
    'market' => 'shopping',
    'red' => 'color',
    'education' => 'learning',
    'fruits' => [
        'red' => 'apple',
        'cool' => 'cherry'
    ]
];
</code>```

For example I need search key red from current array. As you see in this array exist 2 items with key red. If array have similar keys then function return example array as response:

```<code>[
    0 => ['red' => 'color'],
    1 => ['red' => 'apple']
]
</code>```

If search key (example type) is only once inside array then response will be like this:

```<code>['type' => 'vacancy']
</code>```

I tired:

```<code>function searchKey($key, $array) {
    foreach ($array as $k => $v) {
        if($key === $k) {
            return [$k => $v];
        } elseif(is_array($v)) {
            return searchKey($key, $v);
        } elseif(is_array($k)) {
            return searchKey($key, $k);
        }
    }
    return false;
}
</code>```

When I search key root from array result is correct but when I searching key red return false. How can be solved my function or has any performance methods for searching key and get result for my needs?

答:
You can try this :

```<code>function findByKey($findKey, $array, $result = []) {
    foreach ($array as $key => $value) {
        if ($key === $findKey) {
            $result[] = [$key => $value];
        }
        if (is_array($value)) {
            $result = findByKey($findKey, $value, $result);
        }
    }
    return $result;
}
</code>```

The idea is to use a recursive function :

you loop through your array

for each key => value, you check if the key is what you want : if yes, add it to the result array, else go next

if the value is an other array, you search inside this array if you have the key you want

Now use it :

```<code>$array = [
    'type' => 'vacancy',
    'needs' => ['root' => 'active'],
    'market' => 'shopping',
    'red' => 'color',
    'education' => 'learning',
    'fruits' => [
        'red' => 'apple',
        'cool' => 'cherry'
   ]
];
</code>```

With key type :

```<code>$result = findByKey('type', $array);

var_dump($result);
</code>```

Output is :

```<code>array(1) {
[0]=>
    array(1) {
    ["type"]=>
        string(7) "vacancy"
    }
}
</code>```

With key red :

```<code>$result = findByKey('red', $array);

var_dump($result);
</code>```

Output is :

```<code>array(2) {
    [0]=>
    array(1) {
        ["red"]=>
        string(5) "color"
    }
    [1]=>
    array(1) {
        ["red"]=>
        string(5) "apple"
    }
}
</code>```

Here is a link to test it : link

Body:
How I can search array key from multidimensional array and return found key value with parent array key if it's exist. For example I've custom array:

$array = [
    'type' => 'vacancy',
    'needs' => ['root' => 'active'],
    'market' => 'shopping',
    'red' => 'color',
    'education' => 'learning',
    'fruits' => [
        'red' => 'apple',
        'cool' => 'cherry'
    ]
];

For example I need search key red from current array. As you see in this array exist 2 items with key red. If array have similar keys then function return example array as response:

[
    0 => ['red' => 'color'],
    1 => ['red' => 'apple']
]

If search key (example type) is only once inside array then response will be like this:

['type' => 'vacancy']

I tired:

function searchKey($key, $array) {
    foreach ($array as $k => $v) {
        if($key === $k) {
            return [$k => $v];
        } elseif(is_array($v)) {
            return searchKey($key, $v);
        } elseif(is_array($k)) {
            return searchKey($key, $k);
        }
    }
    return false;
}

When I search key root from array result is correct but when I searching key red return false. How can be solved my function or has any performance methods for searching key and get result for my needs?

Body:
You can try this :

function findByKey($findKey, $array, $result = []) {
    foreach ($array as $key => $value) {
        if ($key === $findKey) {
            $result[] = [$key => $value];
        }
        if (is_array($value)) {
            $result = findByKey($findKey, $value, $result);
        }
    }
    return $result;
}

The idea is to use a recursive function :

you loop through your array

for each key => value, you check if the key is what you want : if yes, add it to the result array, else go next

if the value is an other array, you search inside this array if you have the key you want

Now use it :

$array = [
    'type' => 'vacancy',
    'needs' => ['root' => 'active'],
    'market' => 'shopping',
    'red' => 'color',
    'education' => 'learning',
    'fruits' => [
        'red' => 'apple',
        'cool' => 'cherry'
   ]
];

With key type :

$result = findByKey('type', $array);

var_dump($result);

Output is :

array(1) {
[0]=>
    array(1) {
    ["type"]=>
        string(7) "vacancy"
    }
}

With key red :

$result = findByKey('red', $array);

var_dump($result);

Output is :

array(2) {
    [0]=>
    array(1) {
        ["red"]=>
        string(5) "color"
    }
    [1]=>
    array(1) {
        ["red"]=>
        string(5) "apple"
    }
}

Here is a link to test it : link


问:
CollapsingToolbar layout not scrolling
I have a collapsingtoolbarLayout i have included that in my linear layout after i designed the page i noticed that the collapsing toolbar layout is not scrolling.i am not able to scroll the layout

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fitsSystemWindows="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginBottom="32dp"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/changedImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/dinesh"
                    app:layout_collapseMode="parallax" />
                <android.support.v7.widget.Toolbar
                    android:id="@+id/anim_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                   app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

How to make it scrollable??

答:
Try adding:

```<code>app:layout_scrollFlags="scroll|exitUntilCollapsed
</code>```

to your toolbar(you have added it in CollapsingToolbarLayout. add it inside Toolbar also)

I have added it. see below:

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fitsSystemWindows="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginBottom="32dp"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/changedImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/dinesh"
                    app:layout_collapseMode="parallax" />
                <android.support.v7.widget.Toolbar
                    android:id="@+id/anim_toolbar"
</code>```

app:layout_scrollFlags="scroll|exitUntilCollapsed

```<code>                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                   app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

Title: CollapsingToolbar layout not scrolling

Body:
I have a collapsingtoolbarLayout i have included that in my linear layout after i designed the page i noticed that the collapsing toolbar layout is not scrolling.i am not able to scroll the layout

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fitsSystemWindows="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginBottom="32dp"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/changedImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/dinesh"
                    app:layout_collapseMode="parallax" />
                <android.support.v7.widget.Toolbar
                    android:id="@+id/anim_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                   app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>

How to make it scrollable??

Body:
Try adding:

app:layout_scrollFlags="scroll|exitUntilCollapsed

to your toolbar(you have added it in CollapsingToolbarLayout. add it inside Toolbar also)

I have added it. see below:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fitsSystemWindows="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fitsSystemWindows="true"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginBottom="32dp"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/changedImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/dinesh"
                    app:layout_collapseMode="parallax" />
                <android.support.v7.widget.Toolbar
                    android:id="@+id/anim_toolbar"

app:layout_scrollFlags="scroll|exitUntilCollapsed

                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                   app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>


问:
Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)
I'm developing using the GSSAPI, and I have code which works with a vanilla MIT Kerberos 5 server to do some client/server work. I'm now verifying it's functionality against Active Directory and I've hit an issue.

I have my server authenticated and listening. I can get the client to login. For the record, this is code based off of http://thejavamonkey.blogspot.com/2008/04/clientserver-hello-world-in-kerberos.html. However, I cannot get the client to get the ticket back from AD to get the session between it and the server. I get KrbException: Server not found in Kerberos database (7), and I cannot figure out where the proper place is to add it. I've tried putting the server name with ip in the hosts file, updating dns, putting in server records, etc, with no luck.

If anyone knows where the proper place is to update AD to set a server in the Kerberos Database, that would be great!

答:
In my case, My principal was kafka/kafka.niroshan.com@NIROSHAN.COM I got below lines in the terminal:

```<code>>>> KrbKdcReq send: #bytes read=190
>>> KdcAccessibility: remove kerberos.niroshan.com
>>> KDCRep: init() encoding tag is 126 req type is 13
>>>KRBError:
         cTime is Thu Oct 05 03:42:15 UTC 1995 812864535000
         sTime is Fri May 31 06:43:38 UTC 2019 1559285018000
         suSec is 111309
         error code is 7
         error Message is Server not found in Kerberos database
         cname is kafka/kafka.niroshan.com@NIROSHAN.COM
         sname is kafka/kafka.com@NIROSHAN.COM
         msgType is 30
</code>```

After hours of checking, I just found the below line has a wrong value in kafka_2.12-2.2.0/server.properties

listeners=SASL_PLAINTEXT://kafka.com:9092

Also I got two entries of kafka.niroshan.com and kafka.com for same IP address.

I changed it to as listeners=SASL_PLAINTEXT://kafka.niroshan.com:9092 Then it worked!

According to the below link, the principal should contain the Fully Qualified Domain Name (FQDN) of each host and it should be matched with the principal.

https://docs.oracle.com/cd/E19253-01/816-4557/planning-25/index.html

Body:
In my case, My principal was kafka/kafka.niroshan.com@NIROSHAN.COM I got below lines in the terminal:

>>> KrbKdcReq send: #bytes read=190
>>> KdcAccessibility: remove kerberos.niroshan.com
>>> KDCRep: init() encoding tag is 126 req type is 13
>>>KRBError:
         cTime is Thu Oct 05 03:42:15 UTC 1995 812864535000
         sTime is Fri May 31 06:43:38 UTC 2019 1559285018000
         suSec is 111309
         error code is 7
         error Message is Server not found in Kerberos database
         cname is kafka/kafka.niroshan.com@NIROSHAN.COM
         sname is kafka/kafka.com@NIROSHAN.COM
         msgType is 30

After hours of checking, I just found the below line has a wrong value in kafka_2.12-2.2.0/server.properties

listeners=SASL_PLAINTEXT://kafka.com:9092

Also I got two entries of kafka.niroshan.com and kafka.com for same IP address.

I changed it to as listeners=SASL_PLAINTEXT://kafka.niroshan.com:9092 Then it worked!

According to the below link, the principal should contain the Fully Qualified Domain Name (FQDN) of each host and it should be matched with the principal.

https://docs.oracle.com/cd/E19253-01/816-4557/planning-25/index.html