问:
How to convert dictionary of lists to html table?
I have a dictionary of list. eg :

```<code>result = {
    'a': ['x', 'y', 'z'],
    'b': ['p', 'q', 'r'],
    'c': ['m', 'n', 'o']
}
</code>```

I want a, b and c to be the headings of my table and corresponding lists under that particular column.

I have passed the dictionary to html from cherrypy like this
return tmpl.render(result = result)

Addition:
This is the html code written

```<code><table id="myTable"> {% for k,v in result.items() %}
    <th> {{ k }}</th>
    {% for val in v %}
    <tr>
        <td> {{ val }}</td>
    </tr>
    {% endfor %} {% endfor %}
</table>
</code>```

答:
According to your logic, your code will now do the following (pseudo):

```<code>foreach key & value: add the key as a th,
then loop the value (because it is an array):
   add a new table row with a table cell with that 'nested' value.
</code>```

That will result in the following output:

```<code>a
0
1
2
b
0
1
2
c
0
1
2
</code>```

What you want to do, is (pseudo):

```<code>Create a tr for the headers
Loop all keys: add headers for all keys (a, b and c)
Foreach row (remember i (iterator))
    add a tr
    for each key (col) add value[i] as a td
    Close the tr
Close the table tag
</code>```

I'll do my best writing this in your code (looking at the snippet you provided). Note: haven't tested this.

```<code><table id="myTable">
    <tr>
      {% for k,v in results.items() %}
      <th> {{ k }}</th>
      {% endfor %}
    </tr>
    {% for i in range(0, len(results[a])) %}
    <tr>
      {% for k,v in results.items() %}
      <td>v[i]</td>
      {% endfor %}
    </tr>
    {% endfor %}
</table>
</code>```

There are also libraries which do this for you: https://www.decalage.info/python/html (for example)

Body:
I have a dictionary of list. eg :

result = {
    'a': ['x', 'y', 'z'],
    'b': ['p', 'q', 'r'],
    'c': ['m', 'n', 'o']
}

I want a, b and c to be the headings of my table and corresponding lists under that particular column.

I have passed the dictionary to html from cherrypy like this
return tmpl.render(result = result)

Addition:
This is the html code written

 {% for k,v in result.items() %}
     {{ k }}
    {% for val in v %}

         {{ val }}

    {% endfor %} {% endfor %}

Body:
According to your logic, your code will now do the following (pseudo):

foreach key & value: add the key as a th,
then loop the value (because it is an array):
   add a new table row with a table cell with that 'nested' value.

That will result in the following output:

a
0
1
2
b
0
1
2
c
0
1
2

What you want to do, is (pseudo):

Create a tr for the headers
Loop all keys: add headers for all keys (a, b and c)
Foreach row (remember i (iterator))
    add a tr
    for each key (col) add value[i] as a td
    Close the tr
Close the table tag

I'll do my best writing this in your code (looking at the snippet you provided). Note: haven't tested this.

<table id="myTable">
    <tr>
      {% for k,v in results.items() %}
      <th> {{ k }}</th>
      {% endfor %}
    </tr>
    {% for i in range(0, len(results[a])) %}
    <tr>
      {% for k,v in results.items() %}
      <td>v[i]</td>
      {% endfor %}
    </tr>
    {% endfor %}
</table>

There are also libraries which do this for you: https://www.decalage.info/python/html (for example)


来源: stackexchange

问:
If Statement for Error Checking is not working
I need to do some error checking so a user knows they have missed some information before sending the form.

I have a table which is controlled by a Data Validation list dropdown box. This box has numbers 1 to 15, and will show/hide rows associated to the number selected i.e. 3 selected, so rows 1 to 3 are displayed, 4 to 15 or hidden. What the error checking code is supposed to do is, check the list number selected, then check a cell in each row to see if it is empty or not, if empty display the error message, if not then do nothing. I need this error message to display for each row which is displayed and not for the hidden rows. I have a cell at the top of the page with tells the user how many errors they have, so I don't want the hidden rows adding to this count. I can get it working for numbers zero and 1, but for 2 to 15 it is not working. Code below only shows numbers 0 to 3, I can alter the code for the other rows once working.

Correct outcome when nbr 3 is selected
D63 is empty so error msg in A63, D64:65 not empty so no error msg

Actual outcome when Nbr 3 is selected
D63:65 are empty so A63:65 should display the error msg

```<code>Sub Check_SRU_Table()

    ' SRU 0 ** WORKING **
    If Range("SRUAdd").Value = "0" Then
        Range("Sig_1").Value = "Signature Release 1"
        Range("Sig_2").Value = "Signature Release 2"
        Range("Sig_3").Value = "Signature Release 3"
    ' 4 TO 15 OMITTED
    End If

    ' SRU 1 ** WORKING **
    If Range("SRUAdd").Value = "1" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
        End If
    End If

    ' SRU 2 ** NOT WORKING **
    If Range("SRUAdd").Value = "2" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
        End If
    End If

    ' SRU 3 ** NOT WORKING **
    If Range("SRUAdd").Value = "3" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        ElseIf Range("SRUName3").Value = "" Then
            Range("Sig_3").Value = "Signature Release 3 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
            Range("Sig_3").Value = "Signature Release 3"
        End If
    End If
    End Sub

    Private Sub BtnCheck_Click()
        Check_SRU_Table
    End Sub
</code>```

Any help to figure out where I'm going wrong would be much appreciated.

答:
Your "SRU 2" and "SRU 3" are not working because If ... ElseIf ... ElseIf ... (a.k.a. an if-else-if ladder) will only capture the first error encountered. I think you over-thought it.

```<code>' SRU 2 ** Try something like this **
If Range("SRUAdd").Value = "2" Then
    If Range("SRUName1").Value = "" Then
        Range("Sig_1").Value = "Signature Release 1 - ERROR"
    Else
        Range("Sig_1").Value = "Signature Release 1"
    End If
    If Range("SRUName2").Value = "" Then
        Range("Sig_2").Value = "Signature Release 2 - ERROR"
    Else
        Range("Sig_2").Value = "Signature Release 2"
    End If
End If
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to do some error checking so a user knows they have missed some information before sending the form.

I have a table which is controlled by a Data Validation list dropdown box. This box has numbers 1 to 15, and will show/hide rows associated to the number selected i.e. 3 selected, so rows 1 to 3 are displayed, 4 to 15 or hidden. What the error checking code is supposed to do is, check the list number selected, then check a cell in each row to see if it is empty or not, if empty display the error message, if not then do nothing. I need this error message to display for each row which is displayed and not for the hidden rows. I have a cell at the top of the page with tells the user how many errors they have, so I don't want the hidden rows adding to this count. I can get it working for numbers zero and 1, but for 2 to 15 it is not working. Code below only shows numbers 0 to 3, I can alter the code for the other rows once working.

Correct outcome when nbr 3 is selected
D63 is empty so error msg in A63, D64:65 not empty so no error msg

Actual outcome when Nbr 3 is selected
D63:65 are empty so A63:65 should display the error msg

Sub Check_SRU_Table()

    ' SRU 0 ** WORKING **
    If Range("SRUAdd").Value = "0" Then
        Range("Sig_1").Value = "Signature Release 1"
        Range("Sig_2").Value = "Signature Release 2"
        Range("Sig_3").Value = "Signature Release 3"
    ' 4 TO 15 OMITTED
    End If

    ' SRU 1 ** WORKING **
    If Range("SRUAdd").Value = "1" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
        End If
    End If

    ' SRU 2 ** NOT WORKING **
    If Range("SRUAdd").Value = "2" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
        End If
    End If

    ' SRU 3 ** NOT WORKING **
    If Range("SRUAdd").Value = "3" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        ElseIf Range("SRUName3").Value = "" Then
            Range("Sig_3").Value = "Signature Release 3 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
            Range("Sig_3").Value = "Signature Release 3"
        End If
    End If
    End Sub

    Private Sub BtnCheck_Click()
        Check_SRU_Table
    End Sub

Any help to figure out where I'm going wrong would be much appreciated.

Body:
Your "SRU 2" and "SRU 3" are not working because If ... ElseIf ... ElseIf ... (a.k.a. an if-else-if ladder) will only capture the first error encountered. I think you over-thought it.

' SRU 2 ** Try something like this **
If Range("SRUAdd").Value = "2" Then
    If Range("SRUName1").Value = "" Then
        Range("Sig_1").Value = "Signature Release 1 - ERROR"
    Else
        Range("Sig_1").Value = "Signature Release 1"
    End If
    If Range("SRUName2").Value = "" Then
        Range("Sig_2").Value = "Signature Release 2 - ERROR"
    Else
        Range("Sig_2").Value = "Signature Release 2"
    End If
End If


问:
iText pdfReader Not Releasing File in ColdFusion 2018
I am upgrading to ColdFusion 2018.  iText routines that I use to convert and rotate PDFs,  the pdfReader puts locks on the file that do not release when the page is done.

I have tried adding a close() method to my code.  (It was not needed on the pdfReader in Release 11.)

```<code><cfscript>

reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( "test.pdf" );

reader.close();

inStream = createObject("java", "java.io.FileReader").init("test2.pdf");

inStream.close();

</cfscript>
</code>```

I would expect to be able to rename or delete both files when the supplied script is ran, but only the inStream file (test2.pdf) can be.  The reader file (test.pdf) is locked by the system.

答:
Using the suggestions above, I think the following solution will work.</p>

```<code><cfscript>

    fkeys = createObject("java", "java.io.FileInputStream");
    lKeyStoreFileStream = createObject("java", "java.io.BufferedInputStream").init(fkeys.init("test.pdf"));

    reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( lKeyStoreFileStream );

    lKeyStoreFileStream.close();
    fkeys.close();

    reader.close();

