问:
WSO2 ESB HL7 Transport Acknowledgement issue
WSO2 ESB provides the HL7 transport which is nice option. The transport operates in couple of modes 1) Default mode: auto acknowledge 2) NACK mode: No acknowledgement 3) ACK mode: Custom acknowledgement from the downstream sequence or another HL7 endpoint. These modes are documented http://docs.wso2.org/wiki/display/ESB451/HL7+Transport. This JIRA tracker also confirms the same information on configuration of modes. https://wso2.org/jira/browse/ESBJAVA-954

The issue that I am facing is that the ACK mode which allows for the acknowledgement from downstream application or sequence to be returned back to the application which had initiated the call to WSO2 ESB. I can clearly see in the log that the downstream application or sequence is returning back the acknowledgement and that is getting parsed by the HL7 transport API. However, the application that is waiting for response from WSO2 ESB always gets default acknowledgement only.

When looking into the HL7 transport code, it looks like that the WSO2 code has a defect and its never returning acknowledgement from downstream sequence. Here is the method from the HL7ProcessingContext.java

```<code>public Message handleHL7Result(MessageContext ctx, Message hl7Msg) throws HL7Exception
{
    String resultMode = (String) ctx.getProperty(HL7Constants.HL7_RESULT_MODE);
    if (resultMode != null) {
        if (HL7Constants.HL7_RESULT_MODE_ACK.equals(resultMode)) {
            return this.createAck(hl7Msg);
        } else if (HL7Constants.HL7_RESULT_MODE_NACK.equals(resultMode)) {
            String nackMessage = (String) ctx.getProperty(HL7Constants.HL7_NACK_MESSAGE);
            if (nackMessage == null) {
                nackMessage = "";
            }
            return this.createNack(hl7Msg, nackMessage);
        }
    } else if (this.isAutoAck()) {
        return this.createAck(hl7Msg);
    }
    return this.createNack(hl7Msg, "Application Error: ACK/NACK was not explicitely returned");
}
</code>```

If I am not mistaken, this code needs to be altered as shown below

```<code>***** Original Code from above****
if (HL7Constants.HL7_RESULT_MODE_ACK.equals(resultMode)) {
            return this.createAck(hl7Msg);
}

***** Revised code *****
if (HL7Constants.HL7_RESULT_MODE_ACK.equals(resultMode)) {
    OMElement omElement = msgCtx.getEnvelope().getBody().getFirstElement().getFirstElement();
    String xmlFormat = omElement.toString();
    Message message = this.xmlParser.parse(xmlFormat);
    return message;
}
</code>```

Could someone confirm this fix?

答:
From version ESB 4.7.0 onwards you can use HL7_APPLICATION_ACK property in the hl7 in sequence to wait for the back-end application's response.

```<code><property description="HL7_APPLICATION_ACK" name="HL7_APPLICATION_ACK" scope="axis2" type="STRING" value="true"/>
</code>```

with parameter AutoAck to false in the hl7 proxy

<parameter name="transport.hl7.AutoAck">false</parameter>

Body:
WSO2 ESB provides the HL7 transport which is nice option. The transport operates in couple of modes 1) Default mode: auto acknowledge 2) NACK mode: No acknowledgement 3) ACK mode: Custom acknowledgement from the downstream sequence or another HL7 endpoint. These modes are documented http://docs.wso2.org/wiki/display/ESB451/HL7+Transport. This JIRA tracker also confirms the same information on configuration of modes. https://wso2.org/jira/browse/ESBJAVA-954

The issue that I am facing is that the ACK mode which allows for the acknowledgement from downstream application or sequence to be returned back to the application which had initiated the call to WSO2 ESB. I can clearly see in the log that the downstream application or sequence is returning back the acknowledgement and that is getting parsed by the HL7 transport API. However, the application that is waiting for response from WSO2 ESB always gets default acknowledgement only.

When looking into the HL7 transport code, it looks like that the WSO2 code has a defect and its never returning acknowledgement from downstream sequence. Here is the method from the HL7ProcessingContext.java

public Message handleHL7Result(MessageContext ctx, Message hl7Msg) throws HL7Exception
{
    String resultMode = (String) ctx.getProperty(HL7Constants.HL7_RESULT_MODE);
    if (resultMode != null) {
        if (HL7Constants.HL7_RESULT_MODE_ACK.equals(resultMode)) {
            return this.createAck(hl7Msg);
        } else if (HL7Constants.HL7_RESULT_MODE_NACK.equals(resultMode)) {
            String nackMessage = (String) ctx.getProperty(HL7Constants.HL7_NACK_MESSAGE);
            if (nackMessage == null) {
                nackMessage = "";
            }
            return this.createNack(hl7Msg, nackMessage);
        }
    } else if (this.isAutoAck()) {
        return this.createAck(hl7Msg);
    }
    return this.createNack(hl7Msg, "Application Error: ACK/NACK was not explicitely returned");
}

If I am not mistaken, this code needs to be altered as shown below

***** Original Code from above****
if (HL7Constants.HL7_RESULT_MODE_ACK.equals(resultMode)) {
            return this.createAck(hl7Msg);
}

***** Revised code *****
if (HL7Constants.HL7_RESULT_MODE_ACK.equals(resultMode)) {
    OMElement omElement = msgCtx.getEnvelope().getBody().getFirstElement().getFirstElement();
    String xmlFormat = omElement.toString();
    Message message = this.xmlParser.parse(xmlFormat);
    return message;
}

Could someone confirm this fix?

Body:
From version ESB 4.7.0 onwards you can use HL7_APPLICATION_ACK property in the hl7 in sequence to wait for the back-end application's response.

<property description="HL7_APPLICATION_ACK" name="HL7_APPLICATION_ACK" scope="axis2" type="STRING" value="true"/>

with parameter AutoAck to false in the hl7 proxy

<parameter name="transport.hl7.AutoAck">false</parameter>


来源: stackexchange

问:
I want to place images over a div that has a specific background
I want to create a div (100% wide and height auto). It will have this background image

And i want to place cars over this div.

The positions of the cars will be determined by the API.

The end result will be something like this.

Is is possible to achieve? Please guide me if it is possible. Thankyou.

答:
Here is a simple and basic example of how you can do it using pure html and css:

.car-park {
    width: 1200px;
    height:439px;
    background: url('https://i.stack.imgur.com/n2BwR.png') 0 0 no-repeat;
    position: relative;
  }

  .car {
    background: url('https://i.stack.imgur.com/rZYO1.png') 0 0 no-repeat;
    width: 19px;
    height:40px;
    position: absolute;
  }

  .car-1 {
    top: 50px;
    left: 195px;
  }

  .car-2 {
    top: 295px;
    left: 295px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="car-park">
  <div class="car car-1"></div>
  <div class="car car-2"></div>
</div></code>```

You can also control the size of the car like this:

.car {
  background: url('https://i.stack.imgur.com/rZYO1.png') 0 0 no-repeat;
  background-size: contain;
  width: 19px;
  height:40px;
}

.car-lg {
  width: 22.8px;
  height:48px;
}

.car-xl {
  width: 28.8px;
  height:60px;
}

.margin-bottom-10 {
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="car margin-bottom-10"></div>
<div class="car car-lg margin-bottom-10"></div>
<div class="car car-xl margin-bottom-10"></div></code>```

This is how you set the background to 100% width:

body {
  height: 100vh;
}

.car-park {
  width: 100%;
  height: calc(100% * 1020 / 439);
  max-height: 439px;
  background: url(https://i.stack.imgur.com/n2BwR.png) 0 0 no-repeat;
  background-size: contain;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="car-park"></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is a simple and basic example of how you can do it using pure html and css:

.car-park {
    width: 1200px;
    height:439px;
    background: url('https://i.stack.imgur.com/n2BwR.png') 0 0 no-repeat;
    position: relative;
  }

  .car {
    background: url('https://i.stack.imgur.com/rZYO1.png') 0 0 no-repeat;
    width: 19px;
    height:40px;
    position: absolute;
  }

  .car-1 {
    top: 50px;
    left: 195px;
  }

  .car-2 {
    top: 295px;
    left: 295px;
  }

<div class="car-park">
  <div class="car car-1"></div>
  <div class="car car-2"></div>
</div>

You can also control the size of the car like this:

.car {
  background: url('https://i.stack.imgur.com/rZYO1.png') 0 0 no-repeat;
  background-size: contain;
  width: 19px;
  height:40px;
}

.car-lg {
  width: 22.8px;
  height:48px;
}

.car-xl {
  width: 28.8px;
  height:60px;
}

.margin-bottom-10 {
  margin-bottom: 10px;
}

<div class="car margin-bottom-10"></div>
<div class="car car-lg margin-bottom-10"></div>
<div class="car car-xl margin-bottom-10"></div>

This is how you set the background to 100% width:

body {
  height: 100vh;
}

.car-park {
  width: 100%;
  height: calc(100% * 1020 / 439);
  max-height: 439px;
  background: url(https://i.stack.imgur.com/n2BwR.png) 0 0 no-repeat;
  background-size: contain;
  position: relative;
}

<div class="car-park"></div>


问:
Saving data to a file vs. saving it to MySQL DB
Using a PHP script I need to update a number every 5 seconds while somebody is on my page. So let's say I have 300 visitors, each one spending about 1 minute on the page and every 5 seconds they stay on the page the number will be changed...which is a total of 3600 changes per minute. I would prefer to update the number in my MySQL database, except I'm not sure if it's not too inefficient to have so many MySQL connections (just for the one number change), when I could just change the number in a file.

P.S.: I have no idea weather 3600 connections/minute is a high number or not, but what about this case in general, considering an even higher number of visitors. What is the most efficient way to do this?

答:
It will fail eventually if the user count grows but the performance depends of your server setup and other tasks that are related to this update.

You can do a slight test and open up 300 persistent connections to your database end fire up as much query's you can in minute.

If you don't need it to be transactional (the order of executed query's is not important) then i suggest you to use memcached (or redis if you need to save stuff on disk) for this instead

ContentLicense: CC BY-SA 2.5


问:
Conflict with two jquery datepickers on same page
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:

```<code>\---/\---/\---/_______________
/                            /
\                            \
/  DATEPICKER1               /
\                            \
/  DATEPICKER2               /
\                            \
/                            /
\                            \
/____________________________/
</code>```

The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one.  Did you follow that? :)

So to sum up, clicking a date in datepicker2 activates datepicker1.

I have no idea why this is happening - they have different ids and names, as outlined below.

To create the datepickers I'm just using:

```<code>$(function() {
    $("#datepicker1").datepicker();
    $("#datepicker2").datepicker();
});
</code>```

The fields are simply:

```<code><input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
</code>```

I'm using jQuery v1.9.0 and jQueryui v1.10.0.

Any thoughts on this?  As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification.  Any and all help would be greatly appreciated!!

答:
EXPLANATION of issue

I have the same issue and its very disappointing.
I searched through the source code of jquery and found this:

```<code>if ( $.ui.dialog.overlayInstances ) {
    this._on( this.document, {
        focusin: function( event ) {
            if ( !$( event.target ).closest(".ui-dialog").length ) {
                event.preventDefault();
                $(".ui-dialog:visible:last .ui-dialog-content")
                    .data("ui-dialog")._focusTabbable();
            }
        }
    });
}
</code>```

So when you set focus in element thats not inside the .ui-dialog, it will trigger _focusTabbable() function which set focus to the first input in dialog.

The problem is, that $.datepicker creates div on the end of body - so it is outside of .ui-dialog

If there is another input which _focusTabbable() will give focus its ok, as datepicker can handle that. But if this input has datepicker binded, it will close the previous datepicker, open another on the first input and the select on the previous datepicker is not fired.

One of possible solutions

The solution is in this case have input wich will take first focus in dialog and does not have datepicker on it.

I simply use this HTML code as first input on begin of dialog content where otherwise datepicker input will be on first place:

```<code><span class="ui-helper-hidden-accessible"><input type="text" /></span>
</code>```

Body:
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:

\---/\---/\---/_______________
/                            /
\                            \
/  DATEPICKER1               /
\                            \
/  DATEPICKER2               /
\                            \
/                            /
\                            \
/____________________________/

The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one.  Did you follow that? :)

So to sum up, clicking a date in datepicker2 activates datepicker1.

I have no idea why this is happening - they have different ids and names, as outlined below.

To create the datepickers I'm just using:

$(function() {
    $("#datepicker1").datepicker();
    $("#datepicker2").datepicker();
});

The fields are simply:

<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />

I'm using jQuery v1.9.0 and jQueryui v1.10.0.

Any thoughts on this?  As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification.  Any and all help would be greatly appreciated!!

Body:
EXPLANATION of issue

I have the same issue and its very disappointing.
I searched through the source code of jquery and found this:

if ( $.ui.dialog.overlayInstances ) {
    this._on( this.document, {
        focusin: function( event ) {
            if ( !$( event.target ).closest(".ui-dialog").length ) {
                event.preventDefault();
                $(".ui-dialog:visible:last .ui-dialog-content")
                    .data("ui-dialog")._focusTabbable();
            }
        }
    });
}

So when you set focus in element thats not inside the .ui-dialog, it will trigger _focusTabbable() function which set focus to the first input in dialog.

The problem is, that $.datepicker creates div on the end of body - so it is outside of .ui-dialog

If there is another input which _focusTabbable() will give focus its ok, as datepicker can handle that. But if this input has datepicker binded, it will close the previous datepicker, open another on the first input and the select on the previous datepicker is not fired.

One of possible solutions

The solution is in this case have input wich will take first focus in dialog and does not have datepicker on it.

I simply use this HTML code as first input on begin of dialog content where otherwise datepicker input will be on first place:

<span class="ui-helper-hidden-accessible"><input type="text" /></span>


问:
DataGridView navigate cell on KeyUp with wrapped text

I would expect to navigate to the other cell only when reaching the very top.
What actually happens is that it navigates on hitting the 'up' key at the fourth line (which would the first line, if not for the text wrap).

Do you know if it is 'by design' or can be avoided?

答:
Handling of the keyboard input is a responsability shared by the editing controls (classes implementing IDataGridViewEditingControl) inside the DataGridView and the DataGridView itself.

If you look at the source code inside DataGridView, you will see that the decision of where to handle a key press is demanded to the editing controls. Basically, the DataGridView asks to the IDataGridViewEditingControl (in your case, a DataGridViewTextBoxEditingControl) "Do you want to handle it?" by calling the
EditingControlWantsInputKey method.

This method contains a bug, or better an over-semplifications. The intent of the code seems to be "if I am already on the first line, a KeyUp means that the user wants to move to the cell above me". Unfortunately, "first line" is, in the code, anything before the first \r\n, disregarding word wrap. Which is what you are observing.

Fortunately EditingControlWantsInputKey is public virtual, so you can derive from DataGridViewTextBoxEditingControl and adjust the behaviour corresponding to your needs.

For example:

```<code>public class MyDataGridViewTextBoxEditingControl : DataGridViewTextBoxEditingControl {
   public override bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey) {
        switch (keyData & Keys.KeyCode)
        {
            case Keys.Up:
               return false; // never pass KeyUp to the DataGrid
        ...
        // call base.EditingControlWantsInputKey when
        // you want to retain the standard behaviour
</code>```

This is oversimplified (it just disables the "move to the cell above" behaviour; you might want to act differently, maybe measuring the text lenght fitting in the "real" first line inside the cell by using Graphics.MeasureString. This is up to you and what you want to obtain.

Then, it is relatively easy to replace the standard controls for DataGridView cells with your own.

Body:
Handling of the keyboard input is a responsability shared by the editing controls (classes implementing IDataGridViewEditingControl) inside the DataGridView and the DataGridView itself.

If you look at the source code inside DataGridView, you will see that the decision of where to handle a key press is demanded to the editing controls. Basically, the DataGridView asks to the IDataGridViewEditingControl (in your case, a DataGridViewTextBoxEditingControl) "Do you want to handle it?" by calling the
EditingControlWantsInputKey method.

This method contains a bug, or better an over-semplifications. The intent of the code seems to be "if I am already on the first line, a KeyUp means that the user wants to move to the cell above me". Unfortunately, "first line" is, in the code, anything before the first \r\n, disregarding word wrap. Which is what you are observing.

Fortunately EditingControlWantsInputKey is public virtual, so you can derive from DataGridViewTextBoxEditingControl and adjust the behaviour corresponding to your needs.

For example:

public class MyDataGridViewTextBoxEditingControl : DataGridViewTextBoxEditingControl {
   public override bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey) {
        switch (keyData & Keys.KeyCode)
        {
            case Keys.Up:
               return false; // never pass KeyUp to the DataGrid
        ...
        // call base.EditingControlWantsInputKey when
        // you want to retain the standard behaviour

This is oversimplified (it just disables the "move to the cell above" behaviour; you might want to act differently, maybe measuring the text lenght fitting in the "real" first line inside the cell by using Graphics.MeasureString. This is up to you and what you want to obtain.

Then, it is relatively easy to replace the standard controls for DataGridView cells with your own.


问:
How to change owner of PostgreSql database?
I need to change the owner of PostgreSql database.

How to change owner of PostgreSql database in phppgadmin?

答:
```<code>ALTER DATABASE name OWNER TO new_owner;
</code>```

See the Postgresql manual's entry on this for more details.

ContentLicense: CC BY-SA 4.0

Body:
ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.


问:
Android Emulator won't boot or start. Nothing is popping up
This question is already many times asked but nothing its like my problem.
I don't get it why its not booting up or starting my apk.

Its stuck right there. Nothing is happening just the waiting for target device respond is coming up.

Everything worked perfectly until now.

I even reinstalled it. Didn't help much

PC SPECS:
i7 Core 2.2 GHZ
16GB RAM
Intel Iris Pro 1500MB

Android Studio 2.3

```<code>Error while waiting for device: Timed out after 300seconds waiting for emulator to come online.
</code>```

Still the same error.....

答: I got it to work with changing the auto graphics to software!</p>

Body:
This question is already many times asked but nothing its like my problem.
I don't get it why its not booting up or starting my apk.

Its stuck right there. Nothing is happening just the waiting for target device respond is coming up.

Everything worked perfectly until now.

I even reinstalled it. Didn't help much

PC SPECS:
i7 Core 2.2 GHZ
16GB RAM
Intel Iris Pro 1500MB

Android Studio 2.3

Error while waiting for device: Timed out after 300seconds waiting for emulator to come online.

Still the same error.....


问:
PLSQL - Creating procedure with parameter, but only allowing 2 values
First off, I'm a DBA that dabbles in PL/SQL Programming.  I have some knowledge, but some is most certainly lacking.

```<code>CREATE OR REPLACE PROCEDURE TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN VARCHAR2)
AS ....
</code>```

I'd like to allow the P_STATUS parameter only be allowed values of 'E' or 'D' for enabling or disabling a trigger.  I've done some searching, but can't seem to find the solution for this.  Any help is greatly appreciated!

Thanks!

Jeremy

答:
I'd rather take the following approach:

```<code>CREATE OR REPLACE PROCEDURE ENABLE_TRIGGER_PRC (P_TRGNAME IN VARCHAR2)
AS ....
BEGIN
  -- Enable the trigger P_TRGNAME here
END;

CREATE OR REPLACE PROCEDURE DISABLE_TRIGGER_PRC (P_TRGNAME IN VARCHAR2)
AS ....
BEGIN
  -- Disable the trigger P_TRGNAME here
END;
</code>```

You can make the second to call the first etc., but you should always have the IF statement (as GurV mentioned), to validate it once inside the Procedure. In the future, you might want to add drop as well. I suggest you put those into a package, so that they are all consolidated there, having one procedure to execute the actual statement, say in execute immediate, so that all the other procedures can reuse the same code.

Cheers

Body:
First off, I'm a DBA that dabbles in PL/SQL Programming.  I have some knowledge, but some is most certainly lacking.

CREATE OR REPLACE PROCEDURE TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN VARCHAR2)
AS ....

I'd like to allow the P_STATUS parameter only be allowed values of 'E' or 'D' for enabling or disabling a trigger.  I've done some searching, but can't seem to find the solution for this.  Any help is greatly appreciated!

Thanks!

Jeremy

Body:
I'd rather take the following approach:

CREATE OR REPLACE PROCEDURE ENABLE_TRIGGER_PRC (P_TRGNAME IN VARCHAR2)
AS ....
BEGIN
  -- Enable the trigger P_TRGNAME here
END;

CREATE OR REPLACE PROCEDURE DISABLE_TRIGGER_PRC (P_TRGNAME IN VARCHAR2)
AS ....
BEGIN
  -- Disable the trigger P_TRGNAME here
END;

You can make the second to call the first etc., but you should always have the IF statement (as GurV mentioned), to validate it once inside the Procedure. In the future, you might want to add drop as well. I suggest you put those into a package, so that they are all consolidated there, having one procedure to execute the actual statement, say in execute immediate, so that all the other procedures can reuse the same code.

Cheers


问:
Bash integer expression on IF statement when retrieving free memory
I am getting the below error while running the script memory.sh script:

```<code>[root@test tmp]# ./memory.sh
./memory.sh: line 3: [: 2.05028: integer expression expected
 Normal
</code>```

The content of the memory.sh script is:

```<code>[root@test tmp]# cat memory.sh
threshold=80
MEMORY=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if [ ${MEMORY} -gt ${threshold} ]; then
    sudo sync;echo 3 > /proc/sys/vm/drop_caches
else
   echo "Normal"
fi
</code>```

Does anyone know how to prevent this error?

答:
The error on the IF statement comes up when retrieving float values from
the Memory.

The following script casts the float memory value to an integer for the comparison:

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

threshold=80
memory=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
castedMemory=$(echo $memory | cut -d'.' -f1)
if [[ "$castedMemory" -gt $threshold ]]; then
    sudo sync
    echo 3 > /proc/sys/vm/drop_caches
else
   echo "Normal"
fi
</code>```

Body:
I am getting the below error while running the script memory.sh script:

[root@test tmp]# ./memory.sh
./memory.sh: line 3: [: 2.05028: integer expression expected
 Normal

The content of the memory.sh script is:

[root@test tmp]# cat memory.sh
threshold=80
MEMORY=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if [ ${MEMORY} -gt ${threshold} ]; then
    sudo sync;echo 3 > /proc/sys/vm/drop_caches
else
   echo "Normal"
fi

Does anyone know how to prevent this error?

Body:
The error on the IF statement comes up when retrieving float values from
the Memory.

The following script casts the float memory value to an integer for the comparison:

#!/bin/bash

threshold=80
memory=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
castedMemory=$(echo $memory | cut -d'.' -f1)
if [[ "$castedMemory" -gt $threshold ]]; then
    sudo sync
    echo 3 > /proc/sys/vm/drop_caches
else
   echo "Normal"
fi


问:
How to return values from group_by in R dplyr?
Good morning,

I've got a two-column dataset which I'd like to spread to more columns based on a group_by in Dplyr but I'm not sure how.

My data looks like:

```<code>Person     Case
John       A
John       B
Bill       C
David      F
</code>```

I'd like to be able to transform it to the following structure:

```<code>Person  Case_1  Case_2 ... Case_n
John    A       B
Bill    C       NA
David   F       NA
</code>```

My original thought was along the lines of:

```<code>data %>%
  group_by(Person) %>%
  spread()

Error: Please supply column name
</code>```

What's the easiest, or most R-like way to achieve this?

答:
You should first add a case id to the dataset, which can be done with a combination of group_by and mutate:

```<code>dat = data.frame(Person = c('John', 'John', 'Bill', 'David'), Case = c('A', 'B', 'C', 'F'))
dat = dat %>% group_by(Person) %>% mutate(id = sprintf('Case_%d', row_number()))
dat %>% head()
# A tibble: 4 × 3
  Person   Case     id
  <fctr> <fctr>  <chr>
1   John      A Case_1
2   John      B Case_2
3   Bill      C Case_1
4  David      F Case_1
</code>```

Now you can use spread to transform the data:

```<code>dat %>% spread(Person, Case)
# A tibble: 2 × 4
      id   Bill  David   John
*  <chr> <fctr> <fctr> <fctr>
1 Case_1      C      F      A
2 Case_2     NA     NA      B
</code>```

You can get the structure you list above using:

```<code>res = dat %>% spread(Person, Case) %>% select(-id) %>% t() %>% as.data.frame()
names(res) = unique(dat$id)
res
      Case_1 Case_2
Bill       C   <NA>
David      F   <NA>
John       A      B
</code>```

Body:
Good morning,

I've got a two-column dataset which I'd like to spread to more columns based on a group_by in Dplyr but I'm not sure how.

My data looks like:

Person     Case
John       A
John       B
Bill       C
David      F

I'd like to be able to transform it to the following structure:

Person  Case_1  Case_2 ... Case_n
John    A       B
Bill    C       NA
David   F       NA

My original thought was along the lines of:

data %>%
  group_by(Person) %>%
  spread()

Error: Please supply column name

What's the easiest, or most R-like way to achieve this?

Body:
You should first add a case id to the dataset, which can be done with a combination of group_by and mutate:

dat = data.frame(Person = c('John', 'John', 'Bill', 'David'), Case = c('A', 'B', 'C', 'F'))
dat = dat %>% group_by(Person) %>% mutate(id = sprintf('Case_%d', row_number()))
dat %>% head()
# A tibble: 4 × 3
  Person   Case     id
  <fctr> <fctr>  <chr>
1   John      A Case_1
2   John      B Case_2
3   Bill      C Case_1
4  David      F Case_1

Now you can use spread to transform the data:

dat %>% spread(Person, Case)
# A tibble: 2 × 4
      id   Bill  David   John
*  <chr> <fctr> <fctr> <fctr>
1 Case_1      C      F      A
2 Case_2     NA     NA      B

You can get the structure you list above using:

res = dat %>% spread(Person, Case) %>% select(-id) %>% t() %>% as.data.frame()
names(res) = unique(dat$id)
res
      Case_1 Case_2
Bill       C   <NA>
David      F   <NA>
John       A      B


问:
Error when trying to run rspec: `require': cannot load such file -- rails_helper (LoadError)
I am trying to run rspec for Ruby on Rails.  I am running Rails 4.1.1.  I have installed the gem, have established a spec folder with some tests.  I have created a directory through $ rails g rspec:install

I tried to create a testing database through $ rake db:test:prepare but it throws this error message:

```<code>WARNING: db:test:prepare is deprecated. The Rails test helper now maintains your test
schema automatically, see the release notes for details.
</code>```

So I ended up looking at this stack overflow post, and of the two options, the one that worked was:

```<code>rake db:schema:load RAILS_ENV=test
</code>```

So, now I need to run rspec.

When I run $ rspec spec from the command line I get this error:

```<code>/Users/myname/.rbenv/versions/2.1.1/lib/ruby/2.1.0/rubygems/core_ext/
kernel_require.rb:55:in `require': cannot load such file -- rails_helper (LoadError)
</code>```

How do I resolve this so that I can start running tests?

答:
For newer versions (3.5), if you need to run the generator, rails generate rspec:install doesn't work for me. I used:

```<code>rspec --init
</code>```

Creates .rspec and spec/spec_helper.rb.

EDIT:
Just in case, I found out that I installed rspec gem for ruby, not the one for Rails, so rspec:install wasn't available. Should use https://github.com/rspec/rspec-rails.

Body:
I am trying to run rspec for Ruby on Rails.  I am running Rails 4.1.1.  I have installed the gem, have established a spec folder with some tests.  I have created a directory through $ rails g rspec:install

I tried to create a testing database through $ rake db:test:prepare but it throws this error message:

WARNING: db:test:prepare is deprecated. The Rails test helper now maintains your test
schema automatically, see the release notes for details.

So I ended up looking at this stack overflow post, and of the two options, the one that worked was:

rake db:schema:load RAILS_ENV=test

So, now I need to run rspec.

When I run $ rspec spec from the command line I get this error:

/Users/myname/.rbenv/versions/2.1.1/lib/ruby/2.1.0/rubygems/core_ext/
kernel_require.rb:55:in `require': cannot load such file -- rails_helper (LoadError)

How do I resolve this so that I can start running tests?

Body:
For newer versions (3.5), if you need to run the generator, rails generate rspec:install doesn't work for me. I used:

rspec --init

Creates .rspec and spec/spec_helper.rb.

EDIT:
Just in case, I found out that I installed rspec gem for ruby, not the one for Rails, so rspec:install wasn't available. Should use https://github.com/rspec/rspec-rails.


问:
How to convert bytes column (with logicaltype as decimal) in Avro to decimal?
I have a decimal column "TOT_AMT" defined as type "bytes" and logical type "decimal" in my avro schema.

After creating the data frame in spark using databricks spark-avro, when I tried to sum the TOT_AMT column using the sum function it throws "Function sum requires numeric types not Binarytype" error.

The column is defined like below in avro schema,

name="TOT_AMT","type":["null",{ "type":"bytes","logicaltype":"decimal","precision":20,"scale":10}]

I am creating dataframe and summing up like,

```<code>val df=sqlContext.read.format("com.databricks.spark.avro").load("input dir")
df.agg(sum("TOT_AMT")).show()
</code>```

It seems that the decimal value is read as Binarytype while creating dataframe. In such a case how can we perform numeric operations on such decimal columns? Will it be possible to convert this Byte array to BigDecimal and then perform calculations.

答:
According to Supported types for Avro -> Spark SQL conversion, bytes Avro type is converted to Spark SQL's BinaryType (see also the code).

According to the source code you can define your own custom schema using avroSchema option, i.e.

```<code>spark.read
  .format("com.databricks.spark.avro")
  .option("avroSchema", yourSchemaHere)
</code>```

That gives you the way to specify the mapping from BinaryType to Decimal.

You can also use cast function to cast a binary value to their decimal format.

p.s. I don't know if the reader supports logicaltype hints defined in a Avro schema. It'd be nice to have such a feature if not available currently.

Body:
I have a decimal column "TOT_AMT" defined as type "bytes" and logical type "decimal" in my avro schema.

After creating the data frame in spark using databricks spark-avro, when I tried to sum the TOT_AMT column using the sum function it throws "Function sum requires numeric types not Binarytype" error.

The column is defined like below in avro schema,

name="TOT_AMT","type":["null",{ "type":"bytes","logicaltype":"decimal","precision":20,"scale":10}]

I am creating dataframe and summing up like,

val df=sqlContext.read.format("com.databricks.spark.avro").load("input dir")
df.agg(sum("TOT_AMT")).show()

It seems that the decimal value is read as Binarytype while creating dataframe. In such a case how can we perform numeric operations on such decimal columns? Will it be possible to convert this Byte array to BigDecimal and then perform calculations.

Body:
According to Supported types for Avro -> Spark SQL conversion, bytes Avro type is converted to Spark SQL's BinaryType (see also the code).

According to the source code you can define your own custom schema using avroSchema option, i.e.

spark.read
  .format("com.databricks.spark.avro")
  .option("avroSchema", yourSchemaHere)

That gives you the way to specify the mapping from BinaryType to Decimal.

You can also use cast function to cast a binary value to their decimal format.

p.s. I don't know if the reader supports logicaltype hints defined in a Avro schema. It'd be nice to have such a feature if not available currently.


问:
How to change document by terms dataframe into a dataframe which records the documents where a word appears
I have a

I want to change the dataframe into the format like

Could you tell me how to code with pandas, is there any built-in function in pandas which can be used to do it.

```<code>doc_term_frame=pd.DataFrame(data={'doc_id':[1,2,3,4],'words':[['w1','w2'],['w2','w3'],['w4','w5'],['w4','w6']]}).set_index('doc_id')
desired_frame=pd.DataFrame(data={'word':['w1','w2','w3','w4','w5','w6'],'doc_ids':[[1],[1,2],[2],[3,4],[3],[4]]}).set_index('word')
</code>```

答:
Using pd.concat

```<code>w = pd.concat({k: pd.Series(v) for k, v in df.words.iteritems()})
pd.Series(
    w.index.get_level_values(0)
).groupby(w.values).apply(list).to_frame(name='doc_ids')

   doc_ids
w1     [1]
w2  [1, 2]
w3     [2]
w4  [3, 4]
w5     [3]
w6     [4]
</code>```

Body:
I have a

I want to change the dataframe into the format like

Could you tell me how to code with pandas, is there any built-in function in pandas which can be used to do it.

doc_term_frame=pd.DataFrame(data={'doc_id':[1,2,3,4],'words':[['w1','w2'],['w2','w3'],['w4','w5'],['w4','w6']]}).set_index('doc_id')
desired_frame=pd.DataFrame(data={'word':['w1','w2','w3','w4','w5','w6'],'doc_ids':[[1],[1,2],[2],[3,4],[3],[4]]}).set_index('word')

Body:
Using pd.concat

w = pd.concat({k: pd.Series(v) for k, v in df.words.iteritems()})
pd.Series(
    w.index.get_level_values(0)
).groupby(w.values).apply(list).to_frame(name='doc_ids')

   doc_ids
w1     [1]
w2  [1, 2]
w3     [2]
w4  [3, 4]
w5     [3]
w6     [4]


问:
Python. Selenium misses element
I need to get feedbacks from site

Feedbacks are inside  tag, so I go to iframe, and i get feedbacks, from the first page, but then i need change page using button:

Selenium can find it by class or xpath, but when it tries to click it returns error

```<code>selenium.common.exceptions.WebDriverException: Message: unknown error: Element <iframe scrolling="no" frameborder="0" marginwidth="0" marginheight="0" width="100%" height="1943" src="//feedback.aliexpress.com/display/productEvaluation.htm?productId=1000003578539&ownerMemberId=825321852&companyId=&memberType=seller&startValidDate=" cd_frame_id_="9dbc34cc8793cee8fbcab5180296b0d6"></iframe> is not clickable at point (1001, 582). Other element would receive the click: <span data-role="show" class="show-history">...</span>
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.1.7601 SP1 x86_64)
</code>```

Here is my code:

```<code>driver = webdriver.Chrome()
driver.get(url)

close_popup = driver.find_element_by_class_name('close-layer')
close_popup.click()

tab_feedback = driver.find_element_by_xpath('//*[@id="j-product-tabbed-pane"]/ul/li[2]')
tab_feedback.click()

driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "//feedback.aliexpress.com/display/productEvaluation.htm")]'))

text_feedbacks = driver.find_elements_by_class_name('buyer-feedback')

next = driver.find_element_by_class_name('ui-pagination-next ui-goto-page')
next.click()
</code>```

I thought that maybe selenium too fast, I tried to wait and loop but still can't get next page of feedbacks. Also i tried to get this element using xpath:

```<code>next = driver.find_element_by_xpath( "//div[@class='ui-pagination-navi util-left']/a[@class='ui-goto-page']")
</code>```

But nothing helps.

How can i get next page of feedbacks using selenium? Why other element receives click?

答:
Try to use below code:

```<code>from selenium.webdriver.common.keys import Keys

driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "//feedback.aliexpress.com/display/productEvaluation.htm")]'))

text_feedbacks = driver.find_elements_by_class_name('buyer-feedback')
driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
next = driver.find_element_by_link_text("Next")
next.click()
driver.switch_to.default_content()
</code>```

The problem is that span "Recently viewed" element overlaps required button and so intercepts the click... You might need just to scroll page a little (in provided code- by simulating Page Down button pressing)

Note that you should switch back from iframe after clicking "Next" button

Title: Python. Selenium misses element

Body:
I need to get feedbacks from <a href="https://ru.aliexpress.com/item/New-Original-Xiaomi-Mi-Band-2-Miband-Wistband-Bracelet-with-Smart-Heart-Rate-Fitness-Touchpad-OLED/32677212146.html?spm=2114.01010208.3.1.nXc9Wn&ws_ab_test=searchweb0_0%2Csearchweb201602_0_10065_10068_10084_10083_10080_10082_10081_10110_10136_10111_10137_10060_10112_10138_10113_10062_10114_10141_10056_10055_10037_128_10054_10059_10099_10078_10079_10077_10103_10073_10102_10096_10070_10122_10123_10144_10052_10053_10124_10142_10107_10050_10143_10051%2Csearchweb201603_0%2Cafswitch_1%2CppcSwitch_5%2Csingle_sort_0_default&btsid=bb96f999-5b48-47c4-8605-d04f86ebeaf6&algo_expid=b8d752f3-57dc-43e0-8d73-4b008ae3600a-0&algo_pvid=b8d752f3-57dc-43e0-8d73-4b008ae3600a" rel="nofollow noreferrer">site

Feedbacks are inside  tag, so I go to iframe, and i get feedbacks, from the first page, but then i need change page using button:

Selenium can find it by class or xpath, but when it tries to click it returns error

selenium.common.exceptions.WebDriverException: Message: unknown error: Element  is not clickable at point (1001, 582). Other element would receive the click: ...
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.1.7601 SP1 x86_64)

Here is my code:

driver = webdriver.Chrome()
driver.get(url)

close_popup = driver.find_element_by_class_name('close-layer')
close_popup.click()

tab_feedback = driver.find_element_by_xpath('//*[@id="j-product-tabbed-pane"]/ul/li[2]')
tab_feedback.click()

driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "//feedback.aliexpress.com/display/productEvaluation.htm")]'))

text_feedbacks = driver.find_elements_by_class_name('buyer-feedback')

next = driver.find_element_by_class_name('ui-pagination-next ui-goto-page')
next.click()

I thought that maybe selenium too fast, I tried to wait and loop but still can't get next page of feedbacks. Also i tried to get this element using xpath:

next = driver.find_element_by_xpath( "//div[@class='ui-pagination-navi util-left']/a[@class='ui-goto-page']")

But nothing helps.

How can i get next page of feedbacks using selenium? Why other element receives click?

Body:
Try to use below code:

from selenium.webdriver.common.keys import Keys

driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "//feedback.aliexpress.com/display/productEvaluation.htm")]'))

text_feedbacks = driver.find_elements_by_class_name('buyer-feedback')
driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
next = driver.find_element_by_link_text("Next")
next.click()
driver.switch_to.default_content()

The problem is that span "Recently viewed" element overlaps required button and so intercepts the click... You might need just to scroll page a little (in provided code- by simulating Page Down button pressing)

Note that you should switch back from iframe after clicking "Next" button


问:
Rest Assured - Cannot serialize because cannot determine how to serialize content-type
I am using Rest Assured for testing API

WHEN I post a request for authentication, the error occurs to say that: "java.lang.IllegalArgumentException: Cannot serialize because cannot determine how to serialize content-type application/x-www-form-urlencoded;charset=UTF-8"

Here is my test method

```<code> @Test
public void authenticate()
{
    AuthenDto authenDto = new AuthenDto("username","password","false","Login");
    given()
            .contentType("application/x-www-form-urlencoded;charset=UTF-8")
            .accept("application/json, text/plain, */*")
            .body(authenDto)
    .when()
            .post("ENDPOINT")
    .then()
            .statusCode(200);
}
</code>```

答:
Just guessing, but did you try without the "charset"? Like this:

```<code>.contentType("application/x-www-form-urlencoded")
</code>```

Or

```<code>.contentType(ContentType.URLENC)
</code>```