</cfscript>
</code>```

Body:
I am upgrading to ColdFusion 2018.  iText routines that I use to convert and rotate PDFs,  the pdfReader puts locks on the file that do not release when the page is done.

I have tried adding a close() method to my code.  (It was not needed on the pdfReader in Release 11.)

<cfscript>

reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( "test.pdf" );

reader.close();

inStream = createObject("java", "java.io.FileReader").init("test2.pdf");

inStream.close();

</cfscript>

I would expect to be able to rename or delete both files when the supplied script is ran, but only the inStream file (test2.pdf) can be.  The reader file (test.pdf) is locked by the system.

Body:
Using the suggestions above, I think the following solution will work.

<cfscript>

    fkeys = createObject("java", "java.io.FileInputStream");
    lKeyStoreFileStream = createObject("java", "java.io.BufferedInputStream").init(fkeys.init("test.pdf"));

    reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( lKeyStoreFileStream );

    lKeyStoreFileStream.close();
    fkeys.close();

    reader.close();

</cfscript>


问:
Can't replace the footer text in a word application through Delphi
I am trying to replace text in a footer, I am using the following code through which i can replace the normal content (body) but not the content in the footer/header

```<code>myWinWordApp := CreateOLEObject('Word.Application');
myWinWordApp.visible := true;
myWinWordApp.documents.open('c:\ole.doc');
myWinWordApp.Selection.Find.Text :=  'oo';
myWinWordApp.selection.Find.Replacement.Text := 'aa';
myWinWordApp.Selection.Find.Execute(Replace := 2);
</code>```

any help is highly appreciated. Thanks in advance

答:
Made comment into answer:

I would try to set the view to the header/footer mode, maybe by doing something like ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader as shown here.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to replace text in a footer, I am using the following code through which i can replace the normal content (body) but not the content in the footer/header

myWinWordApp := CreateOLEObject('Word.Application');
myWinWordApp.visible := true;
myWinWordApp.documents.open('c:\ole.doc');
myWinWordApp.Selection.Find.Text :=  'oo';
myWinWordApp.selection.Find.Replacement.Text := 'aa';
myWinWordApp.Selection.Find.Execute(Replace := 2);

any help is highly appreciated. Thanks in advance


问:
How to Merge Rows with Same Name SQL Pivot
I am trying to denormalize some data in SQL Server and have been able to successfully pivot a reference table, but would like to be able to merge like rows.

The pivot is executed as follows

```<code>select distinct
'name' = sFname + ' ' + sLname,
advanced,
basic,
standard

from
(select * from dbName..person where deleteFlag <> 'Y') as tableTemp
pivot (
  count(serviceType)
  for serviceType IN (advanced, basic, standard)
) as tablePivot
</code>```

And returns

```<code>name      | advanced | basic | standard
----------+----------+-------+---------
abby a    |     1    |   0   |    0
abby a    |     0    |   1   |    0
charlie c |     0    |   1   |    0
charlie c |     0    |   0   |    1
</code>```

But I would like to return in this form

```<code>name      | advanced | basic | standard
----------+----------+-------+---------
abby a    |     1    |   1   |    0
charlie c |     0    |   1   |    1
</code>```

The original data is structured like

```<code>sFname   | sLname   | serviceType |
---------+----------+-------------+
abby     |     a    |   advanced  |
abby     |     a    |   basic     |
charlie  |     c    |   basic     |
charlie  |     c    |   standard  |
</code>```

How can I run an operation like group by or select distinct to return a consolidated pivoted table in SQL Server?

答:
You need to limit the columns in your subquery before the PIVOT.

```<code>SELECT [name],
       [advanced],
       [basic],
       [standard]
FROM   (
           SELECT 'name' = sFname + ' ' + sLname,
                  serviceType
           FROM   person
           WHERE  deleteFlag <> 'Y'
       ) AS tableTemp
PIVOT(COUNT(serviceType) FOR serviceType IN(advanced, basic, standard)) AS tablePivot;
</code>```

Body:
I am trying to denormalize some data in SQL Server and have been able to successfully pivot a reference table, but would like to be able to merge like rows.

The pivot is executed as follows

select distinct
'name' = sFname + ' ' + sLname,
advanced,
basic,
standard

from
(select * from dbName..person where deleteFlag <> 'Y') as tableTemp
pivot (
  count(serviceType)
  for serviceType IN (advanced, basic, standard)
) as tablePivot

And returns

name      | advanced | basic | standard
----------+----------+-------+---------
abby a    |     1    |   0   |    0
abby a    |     0    |   1   |    0
charlie c |     0    |   1   |    0
charlie c |     0    |   0   |    1

But I would like to return in this form

name      | advanced | basic | standard
----------+----------+-------+---------
abby a    |     1    |   1   |    0
charlie c |     0    |   1   |    1

The original data is structured like

sFname   | sLname   | serviceType |
---------+----------+-------------+
abby     |     a    |   advanced  |
abby     |     a    |   basic     |
charlie  |     c    |   basic     |
charlie  |     c    |   standard  |

How can I run an operation like group by or select distinct to return a consolidated pivoted table in SQL Server?

Body:
You need to limit the columns in your subquery before the PIVOT.

SELECT [name],
       [advanced],
       [basic],
       [standard]
FROM   (
           SELECT 'name' = sFname + ' ' + sLname,
                  serviceType
           FROM   person
           WHERE  deleteFlag <> 'Y'
       ) AS tableTemp
PIVOT(COUNT(serviceType) FOR serviceType IN(advanced, basic, standard)) AS tablePivot;


问:
Homebrew up-to-date, but do I need to worry about `could not link` + `delete path` errors?
I've used homebrew to install rvm and ocaml packages successfully, but I've always wondered about the errors at the end of $ brew update output. For example, when I ran it just now the bash output was:

```<code>Error: Could not link:
/usr/local/etc/bash_completion.d/brew

Please delete these paths and run `brew update`.
Error: Could not link:
/usr/local/share/doc/homebrew

Please delete these paths and run `brew update`.
Error: Could not link:
/usr/local/share/zsh/site-functions/_brew

Please delete these paths and run `brew update`.
Error: Could not link:
/usr/local/share/man/man1/brew-cask.1
/usr/local/share/man/man1/brew.1
</code>```

My colleagues say not to worry about it, but... I worry about it. What can I do to fix them? Just run rm and completely obliterate the "delete me" paths, and mkdir the paths that cannot be linked?

答:
Just try to remove the path which showed on your terminal

$ rm -rf [path]

Example:
$ rm -rf /usr/local/share/doc/homebrew

Body:
I've used homebrew to install rvm and ocaml packages successfully, but I've always wondered about the errors at the end of $ brew update output. For example, when I ran it just now the bash output was:

Error: Could not link:
/usr/local/etc/bash_completion.d/brew

Please delete these paths and run `brew update`.
Error: Could not link:
/usr/local/share/doc/homebrew

Please delete these paths and run `brew update`.
Error: Could not link:
/usr/local/share/zsh/site-functions/_brew

Please delete these paths and run `brew update`.
Error: Could not link:
/usr/local/share/man/man1/brew-cask.1
/usr/local/share/man/man1/brew.1

My colleagues say not to worry about it, but... I worry about it. What can I do to fix them? Just run rm and completely obliterate the "delete me" paths, and mkdir the paths that cannot be linked?


问:
Why is length/2 getting me out of global stack?
when i commit the query:

```<code>?- X in 1..2, length(List,X).
</code>```

the returning results are:

```<code>X = 1, List = [_1260];
X = 2, List = [_1260, _1266];
ERROR: Out of global-stack.
ERROR: No room for exception term. Aborting.
% Execution Aborted
</code>```

i thought this happened cause X isn't grounded, so i ran 3 more queries to see how length/2 bahaves with non-instantiated variables as length:

```<code>?- X in inf..sup, length(List,X).
?- length(List,_).
?- length(List,_X).
</code>```

and all work properly. Thus, if X isn't grounded, after reaching domain's supremum, length/2 crashes. Why is this happening? Shouldn't it return false instead?

答:
Why is this happening? Shouldn't it return false instead?

No, since length/2 is not aware of these bounds, it simply suggests values, and the frozen constraint check each time rejects these values.

The length/2 [swi-doc] can be used in a "constructive" way. Indeed we can generate lists with their corresponding length like:

```<code>?- length(L, N).
L = [],
N = 0 ;
L = [_2316],
N = 1 ;
L = [_2316, _2322],
N = 2 ;
L = [_2316, _2322, _2328],
N = 3
...
</code>```

Now you defined a constraint on N, which means that if you set N to a certain value, the Prolog interpreter will check if that value is in the 1..2 range. For each value with N > 2, that will thus fail. But length/2 of course does not understand this range. It will keep suggesting lists and their corresponding lengths, and that will each time fail.

It is equivalent to:

```<code>?- length(L, N), member(N, [1, 2]).
L = [_2304],
N = 1 ;
L = [_2304, _2310],
N = 2 ;
ERROR: Out of global-stack.
ERROR: No room for exception term. Aborting.
</code>```

Here it makes more sense to do this in reverse, like:

```<code>?- member(N, [1,2]), length(L, N).
N = 1,
L = [_3372] ;
N = 2,
L = [_3372, _3378].
</code>```

Or in case that is not an option try to freeze/2 [swi-doc] the construction of the list until N is known.

Body:
when i commit the query:

?- X in 1..2, length(List,X).

the returning results are:

X = 1, List = [_1260];
X = 2, List = [_1260, _1266];
ERROR: Out of global-stack.
ERROR: No room for exception term. Aborting.
% Execution Aborted

i thought this happened cause X isn't grounded, so i ran 3 more queries to see how length/2 bahaves with non-instantiated variables as length:

?- X in inf..sup, length(List,X).
?- length(List,_).
?- length(List,_X).

and all work properly. Thus, if X isn't grounded, after reaching domain's supremum, length/2 crashes. Why is this happening? Shouldn't it return false instead?

Body:
Why is this happening? Shouldn't it return false instead?

No, since length/2 is not aware of these bounds, it simply suggests values, and the frozen constraint check each time rejects these values.

The length/2 [swi-doc] can be used in a "constructive" way. Indeed we can generate lists with their corresponding length like:

?- length(L, N).
L = [],
N = 0 ;
L = [_2316],
N = 1 ;
L = [_2316, _2322],
N = 2 ;
L = [_2316, _2322, _2328],
N = 3
...

Now you defined a constraint on N, which means that if you set N to a certain value, the Prolog interpreter will check if that value is in the 1..2 range. For each value with N > 2, that will thus fail. But length/2 of course does not understand this range. It will keep suggesting lists and their corresponding lengths, and that will each time fail.

It is equivalent to:

?- length(L, N), member(N, [1, 2]).
L = [_2304],
N = 1 ;
L = [_2304, _2310],
N = 2 ;
ERROR: Out of global-stack.
ERROR: No room for exception term. Aborting.

Here it makes more sense to do this in reverse, like:

?- member(N, [1,2]), length(L, N).
N = 1,
L = [_3372] ;
N = 2,
L = [_3372, _3378].

Or in case that is not an option try to freeze/2 [swi-doc] the construction of the list until N is known.


问:
How do I display multiple divs (and their child elements) as Inline?
I am attempting to display 4 div sections side by side by setting the parent div to:

```<code>.parent {
    display: inline;
}
</code>```

```<code><div class="parent">
        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>

        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>

        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>