Body:
I am using Rest Assured for testing API

WHEN I post a request for authentication, the error occurs to say that: "java.lang.IllegalArgumentException: Cannot serialize because cannot determine how to serialize content-type application/x-www-form-urlencoded;charset=UTF-8"

Here is my test method

 @Test
public void authenticate()
{
    AuthenDto authenDto = new AuthenDto("username","password","false","Login");
    given()
            .contentType("application/x-www-form-urlencoded;charset=UTF-8")
            .accept("application/json, text/plain, */*")
            .body(authenDto)
    .when()
            .post("ENDPOINT")
    .then()
            .statusCode(200);
}

Body:
Just guessing, but did you try without the "charset"? Like this:

.contentType("application/x-www-form-urlencoded")

Or

.contentType(ContentType.URLENC)


问:
How much flexibility it gives when you create a views using Zend forms and decorators
I need to create search view that contains 8 - 9 controls in a form. these controls are mixed type like text box, text area, combo box, check box and radio box. I also need to hide and show some of the controls based on previously selected values. There are some controls generated through ajax based on selected values. after search the same page show the results with pagination.

Can anybody let me know, should I use Zend forms and custom decorators or should I use normal html and Java Script to prepare this page. Which one is time saving job as I prefer later one.

I already have the page design in Static HTML.

答:
In reply to karim79's answer, it really depends. If you're used to Zend_Form or have enough time to dive in, then go for it, it is worth to do it as it could save you a lot of time in a near future.
But it is really a matter of taste, if your design is good and you use view helper to manage your search form and so on, then go for it if you feel better with it.
But be careful, doing such way can lead to messy code, even if it could be true with Zend_Form, it will impose you some rules through its design.

In your case, I'll personally go for custom elements/decorators and view helpers.


问:
Semantic Web - Ontology OWL class vs OOPS class
What is the difference between an OWL class and a class in OOPS language, e.g. Java?</p>

答:
Here is a list of 10 main differences, some of them applicable only for OWL-DL:

OWL classes are like sets, OOPS classes are like templates

OWL classes follow Description Logics, OOPS don't (or any other formal logic; they are based on heuristics)

OOPS classes have relations, while the only relation between OWL classes is rdfs:subClassOf (when OWL classes are treated only as classes, see point 10 for an exeption). What looks a bit like indirect description of relations, are the necessary and sufficient conditions of sublcasses and individuals, using owl:Restriction

OWL classes are not disjoint by default

OWL classes don't have attributes, apart from the annotation properties, providing meta-description, not affecting the members of a class

Although sometimes the concept of "instance" is used, strictly speaking in OWL there is no such thing as instance of a class, as the existence of individuals is not dependant on classes being defined beforehand.

OWL classes can be anonymous, defined through the conditions of classification.

Inference rules can be applied to OWL classes based on DL axioms

OWL classes follow the Open World Assumption

OWL classes can be treated as individuals in OWL2 (aka punning)

Disclaimer: the list is made just on top of my head. It doesn't claim rigour or completeness.


问:
In ion-content change the source of video tag via javascript is not working
Code :

```<code><video  id='play_video' controls="controls"  width="100%" height="100%" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source id='mp4Source' src="" type="video/mp4"/>
 </video>
</code>```

Javascript

```<code>var player = document.getElementById('play_video');
var mp4Vid = document.getElementById('mp4Source');
mp4Vid = "http://scontent-lht6-1.cdninstagram.com/t50.2886-16/10951700_1534409696814630_381716634_n.mp4";
player.load();
player.play();
</code>```

Issue:
video tag is inside ion-content.try to change the src of source tag via javascript is not working. what is the solution for this??

答:
You have to set the src attribute of the element:

var player = document.getElementById('play_video');
var mp4Vid = document.getElementById('mp4Source');

mp4Vid.src = "http://scontent-lht6-1.cdninstagram.com/t50.2886-16/10951700_1534409696814630_381716634_n.mp4";
player.load();
player.play();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id='play_video' controls="controls" width="100%" height="100%" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source id='mp4Source' src="" type="video/mp4"/>
 </video></code>```

Body:
Code :

<video  id='play_video' controls="controls"  width="100%" height="100%" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source id='mp4Source' src="" type="video/mp4"/>
 </video>

Javascript

var player = document.getElementById('play_video');
var mp4Vid = document.getElementById('mp4Source');
mp4Vid = "http://scontent-lht6-1.cdninstagram.com/t50.2886-16/10951700_1534409696814630_381716634_n.mp4";
player.load();
player.play();

Issue:
video tag is inside ion-content.try to change the src of source tag via javascript is not working. what is the solution for this??

Body:
You have to set the src attribute of the element:

var player = document.getElementById('play_video');
var mp4Vid = document.getElementById('mp4Source');

mp4Vid.src = "http://scontent-lht6-1.cdninstagram.com/t50.2886-16/10951700_1534409696814630_381716634_n.mp4";
player.load();
player.play();

<video id='play_video' controls="controls" width="100%" height="100%" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source id='mp4Source' src="" type="video/mp4"/>
 </video>


问:
How to add "No Record Found" in PrimeNG Datatable When data is not there?
I searched on primeNG official site, and I found that there is no such attribute like emptyMessage= "No Record Found" for data table in PrimeNG
ref.http://www.primefaces.org/primeng/#/datatable

So when there was no data in my data table, It is not showing me any message.

```<code><p-dataTable  #datatable [value]="jobData" [rows]="20" [paginator]="true"
            [responsive]="true" selectionMode="single"><--emptyMessage="" not working here as attribute :(
    <p-column expander="true" styleClass="icon"></p-column>
            <p-column field="finOrVin" styleClass="vinfin" header="header" sortable="custom" (sortFunction)="sort($event)">
            <p-column field="state"  styleClass="status" header="Status"  sortable="custom" (sortFunction)="sort($event)">
            </p-column>
    </p-dataTable>
</code>```

答:
The Datatable takes a variable of type string for this attribute:

```<code><p-dataTable ... [emptyMessage]="myVariable" ...>
</code>```

And the controller puts the string into the variable (i.e. using ngx-translate):

```<code>class ... {
    public myVariable;
    ngOnInit() {
        this.translateService.get('MY_TRANSLATION').subscribe(
            (translationString) => {
                this.myVariable = translationString;
            }
        );
    ...
}
</code>```

EDIT:
I came across the solution to do it directly in the template.
(omit the brackets for the attribute):

```<code>emptyMessage="{{ 'MY_TRANSLATION' | translate }}"
</code>```

Body:
I searched on primeNG official site, and I found that there is no such attribute like emptyMessage= "No Record Found" for data table in PrimeNG
ref.http://www.primefaces.org/primeng/#/datatable

So when there was no data in my data table, It is not showing me any message.

<--emptyMessage="" not working here as attribute :(

Body:
The Datatable takes a variable of type string for this attribute:

<p-dataTable ... [emptyMessage]="myVariable" ...>

And the controller puts the string into the variable (i.e. using ngx-translate):

class ... {
    public myVariable;
    ngOnInit() {
        this.translateService.get('MY_TRANSLATION').subscribe(
            (translationString) => {
                this.myVariable = translationString;
            }
        );
    ...
}

EDIT:
I came across the solution to do it directly in the template.
(omit the brackets for the attribute):

emptyMessage="{{ 'MY_TRANSLATION' | translate }}"


问:
what does <_io.TextIOWrapper name='canc.csv' mode='r' encoding='cp1252'> error mean in python?
I want to open a CSV file in python, but I am getting this error again and again. This is my code:</p>

```<code>import csv
with open("canc.csv","r") as csvFile:
  reader = csv.reader(csvFile)
  data = []
  for row in reader:
     if len(row) !=0:
        data = data + [row]
csvFile.close()
print(csvFile)`
</code>```

答:
In your code, csvFile is a file, not the contents, which you read into data

In fact, as print has told you it's an TExtIOWrapper, with a name, mode and encoding: <_io.TextIOWrapper name='canc.csv' mode='r' encoding='cp1252'>

If you want to see the data in the file, simply use

```<code>print(data)
</code>```

Body:
I want to open a CSV file in python, but I am getting this error again and again. This is my code:

import csv
with open("canc.csv","r") as csvFile:
  reader = csv.reader(csvFile)
  data = []
  for row in reader:
     if len(row) !=0:
        data = data + [row]
csvFile.close()
print(csvFile)`

Body:
In your code, csvFile is a file, not the contents, which you read into data

In fact, as print has told you it's an TExtIOWrapper, with a name, mode and encoding: <_io.TextIOWrapper name='canc.csv' mode='r' encoding='cp1252'>

If you want to see the data in the file, simply use

print(data)


问:
How to make a query with FILTER clause run faster?
I have the following SQL which takes 5.6 to 6 seconds to run

```<code>SELECT COUNT(DISTINCT keyword_id) FILTER (WHERE rank>50 OR rank is null) AS "50+",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 21 AND 50) AS "21-50",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 11 AND 20) AS "11-20",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 4 AND 10) AS "4-10",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 1 AND 3) AS "1-3",
  date_trunc('month', rank_date) AS date
  FROM keyword_ranks, keywords
  WHERE keywords.deleted_at IS NULL
  AND keywords.id=keyword_ranks.keyword_id
  AND keywords.business_id=27 GROUP BY date_trunc('month', rank_date);
</code>```

could you please help me to optimize this query so that it will run faster? Thank you

EDIT

keyword_ranks schema

```<code>  create_table "keyword_ranks", force: :cascade do |t|
    t.integer  "rank"
    t.integer  "charge"
    t.text     "dom"
    t.integer  "keyword_id"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.string   "volume"
    t.string   "cmc"
    t.integer  "all_time_service_change"
    t.integer  "all_time_cost_change"
    t.integer  "this_month_service_change"
    t.integer  "this_month_cost_change"
    t.integer  "last_30_days_service_change"
    t.integer  "last_30_days_cost_change"
    t.integer  "last_sevendays_service_change"
    t.integer  "last_sevendays_cost_change"
    t.datetime "service_callback_updated_at"
    t.datetime "cost_callback_updated_at"
    t.json     "service_raw_data"
    t.json     "cost_raw_data"
  end

  add_index "keyword_ranks", ["keyword_id"], name: "index_keyword_ranks_on_keyword_id", using: :btree
  add_index "keyword_ranks", ["rank_date"], name: "rank_date_index", using: :btree