</code>```

The 4 divs (with child elements nested) remain stacked as block elements:

```<code>test1
test1
test1
test1
test1
test1
test1
test1
test1
</code>```

But I want them side by side like this - test1 test1 test1

答:
You can use css.

```<code>.parent {
  display: flex;
  flex-direction: row;
}
</code>```

Please use this reference for further details: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
I am attempting to display 4 div sections side by side by setting the parent div to:

.parent {
    display: inline;
}

test1

test1

test1

test1

test1

test1

test1

test1

test1

The 4 divs (with child elements nested) remain stacked as block elements:

test1
test1
test1
test1
test1
test1
test1
test1
test1

But I want them side by side like this - test1 test1 test1

Body:
You can use css.

.parent {
  display: flex;
  flex-direction: row;
}

Please use this reference for further details: https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
Angular (Javascript) how to control the speed of mousemove event?
I am trying to draw on a canvas using mouse move event

You can see the working demo on this blitzy
I am calling this function on mouse move to draw a rectangle

```<code> updateDraw(e: MouseEvent) {

    this.previousCoordinates = this.currentCoordinates;
    this.currentCoordinates = HelloComponent.getCoordinatesOnCanvas(this.canvas.nativeElement, e);
    if (this.drawingMode) {
      HelloComponent.createShape(this.shapes, this.ctx, this.startCoordinates,
        this.currentCoordinates, this.previousCoordinates, true);
      this.endCoordinates = this.currentCoordinates;
    }
  }