</code>```

execution plan

```<code>"        Sort Method: external sort  Disk: 1808kB"
"        ->  Hash Join  (cost=93.73..158335.35 rows=110023 width=12) (actual time=2.546..5605.758 rows=99149 loops=1)"
"              Output: keyword_ranks.rank_date, keyword_ranks.keyword_id, keyword_ranks.rank"
"              Hash Cond: (keyword_ranks.keyword_id = keywords.id)"
"              ->  Seq Scan on public.keyword_ranks  (cost=0.00..151022.92 rows=1631592 width=12) (actual time=0.236..5177.327 rows=1631592 loops=1)"
"                    Output: keyword_ranks.id, keyword_ranks.rank, keyword_ranks.charge, keyword_ranks.dom, keyword_ranks.rank_date, key (...)"
"              ->  Hash  (cost=84.78..84.78 rows=716 width=4) (actual time=2.200..2.200 rows=714 loops=1)"
"                    Output: keywords.id"
"                    Buckets: 1024  Batches: 1  Memory Usage: 34kB"
"                    ->  Bitmap Heap Scan on public.keywords  (cost=17.83..84.78 rows=716 width=4) (actual time=1.218..2.080 rows=714 loops=1)"
"                          Output: keywords.id"
"                          Recheck Cond: ((keywords.business_id = 27) AND (keywords.deleted_at IS NULL))"
"                          Heap Blocks: exact=41"
"                          ->  Bitmap Index Scan on business_id_index  (cost=0.00..17.66 rows=716 width=0) (actual time=0.767..0.767 rows=714 loops=1)"
"                                Index Cond: (keywords.business_id = 27)"
</code>```

答:
The query looks fine as is.

I'd recommend a partial index for it:

```<code>CREATE INDEX idx ON keywords (business_id) WHERE deleted_at IS NULL;
</code>```

Body:
I have the following SQL which takes 5.6 to 6 seconds to run

SELECT COUNT(DISTINCT keyword_id) FILTER (WHERE rank>50 OR rank is null) AS "50+",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 21 AND 50) AS "21-50",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 11 AND 20) AS "11-20",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 4 AND 10) AS "4-10",
  COUNT(DISTINCT keyword_id) FILTER (WHERE rank BETWEEN 1 AND 3) AS "1-3",
  date_trunc('month', rank_date) AS date
  FROM keyword_ranks, keywords
  WHERE keywords.deleted_at IS NULL
  AND keywords.id=keyword_ranks.keyword_id
  AND keywords.business_id=27 GROUP BY date_trunc('month', rank_date);

could you please help me to optimize this query so that it will run faster? Thank you

EDIT

keyword_ranks schema

  create_table "keyword_ranks", force: :cascade do |t|
    t.integer  "rank"
    t.integer  "charge"
    t.text     "dom"
    t.integer  "keyword_id"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.string   "volume"
    t.string   "cmc"
    t.integer  "all_time_service_change"
    t.integer  "all_time_cost_change"
    t.integer  "this_month_service_change"
    t.integer  "this_month_cost_change"
    t.integer  "last_30_days_service_change"
    t.integer  "last_30_days_cost_change"
    t.integer  "last_sevendays_service_change"
    t.integer  "last_sevendays_cost_change"
    t.datetime "service_callback_updated_at"
    t.datetime "cost_callback_updated_at"
    t.json     "service_raw_data"
    t.json     "cost_raw_data"
  end

  add_index "keyword_ranks", ["keyword_id"], name: "index_keyword_ranks_on_keyword_id", using: :btree
  add_index "keyword_ranks", ["rank_date"], name: "rank_date_index", using: :btree

execution plan

"        Sort Method: external sort  Disk: 1808kB"
"        ->  Hash Join  (cost=93.73..158335.35 rows=110023 width=12) (actual time=2.546..5605.758 rows=99149 loops=1)"
"              Output: keyword_ranks.rank_date, keyword_ranks.keyword_id, keyword_ranks.rank"
"              Hash Cond: (keyword_ranks.keyword_id = keywords.id)"
"              ->  Seq Scan on public.keyword_ranks  (cost=0.00..151022.92 rows=1631592 width=12) (actual time=0.236..5177.327 rows=1631592 loops=1)"
"                    Output: keyword_ranks.id, keyword_ranks.rank, keyword_ranks.charge, keyword_ranks.dom, keyword_ranks.rank_date, key (...)"
"              ->  Hash  (cost=84.78..84.78 rows=716 width=4) (actual time=2.200..2.200 rows=714 loops=1)"
"                    Output: keywords.id"
"                    Buckets: 1024  Batches: 1  Memory Usage: 34kB"
"                    ->  Bitmap Heap Scan on public.keywords  (cost=17.83..84.78 rows=716 width=4) (actual time=1.218..2.080 rows=714 loops=1)"
"                          Output: keywords.id"
"                          Recheck Cond: ((keywords.business_id = 27) AND (keywords.deleted_at IS NULL))"
"                          Heap Blocks: exact=41"
"                          ->  Bitmap Index Scan on business_id_index  (cost=0.00..17.66 rows=716 width=0) (actual time=0.767..0.767 rows=714 loops=1)"
"                                Index Cond: (keywords.business_id = 27)"

Body:
The query looks fine as is.

I'd recommend a partial index for it:

CREATE INDEX idx ON keywords (business_id) WHERE deleted_at IS NULL;


问:
Saving data to a file vs. saving it to MySQL DB
Using a PHP script I need to update a number every 5 seconds while somebody is on my page. So let's say I have 300 visitors, each one spending about 1 minute on the page and every 5 seconds they stay on the page the number will be changed...which is a total of 3600 changes per minute. I would prefer to update the number in my MySQL database, except I'm not sure if it's not too inefficient to have so many MySQL connections (just for the one number change), when I could just change the number in a file.

P.S.: I have no idea weather 3600 connections/minute is a high number or not, but what about this case in general, considering an even higher number of visitors. What is the most efficient way to do this?

答:
files aren't transactional and you don't want to lose count so the database is the way to go

memcached's inc command is faster then the database and was the basis of i think one really fast view counting setup

if you use say a key per hour and switch so when a page view happens inc page:time occurs and you can have a process in the background collect the counts from the past hour and insert them in a database if the memcache fails you might lose the count for that hour but you will not have double counted or missed any and keeping counts per period gives interesting statistics


问:
office access substrac values from each row in one field
Please help, how to substract values in one field from one row to another, for example:

I want it become like this:

答:
This Question is not very clear but I've given what you have asked for.
This will place the first total in the row with NO = 1 and then will reduce that total as NO increases.

```<code>(Select Total from table1 where Date1 = (Select Min(NO) from Table1))-IIf([No]=1,0,(DSum("[Total]","[Table1]","[NO]<=" & [NO] & " AND [NO]<>1")))
</code>```

Add this as the last column in a query on your table. You will have to replace "Table1" with your table name and you should really change the column names to be something different than NO and Date as these are used for other things in Access.

Body:
This Question is not very clear but I've given what you have asked for.
This will place the first total in the row with NO = 1 and then will reduce that total as NO increases.

(Select Total from table1 where Date1 = (Select Min(NO) from Table1))-IIf([No]=1,0,(DSum("[Total]","[Table1]","[NO]<=" & [NO] & " AND [NO]<>1")))

Add this as the last column in a query on your table. You will have to replace "Table1" with your table name and you should really change the column names to be something different than NO and Date as these are used for other things in Access.


问:
bind kendo dropdown from ajax post result
I have been searching it for many hours but did not get any solution yet.

here is the kendo dropdown

```<code> <div id="formMain" class="at-form>
  <span data-name="ERP_DimensionCodesList" id="ERP_DimensionCodesList" data-type="picklist"></span>
</div>
</code>```

here is ajax call

```<code>  window.Page.Data.getDimensionCodeList = function (dimension, company) {
            window.Page.get(
                "/api/ERPIntegrationDimensionSetup/GetDimensionCodeList"
                , { dimension: dimension, company: company }
                , window.Page.Data.dataReceivedDimension
            );
        }
        window.Page.Data.dataReceivedDimension = function (data) {
            debugger;
 var dataSource = [];
            for (i = 0; i < data.length; i++) {
                dataSource.push({ text: data[i].ListID, value: data[i].ListName })
            };
            $("#ERP_DimensionCodesList").kendoDropDownList({
                dataTextField: "text",
                dataValueField: "value",
                dataSource: dataSource
            });
}
</code>```

As shown in picture above, data is not empty but it is not binding data in drop down. How to achieve it? any help would be appreciated.

答:
I think, the problem is your dataTextField & dataValueField declarations.
Setting dataSource is not enough. You should declare your dataTextField and dataValueField according to your object properties.
In your case it should be like this:</p>

```<code>..
dataTextField:"ListName",
dataValueField: "ListID",
..
</code>```

Body:
I have been searching it for many hours but did not get any solution yet.

here is the kendo dropdown

here is ajax call

  window.Page.Data.getDimensionCodeList = function (dimension, company) {
            window.Page.get(
                "/api/ERPIntegrationDimensionSetup/GetDimensionCodeList"
                , { dimension: dimension, company: company }
                , window.Page.Data.dataReceivedDimension
            );
        }
        window.Page.Data.dataReceivedDimension = function (data) {
            debugger;
 var dataSource = [];
            for (i = 0; i < data.length; i++) {
                dataSource.push({ text: data[i].ListID, value: data[i].ListName })
            };
            $("#ERP_DimensionCodesList").kendoDropDownList({
                dataTextField: "text",
                dataValueField: "value",
                dataSource: dataSource
            });
}

As shown in picture above, data is not empty but it is not binding data in drop down. How to achieve it? any help would be appreciated.

Body:
I think, the problem is your dataTextField & dataValueField declarations.
Setting dataSource is not enough. You should declare your dataTextField and dataValueField according to your object properties.
In your case it should be like this:

..
dataTextField:"ListName",
dataValueField: "ListID",
..


问:
javascript - grouping objects by properties
my question is somewhat similar to javascript | Object grouping .

my input obj is

```<code>[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]
</code>```

and my required output is

```<code> [
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  }

]
</code>```

when i tried to implement the answer ,i got

```<code>[[[object Object] {
  group: "Technical detals",
  id: "60",
  name: "Display",
  value: "4"
}, [object Object] {
  group: "Technical detals",
  id: "37",
  name: "OS",
  value: "Apple iOS"
}], [[object Object] {
  group: "Manufacturer",
  id: "58",
  name: "Manufacturer",
  value: "Apple"
}]]
</code>```

i don't want to group my objects with same property into a single array .  i couldn't find out where they are pushing it into array. help me to Fix it :(

答:
You could group the items and the concat all groups in a single array.

It works by generating an object with the group as property an the items as items in the array.

In the next step, the object's values are taken and a new array is generated by concatination of the items with Array#reduce.

```<code>{                                                                              // hash
    "Technical detals": [
        {
            name: "Display",
            group: "Technical detals",
            id: "60",
            value: "4"
        },
        {
            name: "OS",
            group: "Technical detals",
            id: "37",
            value: "Apple iOS"
        }
    ],
    Manufacturer: [
        {
            name: "Manufacturer",
            group: "Manufacturer",
            id: "58",
            value: "Apple"
        }
    ]
}
</code>```

var data = [{ name: "Display", group: "Technical detals", id: "60", value: "4" }, { name: "Manufacturer", group: "Manufacturer", id: "58", value: "Apple" }, { name: "OS", group: "Technical detals", id: "37", value: "Apple iOS" }],
    groups = Object.create(null),
    result = [];

data.forEach(function (a) {
    groups[a.group] = groups[a.group] || [];
    groups[a.group].push(a);
});

result = Object.keys(groups).reduce(function (r, k) {
    return r.concat(groups[k]);
}, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Or just sort by group.

var data = [{ name: "Display", group: "Technical detals", id: "60", value: "4" }, { name: "Manufacturer", group: "Manufacturer", id: "58", value: "Apple" }, { name: "OS", group: "Technical detals", id: "37", value: "Apple iOS" }];

data.sort(function (a, b) {
    return a.group.localeCompare(b.group);
});

console.log(data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
my question is somewhat similar to javascript | Object grouping .

my input obj is

[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]

and my required output is

 [
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  }

]

when i tried to implement the answer ,i got

[[[object Object] {
  group: "Technical detals",
  id: "60",
  name: "Display",
  value: "4"
}, [object Object] {
  group: "Technical detals",
  id: "37",
  name: "OS",
  value: "Apple iOS"
}], [[object Object] {
  group: "Manufacturer",
  id: "58",
  name: "Manufacturer",
  value: "Apple"
}]]

i don't want to group my objects with same property into a single array .  i couldn't find out where they are pushing it into array. help me to Fix it :(

Body:
You could group the items and the concat all groups in a single array.

It works by generating an object with the group as property an the items as items in the array.

In the next step, the object's values are taken and a new array is generated by concatination of the items with Array#reduce.

{                                                                              // hash
    "Technical detals": [
        {
            name: "Display",
            group: "Technical detals",
            id: "60",
            value: "4"
        },
        {
            name: "OS",
            group: "Technical detals",
            id: "37",
            value: "Apple iOS"
        }
    ],
    Manufacturer: [
        {
            name: "Manufacturer",
            group: "Manufacturer",
            id: "58",
            value: "Apple"
        }
    ]
}

var data = [{ name: "Display", group: "Technical detals", id: "60", value: "4" }, { name: "Manufacturer", group: "Manufacturer", id: "58", value: "Apple" }, { name: "OS", group: "Technical detals", id: "37", value: "Apple iOS" }],
    groups = Object.create(null),
    result = [];

data.forEach(function (a) {
    groups[a.group] = groups[a.group] || [];
    groups[a.group].push(a);
});

result = Object.keys(groups).reduce(function (r, k) {
    return r.concat(groups[k]);
}, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

Or just sort by group.

var data = [{ name: "Display", group: "Technical detals", id: "60", value: "4" }, { name: "Manufacturer", group: "Manufacturer", id: "58", value: "Apple" }, { name: "OS", group: "Technical detals", id: "37", value: "Apple iOS" }];

data.sort(function (a, b) {
    return a.group.localeCompare(b.group);
});

console.log(data);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How can I avoid JS and use only CSS?
After several test, I haven't been able to do what I want to do with a pure css. How can I obtain the same result like the example below without using a javascript.

Is it possible to do that with a pure css?

Thanks.

jsfiddle Demo

var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {
 var height = main[i].childNodes[3].offsetHeight;
 main[i].style.height = height+"px";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}</code>```