</code>```

The problem is that if I move the mouse too fast I get multiple rectangles, ( i am assuming that the clear rectangle doesn't work since mouse move is too fast) how can I avoid this there should be only 1 rectangle in 1 drag draw?

Edit: I want to be able to draw more than 1 rectangle, here I am tracking and clearing previous co ordinates

```<code>  private static createShape(shape: Shapes, context: CanvasRenderingContext2D,
    start: Coordinates, end: Coordinates, prev: Coordinates,
    dotted: boolean) {

    context.clearRect(start.x, start.y, (prev.x - start.x), (prev.y - start.y));
</code>```

答:
StackBlitz

Explanation:

You have the right idea, the problem is that the area you're sending to clearRect doesn't actually include the border. Per the documentation (emphasis mine),

The CanvasRenderingContext2D.strokeRect() method of the Canvas 2D API
  draws a rectangle that is stroked (outlined) according to the current
  strokeStyle and other context settings.

So, to clear the border you actually need to account for the border width when you attempt to clear it.

```<code>const borderWidth = 1;
const x = Math.min(start.x, prev.x) - borderWidth;
const y = Math.min(start.y, prev.y) - borderWidth;
const width = Math.abs(start.x - prev.x) + (2 * borderWidth);
const height = Math.abs(start.y - prev.y) + (2 * borderWidth);

context.clearRect(x, y, width, height);
</code>```

Body:
I am trying to draw on a canvas using mouse move event

You can see the working demo on this blitzy
I am calling this function on mouse move to draw a rectangle

 updateDraw(e: MouseEvent) {

    this.previousCoordinates = this.currentCoordinates;
    this.currentCoordinates = HelloComponent.getCoordinatesOnCanvas(this.canvas.nativeElement, e);
    if (this.drawingMode) {
      HelloComponent.createShape(this.shapes, this.ctx, this.startCoordinates,
        this.currentCoordinates, this.previousCoordinates, true);
      this.endCoordinates = this.currentCoordinates;
    }
  }

The problem is that if I move the mouse too fast I get multiple rectangles, ( i am assuming that the clear rectangle doesn't work since mouse move is too fast) how can I avoid this there should be only 1 rectangle in 1 drag draw?

Edit: I want to be able to draw more than 1 rectangle, here I am tracking and clearing previous co ordinates

  private static createShape(shape: Shapes, context: CanvasRenderingContext2D,
    start: Coordinates, end: Coordinates, prev: Coordinates,
    dotted: boolean) {

    context.clearRect(start.x, start.y, (prev.x - start.x), (prev.y - start.y));

Body:
StackBlitz

Explanation:

You have the right idea, the problem is that the area you're sending to clearRect doesn't actually include the border. Per the documentation (emphasis mine),

The CanvasRenderingContext2D.strokeRect() method of the Canvas 2D API
  draws a rectangle that is stroked (outlined) according to the current
  strokeStyle and other context settings.

So, to clear the border you actually need to account for the border width when you attempt to clear it.

const borderWidth = 1;
const x = Math.min(start.x, prev.x) - borderWidth;
const y = Math.min(start.y, prev.y) - borderWidth;
const width = Math.abs(start.x - prev.x) + (2 * borderWidth);
const height = Math.abs(start.y - prev.y) + (2 * borderWidth);

context.clearRect(x, y, width, height);


问:
How to represent a checkbox with data from two different arrays?
I am trying to render some check boxes with data from two arrays which are the id and name in one array and the count/length in the other array. Ex:

```<code>const count = [[{"1":"91"}],[{"1":"1"}],[{"1":"0"}]]
const type = [{id: "1", name: "iPhone"}, {id: "2",name: "Samsung"}, {id: "3",name: "Huawei"}]
</code>```

I tried to use a map function inside another map function.

```<code>var text=type.map(function(itm,i){
   return [<label key={itm.id}><input type="checkbox" key={itm.id} value={itm.id} name="search"/>{itm.name}</label>, (count && count.length > 0 && count.map( item =>
                      item.length > 0 && item.map( el =>
                          Object.keys(el).length > 0 &&
                          Object.keys(el).map(val => <p>{el[val]}</p>)
                      )
                  )[i])];
}).join(' ');
</code>```

this is how should be represented. [] is the checkbox.

```<code>[] Iphone (91)
[] samsung (1)
[] huawei (0)
</code>```

the link of the example https://stackblitz.com/edit/react-6naael

答:
You can simplify things by first reducing the array of arrays of object into simple array

```<code>const { count } = this.state;
const itemCount = count && count.length > 0 && count.map(c => c[0]["1"])
</code>```

Then we just grab the index when we do Array.map() and read from itemCount

```<code>return (
    <div>
        {type && type.map((type,i) => (
            <label key={type.id}>
                <input
                    type="checkbox"
                    key={type.id}
                    value={type.id}
                    name="search"
                    onChange={this.handleChange}
                    onClick={this.handleFilter}/>

                      {type.name}
                      ({itemCount[i]})
                    </label>
                ))}
    </div>
)

</code>```

Working example https://stackblitz.com/edit/react-184rvv

Body:
I am trying to render some check boxes with data from two arrays which are the id and name in one array and the count/length in the other array. Ex:

const count = [[{"1":"91"}],[{"1":"1"}],[{"1":"0"}]]
const type = [{id: "1", name: "iPhone"}, {id: "2",name: "Samsung"}, {id: "3",name: "Huawei"}]

I tried to use a map function inside another map function.

var text=type.map(function(itm,i){
   return [<input type="checkbox" key={itm.id} value={itm.id} name="search"/>{itm.name}, (count && count.length > 0 && count.map( item =>
                      item.length > 0 && item.map( el =>
                          Object.keys(el).length > 0 &&
                          Object.keys(el).map(val =>
{el[val]}
)
                      )
                  )[i])];
}).join(' ');

this is how should be represented. [] is the checkbox.

[] Iphone (91)
[] samsung (1)
[] huawei (0)

the link of the example https://stackblitz.com/edit/react-6naael

Body:
You can simplify things by first reducing the array of arrays of object into simple array

const { count } = this.state;
const itemCount = count && count.length > 0 && count.map(c => c[0]["1"])

Then we just grab the index when we do Array.map() and read from itemCount

return (
    <div>
        {type && type.map((type,i) => (
            <label key={type.id}>
                <input
                    type="checkbox"
                    key={type.id}
                    value={type.id}
                    name="search"
                    onChange={this.handleChange}
                    onClick={this.handleFilter}/>

                      {type.name}
                      ({itemCount[i]})
                    </label>
                ))}
    </div>
)

Working example https://stackblitz.com/edit/react-184rvv


问:
How to pass three variable to custom template tag?
I am trying to pass 3 variables to my custom filter, but I can’t do it. Is there any such possibility in Django?</p>

```<code>{{ item.cost|pay_blago:'{{item.can_pay_blago_to_currency}}, {{item.rest}}'}}

@register.filter
def pay_blago(cost, args):
    print(args.split(','))
</code>```

答:
Django only allows one parameter. You can send it as a list/tuple and split it inside the filter.

There is a ticket for that too with (wontfix flag)
https://code.djangoproject.com/ticket/1199

Body:
I am trying to pass 3 variables to my custom filter, but I can’t do it. Is there any such possibility in Django?

{{ item.cost|pay_blago:'{{item.can_pay_blago_to_currency}}, {{item.rest}}'}}

@register.filter
def pay_blago(cost, args):
    print(args.split(','))


问:
Parsing input to get specific values
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

```<code>my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}
</code>```

Maybe I should be using a different approach.  Could someone help me, please?

Title: Parsing input to get specific values

Body:
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}

Maybe I should be using a different approach.  Could someone help me, please?

Body:
Another way of doing this :

#!/usr/bin/perl

use strict;

my $str = '[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone';

my $maxval = 0;
my $pattern;
while ( $str =~ /(\[(\d+)\|.+?\])/g)
{
        if ( $maxval < $2 ) {
                $maxval = $2;
                $pattern = $1;
        }
}

print "Maximum value = $maxval and the associate pattern = $pattern \n";
# In this example $maxvalue = 204
# and $pattern = [204|0|{A=9,B=201,C=61,D=11}|Calculator]


问:
Hide Sharepoint 2016 list fields based on User permissions
I have sharepoint 2016 List form . It have a field that we have to hide from users based on SharePoint Groups.
 So far my reaserch have shown that writing a javascript file that will help doing that. It haven't worked. I added the code on NewForm.aspx, EditForm.aspx , NewForm.aspx etc
I have that same thing in SP 2010 but it seems 2016 Sharepoint is designed in different way.</p>

答:
There are many ways to achieve this, depends what your constraints are. The following freeware github code solution works great for me on SharePoint 2016 on prem in new, display and edit forms for a custom list. It was easy to implement and worked first time no issue:

https://davidlozzi.com/2014/01/14/sharepoint-2013-script-hide-or-disable-your-fields/

You need only include jQuery, the author's js file and then this fragment of js in your list forms

```<code>$(document).ready(function(){
  ExecuteOrDelayUntilScriptLoaded(function(){
    Lozzi.Fields.hideWithAllowance("Start Date", ["Project Managers"]);
    Lozzi.Fields.hide("% Complete");
    Lozzi.Fields.show("Title");
  },"sp.js");
});
</code>```

There are several other functions in the library, to disable and disable with permissions.

I went one step further and used CSS to hide the fields so even if the js didn't run the fields would still be hidden:

```<code>table .ms-formtable > tbody > tr:not(#idAttachmentsRow)
{
  display:none;
}
</code>```

But then you need to .show() any fields that aren't restricted by permissions or make the CSS selector more precise which is hard since SharePoint buries the field name in an inner HTML comment rather than putting it in an attribute of the row. But that is separate issue.

Body:
There are many ways to achieve this, depends what your constraints are. The following freeware github code solution works great for me on SharePoint 2016 on prem in new, display and edit forms for a custom list. It was easy to implement and worked first time no issue:

https://davidlozzi.com/2014/01/14/sharepoint-2013-script-hide-or-disable-your-fields/

You need only include jQuery, the author's js file and then this fragment of js in your list forms

$(document).ready(function(){
  ExecuteOrDelayUntilScriptLoaded(function(){
    Lozzi.Fields.hideWithAllowance("Start Date", ["Project Managers"]);
    Lozzi.Fields.hide("% Complete");
    Lozzi.Fields.show("Title");
  },"sp.js");
});

There are several other functions in the library, to disable and disable with permissions.

I went one step further and used CSS to hide the fields so even if the js didn't run the fields would still be hidden:

table .ms-formtable > tbody > tr:not(#idAttachmentsRow)
{
  display:none;
}

But then you need to .show() any fields that aren't restricted by permissions or make the CSS selector more precise which is hard since SharePoint buries the field name in an inner HTML comment rather than putting it in an attribute of the row. But that is separate issue.


问:
Button not being positioned in React Native
My button seems to be not positioned in my react native project. The code that I have looks like this:

```<code><Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />
</code>```

Then in my style sheet I did this :

```<code> centered:{
    position: 'absolute',
    top : 350,
}
</code>```

And it did not work. Some other things that I tried:

```<code>style = {centered}
</code>```

Gives a run-time error saying can not find variable centered

```<code>class = "centered"
</code>```

Does not do anything, either.

According to suggestion, I tried creating a separate View for my button alone, but it gave an error saying JSX expressions must have one parent element. The code I tried:

```<code><View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);
</code>```

Style sheet:

```<code>const styles = StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});
</code>```

答:
If you only want to center your button in the screen, wrap it in a View as specified by Junius.

Looking at your edited question, with code attached. You can return only one element from render method. So you need to wrap those 2 Views in a single parent View

Body:
My button seems to be not positioned in my react native project. The code that I have looks like this:

<Button style = "centered"
      onPress = {() => {Alert.alert('Button tapped!');} }
      title = "Confirm"
    />

Then in my style sheet I did this :

 centered:{
    position: 'absolute',
    top : 350,
}

And it did not work. Some other things that I tried:

style = {centered}

Gives a run-time error saying can not find variable centered

class = "centered"

Does not do anything, either.

According to suggestion, I tried creating a separate View for my button alone, but it gave an error saying JSX expressions must have one parent element. The code I tried:

<View style={styles.container}>
    <Text>Select a time to be notified : </Text>
    <Picker
      style={styles.picker} itemStyle={styles.pickerItem}
      selectedValue={this.state.time}
      onValueChange={(itemValue) => this.setState({time: itemValue})}
    >
    <Picker.Item label="Now" value="now" />
      <Picker.Item label="After 1 minute" value="1min" />
      <Picker.Item label="After 5 minutes" value="5min" />
      <Picker.Item label="Custom time" value="ctime" />
    </Picker>
  </View>
  <View>
    <Button style = {{marginTop:350}}
    onPress = {() => {Alert.alert('Button tapped!');} }
    title = "Confirm"
    />
  </View>
);

Style sheet:

const styles = StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  picker :{
    width: 200,
    height: 44,
    backgroundColor: '#CCE6FF',
    borderColor: 'white',
    borderWidth: 1,
  },

  pickerItem :{
    width: 200,
    height: 88,
    backgroundColor: '#CCE6FF',
    borderColor: 'black',
    borderWidth: 1,
  },

  notificationButton :{
    position: 'absolute',
    top : 50,
  },
});


答:
If you are needing somethinf that's a function of an Item instance, the easiest way is a property defined on Item. In the Template, say,

```<code>{{item.cost_pay_blago}}
</code>```

and on the Item model

```<code># this is needed by template foo/bar.html
@property
def cost_pay_blago( self):

    result = # some value based on self.cost, self.rest and self.can_pay_blago_to_currency
    return  result
</code>```

if item is not a model instance or if the function brings together data from multiple objects, you probably compute it in the view and put it into the context that you render the template against.

Or you could use the Jinja template engine, but that's a very big hammer to use if it's a small nut.

Title: How to pass three variable to custom template tag?

Body:
If you are needing somethinf that's a function of an Item instance, the easiest way is a property defined on Item. In the Template, say,

{{item.cost_pay_blago}}

and on the Item model

# this is needed by template foo/bar.html
@property
def cost_pay_blago( self):

    result = # some value based on self.cost, self.rest and self.can_pay_blago_to_currency
    return  result

if item is not a model instance or if the function brings together data from multiple objects, you probably compute it in the view and put it into the context that you render the template against.

Or you could use the Jinja template engine, but that's a very big hammer to use if it's a small nut.


问:
The provider is not compatible with the version of Oracle client
I'm trying to use the Oracle ODP.NET 11g (11.1.0.6.20) Instant Client on my ASP.net project as a Data Provider but when I run the aspx page I get a "The provider is not compatible with the version of Oracle client" error message.  Any help would be appreciated.

I've referenced the Data Provider in Visual Studio 2005 and the code behind looks like this:

```<code>using Oracle.DataAccess.Client;
..

OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString =
    "Data Source=MyOracleServerName;" +
    "Integrated Security=SSPI";
oOracleConn.Open();

//Do Something

oOracleConn.Close();
</code>```

The error for the page looks like this:

```<code>Exception Details: Oracle.DataAccess.Client.OracleException: The provider is not compatible with the version of Oracle client

Source Error:
Line 21:
Line 22:
Line 23:             OracleConnection oOracleConn = new OracleConnection();
Line 24:             oOracleConn.ConnectionString =
Line 25:                 "Data Source=MyOracleServerName;" +

[OracleException (0x80004005): The provider is not compatible with the version of Oracle client]
   Oracle.DataAccess.Client.OracleInit.Initialize() +494
   Oracle.DataAccess.Client.OracleConnection..cctor() +483