```

答:
You can use flexbox to do that, just add display: flex;align-items: center; to .container

and remove the position: absolute and transform translate stuff and you get a clean CSS

.container {
  background: yellow;
  margin-bottom: 10px;
  display: flex;             /* added property */
  align-items: center;       /* added property */
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div></code>```

Title: How can I avoid JS and use only CSS?

Body:
After several test, I haven't been able to do what I want to do with a pure css. How can I obtain the same result like the example below without using a javascript.

Is it possible to do that with a pure css?

Thanks.

jsfiddle Demo

var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {
 var height = main[i].childNodes[3].offsetHeight;
 main[i].style.height = height+"px";
}

.container {
  width: 100%;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}

Body:
You can use flexbox to do that, just add display: flex;align-items: center; to .container

and remove the position: absolute and transform translate stuff and you get a clean CSS

.container {
  background: yellow;
  margin-bottom: 10px;
  display: flex;             /* added property */
  align-items: center;       /* added property */
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
}

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>


问:
In UI automator viewer Error Obtaining Device screenshot, Reason : Error Unable to connect to adb. Check if adb is installed correctly
When I click on UI Automator viewer --> Device screenshot throws Error Unable to connect to adb. Check if adb is installed correctly.

I am trying to run it Appium. I am able to load the apk in the emulator, stuck on the UI Automator viewer due to the adb connection error.

答:
Another fix is to just copy adb.exe next to the uiautomatorviewer.bat.

If I remember correctly, modified files can confuse Android Studio when updating SDK, so you have to manually delete in order to successfully update, meaning more future proof solution. Example: link


问:
autocomplete to populate all values on input focus
I have autocomplete textbox whose values are populated using ajax call which returns json data. This works fine with following code lines.

```<code>$("#searchTitle").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/umbraco/Surface/MyApp/StartSearch",
            type: "POST", dataType: "json",
            data: { term: request.term },
            success: function (data) {
                debugger
                response($.map(data, function (item) {
                    debugger
                    return { label: item.Cat_Name };
                }));
            }
        });
    },
    messages: { noResults: "", results: "" },
    minLength: 0
});
</code>```

But this function gets called when user type something. Now, I want that when input is focused, all the values from response should be shown in autocomplete. How can I trigger the same?

答:
You can achieve by using search event of autocomplete on focus of input.

For example

```<code>$( "#searchTitle" ).focus(function() {
    // make sure you put space between double quote
    $( "#searchTitle" ).autocomplete("search", " " );
});
</code>```

Body:
I have autocomplete textbox whose values are populated using ajax call which returns json data. This works fine with following code lines.

$("#searchTitle").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/umbraco/Surface/MyApp/StartSearch",
            type: "POST", dataType: "json",
            data: { term: request.term },
            success: function (data) {
                debugger
                response($.map(data, function (item) {
                    debugger
                    return { label: item.Cat_Name };
                }));
            }
        });
    },
    messages: { noResults: "", results: "" },
    minLength: 0
});

But this function gets called when user type something. Now, I want that when input is focused, all the values from response should be shown in autocomplete. How can I trigger the same?

Body:
You can achieve by using search event of autocomplete on focus of input.

For example

$( "#searchTitle" ).focus(function() {
    // make sure you put space between double quote
    $( "#searchTitle" ).autocomplete("search", " " );
});


问:
Test if an element is present using Selenium WebDriver
Is there a way how to test if an element is present? Any findElement method would end in an exception, but that is not what I want, because it can be that an element is not present and that is okay. That is not a fail of the test, so an exception can not be the solution.

I've found this post: Selenium C# WebDriver: Wait until element is present.

But this is for C#, and I am not very good at it. What would the code be in Java? I tried it out in Eclipse, but I didn't get it right into Java code.

This is the code:

```<code>public static class WebDriverExtensions{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){

        if (timeoutInSeconds > 0){
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }

        return driver.FindElement(by);
    }
}
</code>```

答:
```<code>public boolean isElementDisplayed() {
    return !driver.findElements(By.xpath("...")).isEmpty();
}
</code>```

Body:
Is there a way how to test if an element is present? Any findElement method would end in an exception, but that is not what I want, because it can be that an element is not present and that is okay. That is not a fail of the test, so an exception can not be the solution.

I've found this post: Selenium C# WebDriver: Wait until element is present.

But this is for C#, and I am not very good at it. What would the code be in Java? I tried it out in Eclipse, but I didn't get it right into Java code.

This is the code:

public static class WebDriverExtensions{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){

        if (timeoutInSeconds > 0){
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }

        return driver.FindElement(by);
    }
}


答:
```<code>var player = document.getElementById('play_video');
var mp4Vid = document.getElementById('mp4Source');

mp4Vid.src = "http://scontent-lht6-1.cdninstagram.com/t50.2886-16/10951700_1534409696814630_381716634_n.mp4";

player.load();
player.play();
</code>```

Title: In ion-content change the source of video tag via javascript is not working

Body:
Code :

<video  id='play_video' controls="controls"  width="100%" height="100%" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source id='mp4Source' src="" type="video/mp4"/>
 </video>

Javascript

var player = document.getElementById('play_video');
var mp4Vid = document.getElementById('mp4Source');
mp4Vid = "http://scontent-lht6-1.cdninstagram.com/t50.2886-16/10951700_1534409696814630_381716634_n.mp4";
player.load();
player.play();

Issue:
video tag is inside ion-content.try to change the src of source tag via javascript is not working. what is the solution for this??


答:
Another way:

```<code>.container {
  width: 100%;
  background: yellow;
  overflow:hidden;
  margin-bottom: 10px;
}
.left-child {
  margin-top:30px;
  width: 40%;
  height: 120px;
  background: red;
  float:left;
}
.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  float:right;
}
</code>```

https://jsfiddle.net/ghdzy57w/14/

Title: How can I avoid JS and use only CSS?

Body:
Another way:

.container {
  width: 100%;
  background: yellow;
  overflow:hidden;
  margin-bottom: 10px;
}
.left-child {
  margin-top:30px;
  width: 40%;
  height: 120px;
  background: red;
  float:left;
}
.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  float:right;
}

https://jsfiddle.net/ghdzy57w/14/


问:
MVC Session Variables in ApplicationDbContext
How to use Session Variables in the ApplicationDbContext constructor. I want to pass 2nd parameter of the constructor from Session variable.

```<code> public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
    {
 public ApplicationDbContext(string schemaname, string connString = HttpContext.Current.Session["ConnString"].ToString())
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }
</code>```

}

It gives me error at HttpContext that 'HttpContext does not exist in the current context'. Even if i have the namespace already added for this class.

答:
Default value for parameter should be compile-time constant (should be known at compile time). HttpContext.Current.Session["ConnString"].ToString() of course cannot be known at compile time, so you cannot use it as default value for connString parameter.