Stack Trace:
[TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception.]
   Oracle.DataAccess.Client.OracleConnection..ctor() +0
   Boeing.IVX.Web.RoyTesting.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\CE218C\Desktop\IVX.Net\Web\IVX\RoyTesting.aspx.cs:23
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +47
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
</code>```

答: Also look for IIS Application pool Enable 32-bit true or false flag, when you see this message, some oracle forum directed me for this!</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use the Oracle ODP.NET 11g (11.1.0.6.20) Instant Client on my ASP.net project as a Data Provider but when I run the aspx page I get a "The provider is not compatible with the version of Oracle client" error message.  Any help would be appreciated.

I've referenced the Data Provider in Visual Studio 2005 and the code behind looks like this:

using Oracle.DataAccess.Client;
..

OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString =
    "Data Source=MyOracleServerName;" +
    "Integrated Security=SSPI";
oOracleConn.Open();

//Do Something

oOracleConn.Close();

The error for the page looks like this:

Exception Details: Oracle.DataAccess.Client.OracleException: The provider is not compatible with the version of Oracle client

Source Error:
Line 21:
Line 22:
Line 23:             OracleConnection oOracleConn = new OracleConnection();
Line 24:             oOracleConn.ConnectionString =
Line 25:                 "Data Source=MyOracleServerName;" +

[OracleException (0x80004005): The provider is not compatible with the version of Oracle client]
   Oracle.DataAccess.Client.OracleInit.Initialize() +494
   Oracle.DataAccess.Client.OracleConnection..cctor() +483

Stack Trace:
[TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception.]
   Oracle.DataAccess.Client.OracleConnection..ctor() +0
   Boeing.IVX.Web.RoyTesting.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\CE218C\Desktop\IVX.Net\Web\IVX\RoyTesting.aspx.cs:23
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +47
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436


答:
Try this:</p>

```<code>.parent .child li {
    display: inline;
}
</code>```

Title: How do I display multiple divs (and their child elements) as Inline?

Body:
Try this:

.parent .child li {
    display: inline;
}


问:
Order by shortestPath WITHOUT excluding disconnected nodes
I'm trying to implement a "find your friends" feature in my social graph, and to make it as user-friendly as possible I want to order the results of my query by shortest path (so that someone already in your "circle of friends" will show up first).  However, results that you dont yet have any relationship with (i.e. there is no shortest path to them) should still be included, in case the person you are looking for is someone totally disconnected from your current network.

My current query is (if the user had typed in 'Bill'):

```<code>MATCH (u:User), (me:User), path=shortestPath((me)-[:WORKED_ON]-(u))
WHERE u.first_name =~ '(?i)Bill.*'
OR u.last_name =~ '(?i)Bill.*' AND
me.user_id='someuserid1234'
RETURN u, path
ORDER BY LENGTH(path) ASC
</code>```

This accomplishes the 'order by shortest path' but it excludes any disconnected nodes from the result.

Is there a way to say "order by shortest path, unless there is no path in which case use a path length of 20" perhaps?
Or maybe "order by shortest path, but if there are fewer than X results, ignore shortest path"?

答:
You need to use an OPTIONAL MATCH for the path between the nodes:</p>

```<code>MATCH (u:User), (me:User)
WHERE u.first_name =~ '(?i)Bill.*'
OR u.last_name =~ '(?i)Bill.*' AND
me.user_id='someuserid1234'
OPTIONAL MATCH path=shortestPath((me)-[:WORKED_ON*]-(u))
RETURN u, coalesce(LENGTH(path), 20) as distance
ORDER BY distance ASC
</code>```

Body:
I'm trying to implement a "find your friends" feature in my social graph, and to make it as user-friendly as possible I want to order the results of my query by shortest path (so that someone already in your "circle of friends" will show up first).  However, results that you dont yet have any relationship with (i.e. there is no shortest path to them) should still be included, in case the person you are looking for is someone totally disconnected from your current network.

My current query is (if the user had typed in 'Bill'):

MATCH (u:User), (me:User), path=shortestPath((me)-[:WORKED_ON]-(u))
WHERE u.first_name =~ '(?i)Bill.*'
OR u.last_name =~ '(?i)Bill.*' AND
me.user_id='someuserid1234'
RETURN u, path
ORDER BY LENGTH(path) ASC

This accomplishes the 'order by shortest path' but it excludes any disconnected nodes from the result.

Is there a way to say "order by shortest path, unless there is no path in which case use a path length of 20" perhaps?
Or maybe "order by shortest path, but if there are fewer than X results, ignore shortest path"?

Body:
You need to use an OPTIONAL MATCH for the path between the nodes:

MATCH (u:User), (me:User)
WHERE u.first_name =~ '(?i)Bill.*'
OR u.last_name =~ '(?i)Bill.*' AND
me.user_id='someuserid1234'
OPTIONAL MATCH path=shortestPath((me)-[:WORKED_ON*]-(u))
RETURN u, coalesce(LENGTH(path), 20) as distance
ORDER BY distance ASC


问:
Strange difference between Integer variable and Array variable
```<code>a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]
</code>```

but Array

```<code>def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value
</code>```

Could Anybody tell me why it is?

答:
There is a difference between mutable and immutable  objects.

Numerical is immutable; in other words, if you had the object 1, you cannot change its value to 2. 1 and 2 will always be different objects, having different object ids. What 1+1 is doing is returning back a newly created 2, that is a different object from 1.

Array, Hash, String are mutable; in other words, if you had the object [], you can change it to [1] retaining its identity, and that is what your code does. Even though the value is now different, it is the same object as [] before.

But in your case, you are comparing Fixnum#+ and Array#<< and claiming they are different. That is not strange. They are different methods, why do you expect them to be the same? In fact, as mu points out, if you do a+[1], that does not change a. It does what is comparable to Fixnum#+: create a new object and return it.

What your question should be really asking is: why is there no counterpart Numerical#<< that behaves like Array#<<? The mutable vs. immutable difference above is the answer to it.

Body:
a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]

but Array

def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value

Could Anybody tell me why it is?


问:
Javascript - Is there a way to revoke appendChild without removing the child node?
I have a drag and drop function in the javascript game that I am creating at the moment.
I've given it a condition to listen to, if it meets the condition, the game will progress to next stage. (If number image matches given condition and fruit image given matches the condition, allow to drop, and reload the number image with next one.)
And these images are all stored in arrays. So to display them, I'm setting the background image of the div.

The problem is that the fruit image appended will remain in the same position. I have tried using removeChild() but removes the whole div. Also tried creating a new div to replace the removed div. It does create a new div but it remains on where it is dropped.

Is there a way to undo the appendChild?

function createDiv() {
    var newDiv = '

';
    var parentDiv = document.getElementById("fruitCloud2");
    parentDiv.appendChild(newDiv);
}

function stage2() {
    createDiv();

    document.getElementById("number").style.backgroundImage = "url(" + numberAddress + myNumber[1] + ")";
    document.getElementById("fruit1").style.backgroundImage = "url(" + fruit1Address + fruitCloudOne[randFruit1] + ")";
    document.getElementById("fruit2").style.backgroundImage = "url(" + fruit2Address + fruitCloudTwo[randFruit2] + ")";
    document.getElementById("fruit3").style.backgroundImage = "url(" + fruit3Address + fruitCloudThree[randFruit3] + ")";
}

function allowDrop(ev) {
    ev.preventDefault();
}

function dragStart(ev) {
    ev.dataTransfer.setData("fruit", ev.target.id);
}

function onDrop(ev) {
  ev.preventDefault();

  if (document.getElementById("number").style.backgroundImage == 'url("' + numberAddress + myNumber[0] +'")' && document.getElementById("fruit2").style.backgroundImage == 'url("' + fruit2Address + fruitCloudTwo[0] + '")') {
      var dropSource = ev.dataTransfer.getData("fruit");
      ev.target.appendChild(document.getElementById(dropSource));
      stage2();
      ev.target.removeChild(document.getElementById(dropSource));
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    width: 100%;
    max-width: 100%;
    margin: 0;
    overflow: hidden;
    padding: 0;
    background-color: black;
}

#background {
    position: absolute;
    background-image: url(Assets/Background_cloudPosition.png);
    background-size: cover;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
    bottom: 0%;
    z-index: -10;
}

#startGame {
    position: absolute;
    left: 90px;
    width: 80px;
    height: 80px;
    background-color: green;
}

#refreshFruits {
    position: absolute;
    left: 180px;
    width: 80px;
    height: 80px;
    background-color: blue;
}

#number {
    position: absolute;
    width: 230px;
    height: 230px;
    left: 450px;
    bottom: 415px;
    background-size: contain;
    background-repeat: no-repeat;
    z-index: 15;
}

#fruitCloud1 {
    position: absolute;
    width: 240px;
    height: 120px;
    bottom: 460px;
    left: 135px;
    z-index: 15;
}

#fruitCloud2 {
    position: absolute;
    width: 240px;
    height: 120px;
    bottom: 320px;
    left: 300px;
    z-index: 15;
}

#fruitCloud3 {
    position: absolute;
    width: 240px;
    height: 120px;
    bottom: 185px;
    left: 110px;
    z-index: 15;
}

#fruit1 {
    position: absolute;
    width: 240px;
    height: 120px;
    background-size: contain;
    background-repeat: no-repeat;
}

#fruit2 {
    position: absolute;
    width: 240px;
    height: 120px;
    background-size: contain;
    background-repeat: no-repeat;
}

#fruit3 {
    position: absolute;
    width: 240px;
    height: 120px;
    background-size: contain;
    background-repeat: no-repeat;
}

#jelly {
    position: absolute;
    background-image: url(Assets/JellyMonster/JellyMonsterDefault.png);
    background-size: contain;
    background-repeat: no-repeat;
    width: 260px;
    height: 190px;
    bottom: 50px;
    right: 390px;
    z-index: 10;
}</code>```

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">

    <title>This is an experiment.</title>

<button id="download" onclick="download()"></button>

<button id="startGame" onclick="startGame()"></button>
<button id="refreshFruits" onclick="refreshFruits()"></button>

```

答:
I have found an answer to this myself.
Instead of removing child (dropsource), I set visibility to hidden.
Then on the next stage function, I set it back to visible and appended the fruit div back to its parent div, which is the div with id fruitcloud.</p>

Body:
I have a drag and drop function in the javascript game that I am creating at the moment.
I've given it a condition to listen to, if it meets the condition, the game will progress to next stage. (If number image matches given condition and fruit image given matches the condition, allow to drop, and reload the number image with next one.)
And these images are all stored in arrays. So to display them, I'm setting the background image of the div.

The problem is that the fruit image appended will remain in the same position. I have tried using removeChild() but removes the whole div. Also tried creating a new div to replace the removed div. It does create a new div but it remains on where it is dropped.

Is there a way to undo the appendChild?

function createDiv() {
    var newDiv = '

';
    var parentDiv = document.getElementById("fruitCloud2");
    parentDiv.appendChild(newDiv);
}

function stage2() {
    createDiv();

    document.getElementById("number").style.backgroundImage = "url(" + numberAddress + myNumber[1] + ")";
    document.getElementById("fruit1").style.backgroundImage = "url(" + fruit1Address + fruitCloudOne[randFruit1] + ")";
    document.getElementById("fruit2").style.backgroundImage = "url(" + fruit2Address + fruitCloudTwo[randFruit2] + ")";
    document.getElementById("fruit3").style.backgroundImage = "url(" + fruit3Address + fruitCloudThree[randFruit3] + ")";
}

function allowDrop(ev) {
    ev.preventDefault();
}

function dragStart(ev) {
    ev.dataTransfer.setData("fruit", ev.target.id);
}

function onDrop(ev) {
  ev.preventDefault();

  if (document.getElementById("number").style.backgroundImage == 'url("' + numberAddress + myNumber[0] +'")' && document.getElementById("fruit2").style.backgroundImage == 'url("' + fruit2Address + fruitCloudTwo[0] + '")') {
      var dropSource = ev.dataTransfer.getData("fruit");
      ev.target.appendChild(document.getElementById(dropSource));
      stage2();
      ev.target.removeChild(document.getElementById(dropSource));
  }
}

body {
    width: 100%;
    max-width: 100%;
    margin: 0;
    overflow: hidden;
    padding: 0;
    background-color: black;
}

#background {
    position: absolute;
    background-image: url(Assets/Background_cloudPosition.png);
    background-size: cover;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
    bottom: 0%;
    z-index: -10;
}

#startGame {
    position: absolute;
    left: 90px;
    width: 80px;
    height: 80px;
    background-color: green;
}

#refreshFruits {
    position: absolute;
    left: 180px;
    width: 80px;
    height: 80px;
    background-color: blue;
}

#number {
    position: absolute;
    width: 230px;
    height: 230px;
    left: 450px;
    bottom: 415px;
    background-size: contain;
    background-repeat: no-repeat;
    z-index: 15;
}

#fruitCloud1 {
    position: absolute;
    width: 240px;
    height: 120px;
    bottom: 460px;
    left: 135px;
    z-index: 15;
}

#fruitCloud2 {
    position: absolute;
    width: 240px;
    height: 120px;
    bottom: 320px;
    left: 300px;
    z-index: 15;
}

#fruitCloud3 {
    position: absolute;
    width: 240px;
    height: 120px;
    bottom: 185px;
    left: 110px;
    z-index: 15;
}

#fruit1 {
    position: absolute;
    width: 240px;
    height: 120px;
    background-size: contain;
    background-repeat: no-repeat;
}

#fruit2 {
    position: absolute;
    width: 240px;
    height: 120px;
    background-size: contain;
    background-repeat: no-repeat;
}

#fruit3 {
    position: absolute;
    width: 240px;
    height: 120px;
    background-size: contain;
    background-repeat: no-repeat;
}

#jelly {
    position: absolute;
    background-image: url(Assets/JellyMonster/JellyMonsterDefault.png);
    background-size: contain;
    background-repeat: no-repeat;
    width: 260px;
    height: 190px;
    bottom: 50px;
    right: 390px;
    z-index: 10;
}

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">

    <title>This is an experiment.</title>

<button id="download" onclick="download()"></button>

<button id="startGame" onclick="startGame()"></button>
<button id="refreshFruits" onclick="refreshFruits()"></button>


问:
JQuery .on("click") event not triggering
I am currently working on a "split-screen" web application. It uses selenium to retrieve the html of a webpage then sends and displays it in iframes using srcdoc. I want, when someone presses a link in the first screen, for the second screen to display a simple "Loading" while an ajax request is sent to the backend to retrieve the html of the url (as it might take a couple of seconds to load) then display the retrieved html in the second screen.

To do so, I "inject" a JQuery event code into the src code of the first screen in the backend (shown below) right before the end body tag (as the retrieved source is a string, that is easy to do). The second screen has id="oframe".

For some reason, the JQuery event wont trigger. Any ideas why?

```<code><script>
    $("a").on("click",function(e){
    e.preventDefault();
    if(e.target.href){
        let link = e.target.href;
        parent.document.getElementById("oframe").srcdoc="<html><head></head><body>
                                                       <p>Loading</p></body></html>";
        $.ajax({
            url: "/newOrigin",
            data: {"link":link},
            type: "POST",
            success: function(response) {
                 parent.document.getElementById("oframe").srcdoc=response.site;},
            error: function(error) {console.log(error);}
        });
    }});
    </script>
</code>```

Note that the event works if I only have

parent.document.getElementById("oframe").srcdoc="

or

```<code>$.ajax({
            url: "/newOrigin",
            data: {"link":link},
            type: "POST",
            success: function(response) {
                 parent.document.getElementById("oframe").srcdoc=response.site;},
            error: function(error) {console.log(error);}
        });
</code>```

inside the if statement.Together they stop the event, I know that because preventDefault() is not working (link opens in a new tab).

Example  tag:

cookies

答:
You cannot have a line break in the middle of JavaScript string.

So, put this:

```<code>parent.document.getElementById("oframe").srcdoc="<html><head></head><body>
                                               <p>Loading</p></body></html>";
</code>```

all on one line:

```<code>parent.document.getElementById("oframe").srcdoc="<html><head></head><body>p>Loading</p></body></html>";
</code>```

Body:
I am currently working on a "split-screen" web application. It uses selenium to retrieve the html of a webpage then sends and displays it in iframes using srcdoc. I want, when someone presses a link in the first screen, for the second screen to display a simple "Loading" while an ajax request is sent to the backend to retrieve the html of the url (as it might take a couple of seconds to load) then display the retrieved html in the second screen.

To do so, I "inject" a JQuery event code into the src code of the first screen in the backend (shown below) right before the end body tag (as the retrieved source is a string, that is easy to do). The second screen has id="oframe".

For some reason, the JQuery event wont trigger. Any ideas why?

Note that the event works if I only have

parent.document.getElementById("oframe").srcdoc="

or

$.ajax({
            url: "/newOrigin",
            data: {"link":link},
            type: "POST",
            success: function(response) {
                 parent.document.getElementById("oframe").srcdoc=response.site;},
            error: function(error) {console.log(error);}
        });

inside the if statement.Together they stop the event, I know that because preventDefault() is not working (link opens in a new tab).

Example  tag:

cookies

Body:
You cannot have a line break in the middle of JavaScript string.

So, put this:

parent.document.getElementById("oframe").srcdoc="<html><head></head><body>
                                               <p>Loading</p></body></html>";

all on one line:

parent.document.getElementById("oframe").srcdoc="<html><head></head><body>p>Loading</p></body></html>";


问:
Check if passed argument value is nil or empty
I am trying to re-write the C# code which i have wrote previously to Swift.

```<code>public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}
</code>```

I am not able to write if statement effectively in swift.

答:
Using prefix and ?: as a one-liner

```<code>func right(value: String, length: Int) -> String {
    return value.count > length ? String(value.prefix(value.count - length)) : value
}
</code>```

Body:
I am trying to re-write the C# code which i have wrote previously to Swift.

public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}

I am not able to write if statement effectively in swift.

Body:
Using prefix and ?: as a one-liner

func right(value: String, length: Int) -> String {
    return value.count > length ? String(value.prefix(value.count - length)) : value
}


问:
How to remove duplicate words from a text file using java
I have a input file like

names.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

</code>```

I want to output like. Removing duplicates words from the name

output.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

</code>```

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}
```

答:
You can even save the order creating set as:

```<code>Set<String> uniqueNames = new LinkedHashSet<>();
</code>```

Then you can just add the elements to your set:

```<code>uniqueNames.add(next);
</code>```

Body:
I have a input file like

names.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

I want to output like. Removing duplicates words from the name

output.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}

Body:
You can even save the order creating set as:

Set<String> uniqueNames = new LinkedHashSet<>();

Then you can just add the elements to your set:

uniqueNames.add(next);


问:
Split list using a given item
I want to extract groups of elements between special elements '-break-'. And then store these groups into a new list.

This is the input list:

```<code>main_list = [ '-break-',
          'one',
          'two',
          '-break-',
          'three',
          '-break-',
          'four',
          'five',
          'six'
          '-break-',
          'seven',
          'eight',
          'nine',
          'ten'
         ]
</code>```

The output list should be:

```<code>new_list = [ ['one', 'two'],
         ['three'],
         ['four', 'five', 'six'],
         ['seven', 'eight', 'nine', 'ten'],
        ]
</code>```

答:
Here's one approach using itertools.groupby:

```<code>from itertools import groupby
out = [[*v] for k,v in groupby(main_list, key= lambda x: x != '-break-') if k]

print(out)

[['one', 'two'],
 ['three'],
 ['four', 'five', 'six'],
 ['seven', 'eight', 'nine', 'ten']]
</code>```

itertools.groupby groups together consecutive values that are equal. However when a key is provided, the same logic applies but using the outcome from the key function. In this case the key function will be generating the following values:

```<code>[x != '-break-' for x in main_list]
# [False, True, True, False, True, False, True, True, True, True, True, True, True]
</code>```

So on each iteration we will be receiving a tuple consisting on the grouping key (either True or False) and a list with the corresponding values. So in order to keep only those where the grouping key is True, we only need to add if k as a condition.

Title: Split list using a given item

Body:
I want to extract groups of elements between special elements '-break-'. And then store these groups into a new list.

This is the input list:

main_list = [ '-break-',
          'one',
          'two',
          '-break-',
          'three',
          '-break-',
          'four',
          'five',
          'six'
          '-break-',
          'seven',
          'eight',
          'nine',
          'ten'
         ]

The output list should be:

new_list = [ ['one', 'two'],
         ['three'],
         ['four', 'five', 'six'],
         ['seven', 'eight', 'nine', 'ten'],
        ]

Body:
Here's one approach using itertools.groupby:

from itertools import groupby
out = [[*v] for k,v in groupby(main_list, key= lambda x: x != '-break-') if k]

print(out)

[['one', 'two'],
 ['three'],
 ['four', 'five', 'six'],
 ['seven', 'eight', 'nine', 'ten']]

itertools.groupby groups together consecutive values that are equal. However when a key is provided, the same logic applies but using the outcome from the key function. In this case the key function will be generating the following values:

[x != '-break-' for x in main_list]
# [False, True, True, False, True, False, True, True, True, True, True, True, True]

So on each iteration we will be receiving a tuple consisting on the grouping key (either True or False) and a list with the corresponding values. So in order to keep only those where the grouping key is True, we only need to add if k as a condition.


答:
Massive one-liner. It can probably be simplified:

new_list = [[y for y in x.split(',') if y] for x in ','.join(main_list).split('-break-') if x]
```

<p>Here's a more clear view of the list comprehension:</p>

<pre class="lang-py prettyprint-override"><code>[
    [
         y
         # Split all the elements by ","
         for y in x.split(',')
         # Filter out empty values
         if y
    ]
    # Join everything with "," and then split it by "-break-"
    for x in ','.join(main_list)
             .split('-break-')
    # Filter out empty values
    if x
]
</code>```

Title: Split list using a given item

Body:
Massive one-liner. It can probably be simplified:

new_list = [[y for y in x.split(',') if y] for x in ','.join(main_list).split('-break-') if x]

Here's a more clear view of the list comprehension:

[
    [
         y
         # Split all the elements by ","
         for y in x.split(',')
         # Filter out empty values
         if y
    ]
    # Join everything with "," and then split it by "-break-"
    for x in ','.join(main_list)
             .split('-break-')
    # Filter out empty values
    if x
]


问:
Is it possible to generate a report from JIRA or Greenhopper on what code has changed?
We have the confluence suite.

Using this, is it possible to produce a report highlighting what classes have changed?

JIRA items linked to GreenHopper via SVN+JIRA references is exactly the type of information I need.

Does such a report template exist?

答:
The best way to get this out of the box is to get FishEye, Atlassian's repository browser tool.  With the latest versions you can embed FishEye content in a JIRA dashboard and get the reports you need without having to switch to FishEye.

As Francis mentioned already, post back here if you have more detailed questions.


问:
Can i import my primary key in Neo4j with CSV
I'm importing CSV files to Neo4J, but Neo4J doesn't import my primary key.

I'm using this:

```<code>LOAD CSV WITH HEADERS FROM "file:///C:/c/tabela_sujeito.csv" AS row
CREATE(:Sujeito{suj_ID:row.id, idade:row.idade, altura:row.altura, peso:row.peso, genero:row.genero, mao_dominante:row.mao_dominante});
</code>```

suj_ID is my primary key, and it isn't imported, unlike the other attributes.

答:
As suggested by @InverseFalcon, You need to use row.suj_ID instead of row.id  in your query.

```<code>LOAD CSV WITH HEADERS FROM "file:///C:/c/tabela_sujeito.csv" AS row
CREATE(:Sujeito{suj_ID:row.suj_ID, idade:row.idade, altura:row.altura, peso:row.peso, genero:row.genero, mao_dominante:row.mao_dominante});
</code>```

Body:
I'm importing CSV files to Neo4J, but Neo4J doesn't import my primary key.

I'm using this:

LOAD CSV WITH HEADERS FROM "file:///C:/c/tabela_sujeito.csv" AS row
CREATE(:Sujeito{suj_ID:row.id, idade:row.idade, altura:row.altura, peso:row.peso, genero:row.genero, mao_dominante:row.mao_dominante});

suj_ID is my primary key, and it isn't imported, unlike the other attributes.

Body:
As suggested by @InverseFalcon, You need to use row.suj_ID instead of row.id  in your query.

LOAD CSV WITH HEADERS FROM "file:///C:/c/tabela_sujeito.csv" AS row
CREATE(:Sujeito{suj_ID:row.suj_ID, idade:row.idade, altura:row.altura, peso:row.peso, genero:row.genero, mao_dominante:row.mao_dominante});


问:
How to determine when the distance between two lines gets within a certain threshold?
I have a graph with the main data points(blue line) and the maxima (green) and minima (red).

Note that the x-values of the minima and maxima values are not the same, nor are they guaranteed to have the same count of values.

Now my goal is to determine when the distance along the y-axis (integral? sorry, its been a while since calculus in uni) between the maxima and minima lines gets below 10% (or any other arbitrary threshold) from the the average distance along the y-axis.

Here is the code used to generate:

```<code># Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Plotting the values for the graph above
plt.plot(df.flow.values)
upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')
</code>```

If it makes a difference, I'm using a Pandas Dataframe, scipy, and matplotlib.

答:
If I understand your question correct, you basically want to interpolate the lines defined by the extreme values. Stealing the answer from this post Interpolate NaN values in a numpy array, you can do this

```<code># Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Interpolate so you get no 'nan' values
df['min_extreme'] = df['min_extreme'].interpolate()
df['max_extreme'] = df['max_extreme'].interpolate()
</code>```

From here it should be easy do to all kinds of stuff with the distancens between the two lines. For instance

```<code># Get the average distance between the upper and lower extrema-lines
df['distance'] = df['max_extreme'] - df['min_extreme']
avg_dist = np.mean(df['distance'])

# Find indexes where distance is within some tolerance
df.index[df['distance']< avg_dist * .95]
</code>```

Body:
I have a graph with the main data points(blue line) and the maxima (green) and minima (red).

Note that the x-values of the minima and maxima values are not the same, nor are they guaranteed to have the same count of values.

Now my goal is to determine when the distance along the y-axis (integral? sorry, its been a while since calculus in uni) between the maxima and minima lines gets below 10% (or any other arbitrary threshold) from the the average distance along the y-axis.

Here is the code used to generate:

# Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Plotting the values for the graph above
plt.plot(df.flow.values)
upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')

If it makes a difference, I'm using a Pandas Dataframe, scipy, and matplotlib.

Body:
If I understand your question correct, you basically want to interpolate the lines defined by the extreme values. Stealing the answer from this post Interpolate NaN values in a numpy array, you can do this

# Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Interpolate so you get no 'nan' values
df['min_extreme'] = df['min_extreme'].interpolate()
df['max_extreme'] = df['max_extreme'].interpolate()

From here it should be easy do to all kinds of stuff with the distancens between the two lines. For instance

# Get the average distance between the upper and lower extrema-lines
df['distance'] = df['max_extreme'] - df['min_extreme']
avg_dist = np.mean(df['distance'])

# Find indexes where distance is within some tolerance
df.index[df['distance']< avg_dist * .95]


问:
How to fix "List Index Our of Range" error
I'm scraping a webpage, and writing the output to a .csv. I'm getting a "list index out of range" error. I think I understand what the error means, but I'm uncertain how to fix it.

The HTML code that houses the containers over which I want to iterate looks like this:

```<code><tr class="featured even" role="row"><td class="sorting_1 dcLogo">
    <a href="company/company">
    <img src="URL" alt="Company Name" width="50">
    </a>
    </td><td class="dcCompanyName"><a href="URL">Company Name</a></td><td class="dcBoothLabel">9999</td><td class="dcCategories">Widget 1, Widget 2, Widget 3</td><td class="dcCityState">CITY, STATE<br/></td><td class="dcCountry">US</td><td style="visibility:hidden;display:none;">4</td></tr>
</code>```

My code looks like this:

```<code>
page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll('tr')
del containers[8]

company_names = []
booth_numbers = []
categories = []
countries = []

print("generating csv")
with open('CompanyList.csv','w') as f:
    csv_out = csv.writer(f)
    csv_out.writerow(["company_name", "booth_number", "category", "country"])
    for container in containers:
            cols = container.findAll("td")
            company_name = cols[1].find("a").text
            booth_number = cols[2].text
            category = cols[3].text.strip()
            country = cols[5].text

            company_names.append(company_name)
            booth_numbers.append(booth_number)
            categories.append(category)
            countries.append(country)

            csv_out.writerow([company_name, booth_number, category, country])

f.close
print('Done Writing to File')
</code>```