What you can do is create another contstructor:

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable {
    public ApplicationDbContext(string schemaname, string connString)
        : base(connString) {
        SchemaName = schemaname;
        ((IObjectContextAdapter) this).ObjectContext.CommandTimeout = 180;
    }

    public ApplicationDbContext(string schemaname)
       : this(schemaname, HttpContext.Current.Session["ConnString"].ToString())
    {
    }
}
</code>```

Body:
How to use Session Variables in the ApplicationDbContext constructor. I want to pass 2nd parameter of the constructor from Session variable.

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
    {
 public ApplicationDbContext(string schemaname, string connString = HttpContext.Current.Session["ConnString"].ToString())
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

}

It gives me error at HttpContext that 'HttpContext does not exist in the current context'. Even if i have the namespace already added for this class.

Body:
Default value for parameter should be compile-time constant (should be known at compile time). HttpContext.Current.Session["ConnString"].ToString() of course cannot be known at compile time, so you cannot use it as default value for connString parameter.

What you can do is create another contstructor:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable {
    public ApplicationDbContext(string schemaname, string connString)
        : base(connString) {
        SchemaName = schemaname;
        ((IObjectContextAdapter) this).ObjectContext.CommandTimeout = 180;
    }

    public ApplicationDbContext(string schemaname)
       : this(schemaname, HttpContext.Current.Session["ConnString"].ToString())
    {
    }
}


问:
Run ruby script and assign to var Groovy/Jenkins
Probably something simple but don't seem to be getting the output i want, but say i have a ruby script

```<code>class SlackNames

def developers
  { "Richard Lewis" => "/@richlewis",
    "Name 2" => "/@name2",
    "Name 3" => "/@name3"
  }
end

def slack_handle
 puts developers["#{ARGV[0]}"] if developers.key?("#{ARGV[0]}")
end

end

SlackNames.new.slack_handle
</code>```

I would run this on the command line

```<code>ruby slack_names.rb "Richard Lewis"
</code>```

Which as you can see will just return a keys given value, when i run this in a Groovy script how can i save that value to a variable?

```<code>-- Groovy
-- DEV_NAME here equals "Richard Lewis"

SLACK_NAME = sh """#!/bin/bash -l
                   ruby ruby_scripts/slack_names.rb \"${DEV_NAME}\"
                """
echo "${SLACK_NAME}"
</code>```

When i echo out SLACK_NAME it comes back as blank

What am i doing wrong here ?

Thanks

答:
Just to add to CookieNinjas answer once i added this in groovy everything works as expected</p>

```<code>SLACK_NAME = sh (
             script: """#!/bin/bash -l
                        ruby ruby_scripts/slack_names.rb \"${DEV_NAME}\"
                     """,
             returnStdout: true
)
</code>```

Body:
Probably something simple but don't seem to be getting the output i want, but say i have a ruby script

class SlackNames

def developers
  { "Richard Lewis" => "/@richlewis",
    "Name 2" => "/@name2",
    "Name 3" => "/@name3"
  }
end

def slack_handle
 puts developers["#{ARGV[0]}"] if developers.key?("#{ARGV[0]}")
end

end

SlackNames.new.slack_handle

I would run this on the command line

ruby slack_names.rb "Richard Lewis"

Which as you can see will just return a keys given value, when i run this in a Groovy script how can i save that value to a variable?

-- Groovy
-- DEV_NAME here equals "Richard Lewis"

SLACK_NAME = sh """#!/bin/bash -l
                   ruby ruby_scripts/slack_names.rb \"${DEV_NAME}\"
                """
echo "${SLACK_NAME}"

When i echo out SLACK_NAME it comes back as blank

What am i doing wrong here ?

Thanks

Body:
Just to add to CookieNinjas answer once i added this in groovy everything works as expected

SLACK_NAME = sh (
             script: """#!/bin/bash -l
                        ruby ruby_scripts/slack_names.rb \"${DEV_NAME}\"
                     """,
             returnStdout: true
)


问:
Full opacity of fill colour
I want to create a filled area chart with Plotly in R.

Reproducible example:

```<code>library(plotly)
library(dplyr)

data <- data.frame(a = c("r","r","r","r","s","s","s","s"),
                   b = c(2,4,6,4,1,3,5,7),
                   c = c(1,2,3,4,1,2,3,4))
data %>%
  plot_ly(x = ~c, y = ~b, split = ~a, type = 'scatter', mode = 'none', fill = 'tozeroy')
</code>```

By default, the fill colours have 50% opacity, but I want them to have 100% opacity. Plotly offers an opacity as well as an alpha parameter, but none of them affects the opacity of the fill colours.

Do I miss anything?

答:
Perhaps you could approach the problem like this:</p>

```<code>data_r <- data[data$a == 'r',]
data_s <- data[data$a == 's',]

plot_ly(x = data_r$c, y = data_r$b, split = data_r$a, type = 'scatter', mode = 'none', fill = 'tozeroy', fillcolor = 'skyblue') %>%
  add_trace(x = data_s$c, y = data_s$b, split = data_s$a, type = 'scatter', mode = 'none', fill = 'tozeroy', fillcolor = 'coral')
</code>```

Title: Full opacity of fill colour

Body:
I want to create a filled area chart with Plotly in R.

Reproducible example:

library(plotly)
library(dplyr)

data <- data.frame(a = c("r","r","r","r","s","s","s","s"),
                   b = c(2,4,6,4,1,3,5,7),
                   c = c(1,2,3,4,1,2,3,4))
data %>%
  plot_ly(x = ~c, y = ~b, split = ~a, type = 'scatter', mode = 'none', fill = 'tozeroy')

By default, the fill colours have 50% opacity, but I want them to have 100% opacity. Plotly offers an opacity as well as an alpha parameter, but none of them affects the opacity of the fill colours.

Do I miss anything?

Body:
Perhaps you could approach the problem like this:

data_r <- data[data$a == 'r',]
data_s <- data[data$a == 's',]

plot_ly(x = data_r$c, y = data_r$b, split = data_r$a, type = 'scatter', mode = 'none', fill = 'tozeroy', fillcolor = 'skyblue') %>%
  add_trace(x = data_s$c, y = data_s$b, split = data_s$a, type = 'scatter', mode = 'none', fill = 'tozeroy', fillcolor = 'coral')


问:
Limit providers while integrating Gigya in iPhone?
I am integrating Gigya in my iphone app. Now it provides 17 providers for access, I want to limit it to just 9 providers. How can I do that?

Has any one integrated it for iPhone? It loads a web view which displays 17 providers in a grouped table format, see here.

答:
```<code> GSAPI *gsAPI // declare this

 gsAPI = [[GSAPI alloc] initWithAPIKey:<API-KEY> viewController:self];  // i kept this in viewDidload

// add this code to have facebook and twitter on provider list

   GSDictionary *pParams5 = [[GSDictionary new] autorelease];
   [pParams5 putStringValue:@"facebook,twitter" forKey:@"enabledProviders"];
   [gsAPI showAddConnectionsUI:pParams5 delegate:self context:nil];

//this method called when login fails
  -(void)gsLoginUIDidFail:(int)errorCode errorMessage:(NSString*)errorMessage context:(id)context{ }

// this method called on successful login
  - (void)  gsLoginUIDidLogin:(NSString*)provider user:(GSDictionary*)user context:(id)context {}
</code>```

Check whether you have valid API

Body:
 GSAPI *gsAPI // declare this

 gsAPI = [[GSAPI alloc] initWithAPIKey:<API-KEY> viewController:self];  // i kept this in viewDidload

// add this code to have facebook and twitter on provider list

   GSDictionary *pParams5 = [[GSDictionary new] autorelease];
   [pParams5 putStringValue:@"facebook,twitter" forKey:@"enabledProviders"];
   [gsAPI showAddConnectionsUI:pParams5 delegate:self context:nil];

//this method called when login fails
  -(void)gsLoginUIDidFail:(int)errorCode errorMessage:(NSString*)errorMessage context:(id)context{ }

// this method called on successful login
  - (void)  gsLoginUIDidLogin:(NSString*)provider user:(GSDictionary*)user context:(id)context {}

Check whether you have valid API


答:
A solution without position : relative or position : absolute

.container {
  width: 100%;
  background: yellow;
  margin-bottom: 10px;
  display: inline-block;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  margin-top: 30px;
  display:inline-block;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  display:inline-block;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left-child">
  </div><!--
  --><div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div><!--
  --><div class="right-child">
  </div>
</div></code>```

Title: How can I avoid JS and use only CSS?

Body:
A solution without position : relative or position : absolute

.container {
  width: 100%;
  background: yellow;
  margin-bottom: 10px;
  display: inline-block;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  margin-top: 30px;
  display:inline-block;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  display:inline-block;
  float: right;
}

<div class="container">
  <div class="left-child">
  </div><!--
  --><div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div><!--
  --><div class="right-child">
  </div>
</div>


问:
How to map java.time.Year and others java.time types using Hibernate
There's hibernate-java8 JAR providing adapters for a couple of classes like Instant, LocalDate, etc., but some classes from java.time, e.g., Year, Month, YearMonth are missing. These classes get stored like an unknown Serializable, which is needlessly wasteful.

Surely I could use an int year instead of Year year, but I don't think, it's a good idea.

It looks like writing the YearJavaDescriptor should be pretty easy, however, I wonder why it's missing. Especially in case of YearMonth, I'd strongly prefer an existing adapter, ist there any? Or am I doing something stupid?

I'm unsure as googling returns nothing.

答: If your JPA provider does not persist a type in a sensible manner (in this case because it is a Java8 class, which was added after JPA 2.1 was approved) then you need to define a JPA 2.1 AttributeConverter to convert it to a standard JPA persistable type (in this case something like java.sql.Date).</p>


问:
How to get parent property in JS object?
Not sure if title is formulated correct, but I have a JS object that looks like:

```<code>parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]
</code>```

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b'  participates in child 1
etc.

I figure it out I have to map the object but not sure how to proceed after that

答:
You can write a function like this one:

```<code>function findTopicByID(id) {
    let findedTopic = {};

    let topics = obj.project.topics;

    topics.map((topic) => {
        if(parseInt(topic.id) === id) findedTopic = topic;
    });

    return findedTopic;
}
</code>```

This function return the finded topic with the corresponding id or an empty object.

Body:
Not sure if title is formulated correct, but I have a JS object that looks like:

parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b'  participates in child 1
etc.

I figure it out I have to map the object but not sure how to proceed after that

Body:
You can write a function like this one:

function findTopicByID(id) {
    let findedTopic = {};

    let topics = obj.project.topics;

    topics.map((topic) => {
        if(parseInt(topic.id) === id) findedTopic = topic;
    });

    return findedTopic;
}

This function return the finded topic with the corresponding id or an empty object.