When I run this, I get an "IndexError: list index out of range" error pointing at the:

```<code>booth_number = cols[3].text
</code>```

Any help would be greatly appreciated.

答:
There are not as many columns as you are assuming.

You can see how many columns there are with len(cols), and based on that, decide what to do when this expected column isn't there.

Note that you'll have a similar issue with the line after that.

Body:
I'm scraping a webpage, and writing the output to a .csv. I'm getting a "list index out of range" error. I think I understand what the error means, but I'm uncertain how to fix it.

The HTML code that houses the containers over which I want to iterate looks like this:

    	Company Name	9999	Widget 1, Widget 2, Widget 3	CITY, STATE
	US	4

My code looks like this:

page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll('tr')
del containers[8]

company_names = []
booth_numbers = []
categories = []
countries = []

print("generating csv")
with open('CompanyList.csv','w') as f:
    csv_out = csv.writer(f)
    csv_out.writerow(["company_name", "booth_number", "category", "country"])
    for container in containers:
            cols = container.findAll("td")
            company_name = cols[1].find("a").text
            booth_number = cols[2].text
            category = cols[3].text.strip()
            country = cols[5].text

            company_names.append(company_name)
            booth_numbers.append(booth_number)
            categories.append(category)
            countries.append(country)

            csv_out.writerow([company_name, booth_number, category, country])

f.close
print('Done Writing to File')

When I run this, I get an "IndexError: list index out of range" error pointing at the:

booth_number = cols[3].text

Any help would be greatly appreciated.


问:
How do I display multiple divs (and their child elements) as Inline?
I am attempting to display 4 div sections side by side by setting the parent div to:

```<code>.parent {
    display: inline;
}
</code>```

```<code><div class="parent">
        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>

        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>

        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>
</code>```

The 4 divs (with child elements nested) remain stacked as block elements:

```<code>test1
test1
test1
test1
test1
test1
test1
test1
test1
</code>```

But I want them side by side like this - test1 test1 test1

答:
There are many options. You can try flexbox:
https://www.w3schools.com/css/css3_flexbox.asp</p>

```<code>.parent {
  display: flex;
  flex-wrap: wrap;
}
</code>```

Body:
I am attempting to display 4 div sections side by side by setting the parent div to:

.parent {
    display: inline;
}

test1

test1

test1

test1

test1

test1

test1

test1

test1

The 4 divs (with child elements nested) remain stacked as block elements:

test1
test1
test1
test1
test1
test1
test1
test1
test1

But I want them side by side like this - test1 test1 test1

Body:
There are many options. You can try flexbox:
https://www.w3schools.com/css/css3_flexbox.asp

.parent {
  display: flex;
  flex-wrap: wrap;
}


问:
How do I show that I'm getting the smallest number of conflicts with Git by using K&R instead of B&D as the coding standard?
Git is smart and will "follow" changes in history to make merging easier and auto merge more for me. Conflicts are delineated by the lines that have not changed around the change. With K&R you get no ambiguous lines that have only "{" in them like you would in B&D. How would I test the limit of the context sensitivity that Git has in terms of the lines that surround a change?

I want to avoid resolving conflicts that I may not need to. But I need some way to test how many potential conflicts I will save by switching to K&R and the additional context it brings.

So far, Git is too smart to get fooled by trivial examples.

Any help is appreciated. Thanks in advance.

答:
So this is the closest thing I have found so far as evidence to this.

http://git.661346.n2.nabble.com/Bram-Cohen-speaks-up-about-patience-diff-td2277041.html

The e-mail is discussing the purpose of the "patience" algorithm in Git.  In it Bram explains how superfluous matching lines can create nasty conflicts that can be tough to resolve but only in the case of fairly complex merges involving large patches.  In other words simple contrived examples will fail to show this behavior.

While he does also mention things like End affecting the results it makes some sense to infer that placing an opening brace on it's own line increases the number of superfluous matching lines possibly resulting in a greater probability of these conflicts.

I'd say this isn't iron-clad, but it does lend some credence to this theory.

So 'unique lines' is a simple cross-language proxy for 'unimportant
  lines'.

That quote stands out to me in this discussion, since we are basically matching on what we feel are important lines that are supposed to give us context, however a brace by itself is not important and provides no context.


问:
How to resize twemoji emojis?
I'm using twemoji to style emojis on a page:

```<code>$(document).ready(function () {
  document.body = twemoji.parse(document.body)
 });
</code>```

It works fine, however the default emojis turn out to be 72x72:

```<code><img draggable="false" class="emoji" alt="" src="https://twemoji.maxcdn.com/2/72x72/1f600.png">
</code>```

I'd like twemoji to render 16x16 png or svg icons instead.

The docs does not explicitly say how to change the icon size, so I tried things like:

```<code>$(document).ready(function () {
  document.body = twemoji.parse(document.body,
   {size: 16}
    )
 });
</code>```

But none worked. How can I fix this?

答:
You can set the default size before running the parse() method:

```<code>$(document).ready(function () {
  // Set the size of the rendered Emojis
  // This can be set to 16x16, 36x36, or 72x72
  twemoji.size = '36x36';

  document.body = twemoji.parse(document.body);
});
</code>```

Credit to this page for the tip (and to this simple google search for finding it!).

Title: How to resize twemoji emojis?

Body:
I'm using twemoji to style emojis on a page:

$(document).ready(function () {
  document.body = twemoji.parse(document.body)
 });

It works fine, however the default emojis turn out to be 72x72:

I'd like twemoji to render 16x16 png or svg icons instead.

The docs does not explicitly say how to change the icon size, so I tried things like:

$(document).ready(function () {
  document.body = twemoji.parse(document.body,
   {size: 16}
    )
 });

But none worked. How can I fix this?

Body:
You can set the default size before running the parse() method:

$(document).ready(function () {
  // Set the size of the rendered Emojis
  // This can be set to 16x16, 36x36, or 72x72
  twemoji.size = '36x36';

  document.body = twemoji.parse(document.body);
});

Credit to this page for the tip (and to this simple google search for finding it!).


问:
How to keep polling GitHub repository and get commits by its messages on a regular interval using Jenkins?
I need to know how to write a Jenkins job which polls a GitHub repository continuously(say once in 4 hours) and send an email of commits(only the commit messages) made to that repo.</p>

答:
First the polling part:

In your job configuration, you can check of Poll SCM, and in that box enter values that would poll your repository every 4 hours, such as shown in the screenshot below:

The second part about sending the commit message:

As far as I am aware Jenkins always grabs the latest commit with the latest commit message. You could get the latest commit message from running "git log -1" inside of a shell command and storing it inside of an environment variable and then including that environment variable in your email body.

Here is a list of default environment variables that you can use throughout your job or also include in your email: https://wiki.jenkins.io/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-belowJenkinsSetEnvironmentVariables


问:
How to open a file in both read and append mode at the same time in one variable in python?
'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

```<code>open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")
</code>```

error:

```<code>invalid mode: 'r,a'
</code>```

答:
You're looking for the r+/a+/w+ mode, which allows both read and write operations to files.

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

```<code>with open("filename", "r+") as f:
    # here, position is initially at the beginning
    text = f.read()
    # after reading, the position is pushed toward the end

    f.write("stuff to append")
</code>```
```<code>with open("filename", "a+") as f:
    # here, position is already at the end
    f.write("stuff to append")
</code>```

If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0).

```<code>with open("filename", "r+") as f:
    text = f.read()
    f.write("stuff to append")

    f.seek(0)  # return to the top of the file
    text = f.read()

    assert text.endswith("stuff to append")
</code>```

(Further Reading: What's the difference between 'r+' and 'a+' when open file in python?)

You can also use w+, but this will truncate (delete) all the existing content.

Here's a nice little diagram from another SO post:

Body:
'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")

error:

invalid mode: 'r,a'

Body:
You're looking for the r+/a+/w+ mode, which allows both read and write operations to files.

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

with open("filename", "r+") as f:
    # here, position is initially at the beginning
    text = f.read()
    # after reading, the position is pushed toward the end

    f.write("stuff to append")

with open("filename", "a+") as f:
    # here, position is already at the end
    f.write("stuff to append")

If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0).

with open("filename", "r+") as f:
    text = f.read()
    f.write("stuff to append")

    f.seek(0)  # return to the top of the file
    text = f.read()

    assert text.endswith("stuff to append")

(Further Reading: What's the difference between 'r+' and 'a+' when open file in python?)

You can also use w+, but this will truncate (delete) all the existing content.

Here's a nice little diagram from another SO post:


问:
merge multiple actions into a single one in effects
I have the following list of action and I want to merge them so that I return a list of action and execute them one by one.

I tried

```<code>    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return forkJoin(actions);
    }),
</code>```

I also tried

```<code>    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return merge(actions);
    }),
</code>```

booth doesn't works

ERROR Error: Effect "UsedDronesEffect.getUsedDrones$" dispatched an
  invalid action: {"_isScalar":false}

```<code>core.js:15724 ERROR TypeError: Actions must have a type property
    at
</code>```

How can I merge them ?

答: You should be able to return an array of actions with on of the following operators mergeMap, switchMapandconcatMap`. Also does it have to return an array of actions, why not dispatch the actions one by one?

Body:
I have the following list of action and I want to merge them so that I return a list of action and execute them one by one.

I tried

    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return forkJoin(actions);
    }),

I also tried

    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return merge(actions);
    }),

booth doesn't works

ERROR Error: Effect "UsedDronesEffect.getUsedDrones$" dispatched an
  invalid action: {"_isScalar":false}

core.js:15724 ERROR TypeError: Actions must have a type property
    at

How can I merge them ?