问:
How to insert two blank lines between title and header in list-table of reStrutureText?
Here is the snippet of  list-table in reStrutureText.

```<code>.. list-table:: Frozen Delights!
  :widths: 15 10 30
  :header-rows: 1

  * - Treat
    - Quantity
    - Description
  * - Albatross
    - 2.99
    - On a stick!
  * - Crunchy Frog
    - 1.49
    - If we took the bones out, it wouldn't be
      crunchy, now would it?
  * - Gannet Ripple
    - 1.99
    - On a stick!
</code>```

The display effect.

How to insert two blank lines  between  title Frozen Delights! and header line Treat   Quantity  Description  ?

To test \n in online tool http://rst.ninjs.org/, \n doesn't work.

答:
If all you want is a style modification with visual space, and not actual line breaks, then modify the style sheet of the rendered HTML.

```<code>caption {
    margin-bottom: 2em;
}
</code>```

Body:
Here is the snippet of  list-table in reStrutureText.

.. list-table:: Frozen Delights!
  :widths: 15 10 30
  :header-rows: 1

  * - Treat
    - Quantity
    - Description
  * - Albatross
    - 2.99
    - On a stick!
  * - Crunchy Frog
    - 1.49
    - If we took the bones out, it wouldn't be
      crunchy, now would it?
  * - Gannet Ripple
    - 1.99
    - On a stick!

The display effect.

How to insert two blank lines  between  title Frozen Delights! and header line Treat   Quantity  Description  ?

To test \n in online tool http://rst.ninjs.org/, \n doesn't work.

Body:
If all you want is a style modification with visual space, and not actual line breaks, then modify the style sheet of the rendered HTML.

caption {
    margin-bottom: 2em;
}


来源: stackexchange

问:
How to combine work from more than one developer before checking into TFS?
My team's policy is to not check in broken code into TFS. But what if two team members are working on the same file and each member's work represents a partial solution ? One members changes won't work without the other.

How is the best way to combine the code and still follow policy of not checking in broken code ?

答:
Both developers could create a shelveset of their changes once their own coding is complete. Once it's time to merge their code, you have 1 developer unshelve the other developer's shelveset into their own workspace. Doing this will also trigger the Merge Tool in case there are any merge conflicts that can't be automatically resolved. This should allow the developer to combine work with the other without checking in broken code.

Note that both developers should make a shevleset of their own work before unshelving the other's, in case the unshelve of the other developers work goes terribly wrong in the merge and they need to revert their own work to the un-merged state.

Here's some documentation on creating and unshelving shelvesets

ContentLicense: CC BY-SA 3.0


问:
Trying to add a filter condition to TransferSpreadsheet using DAO and Me.filter
There is a button on a report that exports the underlying query of the report to excel. This function works fine as it would but I need it to take the criteria of the report. I have a massive reporting manager that will set the criteria for the report and then will open it up.

To make it easy, I want to pass me.filter to a variable which works in a different sub, but here my problem is that I need to pass the filter to be properly formatted for an sql statement I assume? The other sub just uses it as a [WhereCondition] for an open report command.

For clarification, the portion getreportsource() is a module that gets the reports source and it works fine.
Here are some example outputs of the variables as well as the code:

strRptName: TotalSalesForYear

strRptSource: qryMainDashboard

FilterCondition: TxnDate >= #11/1/2017# AND TxnDate <= #11/30/2017#

Private Sub cmdExcel_Click()

Dim strRptName As String
Dim strRptSource As String
Dim vardate As String
Dim varExportPath As String
Dim FilterCondition As String
Dim oExcel

FilterCondition = Me.filter

' Get the Report Name
strRptName = Screen.ActiveReport.Name

' Get the RecordSource of the Report from a module
strRptSource = GetReportSource(strRptName)

'Present Date
vardate = Format$(Now(), "YYYY.MM.DD_HH-mm-ss")
'Path of export
varExportPath = "C:\Users\Public\Downloads\"

'Check for terminating backslash ExportLinkReportsOut filepath.
    If Right(varExportPath, 1) <> "\" Then
       varExportPath = varExportPath & "\"
    End If
    varExportPath = varExportPath & strRptName & ".xlsx"

' set dao and create temp table
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Const tempTableName = "_tempTbl"
Set cdb = CurrentDb

'deletes temp table and handles error
On Error Resume Next
DoCmd.DeleteObject acTable, tempTableName
On Error GoTo 0

Set qdf = cdb.CreateQueryDef("")
qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] where filtercondition"
qdf.Execute
Set qdf = Nothing
Set cdb = Nothing

' export spreadsheet with the temp table, the export path, and then open the spreadsheet
DoCmd.TransferSpreadsheet acExport, , tempTableName, varExportPath, True
Set oExcel = GetObject(varExportPath)
oExcel.Application.Visible = True
oExcel.Parent.Windows(1).Visible = True

End Sub
```

Everything works when I change qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] where filtercondition" to qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] "

Problem is there is no filter when I drop filtercondition, obviously.
The error I keep getting is "Run-time error '3061': Too few paramters. Expected 1."

Anyone have any pointers?

答:
The problem is that you aren't concatenating the filter condition. Your query just states WHERE filtercondition, not WHERE TxnDate >= #11/1/2017# AND TxnDate <= #11/30/2017#

Change qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] where filtercondition" to qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] WHERE " & filtercondition

Body:
There is a button on a report that exports the underlying query of the report to excel. This function works fine as it would but I need it to take the criteria of the report. I have a massive reporting manager that will set the criteria for the report and then will open it up.

To make it easy, I want to pass me.filter to a variable which works in a different sub, but here my problem is that I need to pass the filter to be properly formatted for an sql statement I assume? The other sub just uses it as a [WhereCondition] for an open report command.

For clarification, the portion getreportsource() is a module that gets the reports source and it works fine.
Here are some example outputs of the variables as well as the code:

strRptName: TotalSalesForYear

strRptSource: qryMainDashboard

FilterCondition: TxnDate >= #11/1/2017# AND TxnDate <= #11/30/2017#

Private Sub cmdExcel_Click()

Dim strRptName As String
Dim strRptSource As String
Dim vardate As String
Dim varExportPath As String
Dim FilterCondition As String
Dim oExcel

FilterCondition = Me.filter

' Get the Report Name
strRptName = Screen.ActiveReport.Name

' Get the RecordSource of the Report from a module
strRptSource = GetReportSource(strRptName)

'Present Date
vardate = Format$(Now(), "YYYY.MM.DD_HH-mm-ss")
'Path of export
varExportPath = "C:\Users\Public\Downloads\"

'Check for terminating backslash ExportLinkReportsOut filepath.
    If Right(varExportPath, 1) <> "\" Then
       varExportPath = varExportPath & "\"
    End If
    varExportPath = varExportPath & strRptName & ".xlsx"

' set dao and create temp table
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Const tempTableName = "_tempTbl"
Set cdb = CurrentDb

'deletes temp table and handles error
On Error Resume Next
DoCmd.DeleteObject acTable, tempTableName
On Error GoTo 0

Set qdf = cdb.CreateQueryDef("")
qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] where filtercondition"
qdf.Execute
Set qdf = Nothing
Set cdb = Nothing

' export spreadsheet with the temp table, the export path, and then open the spreadsheet
DoCmd.TransferSpreadsheet acExport, , tempTableName, varExportPath, True
Set oExcel = GetObject(varExportPath)
oExcel.Application.Visible = True
oExcel.Parent.Windows(1).Visible = True

End Sub

Everything works when I change qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] where filtercondition" to qdf.SQL = "SELECT * INTO [" & tempTableName & "] FROM [" & strRptSource & "] "

Problem is there is no filter when I drop filtercondition, obviously.
The error I keep getting is "Run-time error '3061': Too few paramters. Expected 1."

Anyone have any pointers?


问:
How to know if a Javascript Callback is Synchronous or Asynchronous?

Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

```<code>$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});
</code>```

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

答:
You have several questions here, so I'll try to answer them one by one:

Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

In the browser you can kinda have this as the rule of thumb: Only setTimeout, setInterval, requests and events are asynchronous. Other built-in callbacks (like Array.prototype.map) are synchronous.

On Node.js it's more complicated: e.g. you can do file reading both synchronously and asynchronously. Then you just need to know that the callback is asynchronous by nature.

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

Unfotunately without checking the source code of the method/function you're calling you cannot know if it's synchronous or asynchronous.

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up.

Exactly. You can find this from jQuery's documentation for .hide method:

complete

  Type: Function()

  A function to call once the animation is complete, called once per matched element.

Body:
Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?


问:
custom View Cell in listview having only button clickable
I want to create a viewcell which stacklayout containing Frame for border each row. This Frame contains labels and one button. On this button click I have to change screen.

I find an issue when I render that code on iOS simulator and found out that on selection of any rows i.e. viewcell, it grays out and show blurred selected row which looks ugly. I tried to disable the view cell which solved my row selection issue but it also disabled button click on row as it is part of it.

I only requires a button to be enabled and available for click and rest of the part on viewcell should not be clickable or available to select. I have to use frame for border purpose. Which also provides rounded border but suggest me some solution which I can use in place of frame for borders as well.

Screenshot:

```<code><ListView x:Name="lstView" RowHeight="150" SeparatorVisibility="None" IsPullToRefreshEnabled="False" >
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <StackLayout Padding="10,10,10,10">
          <Frame OutlineColor="Silver">
            <Grid>
              <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="100" />
              </Grid.ColumnDefinitions>
              <Label Text="Car Type" Grid.Row="0" Grid.Column="0" FontAttributes="Bold"/>
              <Label Text="{Binding CreatedDate}" Grid.Row="1" Grid.Column="0"/>
              <Label Text="{Binding TransactionId}" Grid.Row="2" Grid.Column="0"/>
              <StackLayout Grid.Row="0" Grid.Column="1" Orientation="Horizontal">
                <Label Text="Status" FontAttributes="Bold"/>
                <Label Text="{Binding Status}" FontAttributes="Bold"/>
              </StackLayout>
              <StackLayout Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
                <Label Text="Customer Name" />
                <Label Text="{Binding CustName}" />
              </StackLayout>
              <Button Text="Button" Grid.Row="1" Grid.Column="2" Clicked="OnClicked" CommandParameter="{Binding DisplayName}"></Button>
            </Grid>
          </Frame>
          </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</code>```

答:
Easiest way, if you wanna stick to xamarin forms only, is to the ViewCell BackgroundColor or the Layout in your ViewCell.View to white.

So in this case:

```<code><DataTemplate>
        <ViewCell>
          <StackLayout Padding="10,10,10,10" BackgroundColor="White">
</code>```

But because of the padding, there might be some space left transparent, showing the touch response when hitting the ViewCell

Body:
I want to create a viewcell which stacklayout containing Frame for border each row. This Frame contains labels and one button. On this button click I have to change screen.

I find an issue when I render that code on iOS simulator and found out that on selection of any rows i.e. viewcell, it grays out and show blurred selected row which looks ugly. I tried to disable the view cell which solved my row selection issue but it also disabled button click on row as it is part of it.

I only requires a button to be enabled and available for click and rest of the part on viewcell should not be clickable or available to select. I have to use frame for border purpose. Which also provides rounded border but suggest me some solution which I can use in place of frame for borders as well.

Screenshot:

<ListView x:Name="lstView" RowHeight="150" SeparatorVisibility="None" IsPullToRefreshEnabled="False" >
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <StackLayout Padding="10,10,10,10">
          <Frame OutlineColor="Silver">
            <Grid>
              <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="100" />
              </Grid.ColumnDefinitions>

              <StackLayout Grid.Row="0" Grid.Column="1" Orientation="Horizontal">

              </StackLayout>
              <StackLayout Grid.Row="1" Grid.Column="1" Orientation="Horizontal">

              </StackLayout>
              <Button Text="Button" Grid.Row="1" Grid.Column="2" Clicked="OnClicked" CommandParameter="{Binding DisplayName}"></Button>
            </Grid>
          </Frame>
          </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

Body:
Easiest way, if you wanna stick to xamarin forms only, is to the ViewCell BackgroundColor or the Layout in your ViewCell.View to white.

So in this case:

<DataTemplate>
        <ViewCell>
          <StackLayout Padding="10,10,10,10" BackgroundColor="White">

But because of the padding, there might be some space left transparent, showing the touch response when hitting the ViewCell


问:
Declare UInt8Array variable in TypeScript
How to declare function parameter of type UInt8Array in TypeScript?

```<code>import * as fs from "fs";
fs.readFile(fileName, (err: string, data: UInt8Array) => {
                if (err) {
                    return console.error(err);
                }
                console.log("file text: " + data.toString());
            });
</code>```

I'm having an error:

error TS2304: Cannot find name 'UInt8Array'

Thanks

答:
Your error message indicates a typo, i.e.

```<code>error TS2304: Cannot find name 'UInt8Array'
</code>```

complains about UInt8Array. But the name you're looking for is probably Uint8Array, with a lowercase i.

Body:
How to declare function parameter of type UInt8Array in TypeScript?

import * as fs from "fs";
fs.readFile(fileName, (err: string, data: UInt8Array) => {
                if (err) {
                    return console.error(err);
                }
                console.log("file text: " + data.toString());
            });

I'm having an error:

error TS2304: Cannot find name 'UInt8Array'

Thanks

Body:
Your error message indicates a typo, i.e.

error TS2304: Cannot find name 'UInt8Array'

complains about UInt8Array. But the name you're looking for is probably Uint8Array, with a lowercase i.


问:
c# Switch case not working
I'm trying to check a value by using a switch:

private void btnInput1Rste_Click(object sender, EventArgs e)
{
    switch (sender == btnInput1Rste)
    {
        case "1": currentButtonPressedRste = 1;
            break;
    }
}
```

It gives the error as follows:

can't convert type 'string' to 'bool'

However, when i try to convert it to a boolean it says:

a constant value is expected.

How do I fix it?

When it works it's supposed to check 3 values. (not with just this switch)

答:
Option 1 using switch, where we assume that your btnInput1Rste is a const string such:

```<code>    //..
    public const string btnInput1Rste= "some_value";

    ///...then this should work:
    switch (sender)
        {
            case btnInput1Rste:
                //enter code here
                break;
        }
</code>```

Option 2 where the btnInput1Rste does not have to be constant string:

```<code>if(sender == btnInput1Rste){
      //enter code here
}
</code>```

Title: c# Switch case not working

Body:
I'm trying to check a value by using a switch:

private void btnInput1Rste_Click(object sender, EventArgs e)
{
    switch (sender == btnInput1Rste)
    {
        case "1": currentButtonPressedRste = 1;
            break;
    }
}

It gives the error as follows:

can't convert type 'string' to 'bool'

However, when i try to convert it to a boolean it says:

a constant value is expected.

How do I fix it?

When it works it's supposed to check 3 values. (not with just this switch)

Body:
Option 1 using switch, where we assume that your btnInput1Rste is a const string such:

    //..
    public const string btnInput1Rste= "some_value";

    ///...then this should work:
    switch (sender)
        {
            case btnInput1Rste:
                //enter code here
                break;
        }

Option 2 where the btnInput1Rste does not have to be constant string:

if(sender == btnInput1Rste){
      //enter code here
}


问:
Can I trigger CSS transitions via selectors other than ":hover" and ":active"?
I'm learning about transitions in CSS3 via sololearn.com, where the only examples given for using transitions are in conjunction with the :hover selector.

Everything else I can find uses either that or :active with no explanation of what other selectors can be used or why selectors other than these two are not shown as examples.

Is there a way to start transitions without interaction from the user? Or would that require JavaScript?

答:
Transitions are, as Paulie_D says, changes in state. What this "state" refers to, is simply the value of any style property (that can be animated, anyway). Even the spec describes it the same way:

Normally when the value of a CSS property changes, the rendered result is instantly updated, with the affected elements immediately changing from the old property value to the new property value. This section describes a way to specify transitions using new CSS properties. These properties are used to animate smoothly from the old state to the new state over time.

This means that you don't actually need a selector to start transitions. Styles can be changed via CSS, JavaScript, or the inline style attribute. All of these are subject to transitions, because they all modify style property values. Selectors just happen to be the most common way of doing it because selectors and declaration blocks are the two fundamental components that make up style rules, themselves the building blocks of CSS.

Most other ways of using transitions with or without user interaction do in fact involve JavaScript because CSS doesn't support much state change without requiring user interaction (outside of animations, which are a different beast from transitions), but that doesn't mean that JavaScript is inherently required for transitions to work, because transitions are about state change, regardless of how that state change is invoked (JS or not).

Most tutorials use :hover and :active to demonstrate transitions simply because user interaction is the easiest and most intuitive way for readers to see transitions in action, and to learn what it means for an element to change state (albeit a different kind of state, but the principle is the same). It's also by far the most common use case for transitions: animating changes in state in response to user interaction.

But you don't actually need to change property values with a user interaction pseudo-class in order for transitions to work. You can change them with any selector, even if user interaction is handled by a different element (and that element doesn't have to start transitions using :hover or :active either)...

label {
  transition: color 1s linear;
}

:checked + label {
  color: #f00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><input type=checkbox id=check><label for=check>Label</label></code>```

... or by the page itself...

h1 {
  transition: color 1s linear;
}

:target {
  color: #f00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Section 1 Section 2
<h1 id=sec1>Section 1</h1>
<h1 id=sec2>Section 2</h1></code>```

Once you add JavaScript into the mix, you can set property values directly (i.e. not use a selector)...

setTimeout(function() {
  document.querySelector('p').style.color = '#f00';
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  transition: color 1s linear;
}</code>```

Wait for it...```
</div>
</div>
</p>

<p>... change an element's class, ID or other attribute...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>setTimeout(function() {
  document.querySelector('p.foo').className = 'bar';
}, 1000);

setTimeout(function() {
  document.getElementById('foo').id = 'bar';
}, 2000);

setTimeout(function() {
  document.querySelector('p[data-attr]').dataset.attr = 'bar';
}, 3000);</code>```

p {
  transition: color 1s linear;
}

p.bar { color: #f00; }
p#bar { color: #090; }
p[data-attr=bar] { color: #00f; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class=foo>Wait for it...
<p id=foo>Wait for it...
<p data-attr=foo>Wait for it...</code>```

... or even move elements around in the DOM tree (although this does have limitations — notice that the Foo item fails to start its transition because it's getting detached before being reattached, while the Bar item is able to start its transition once it notices it's now first because it never leaves the DOM tree)...

setTimeout(function() {
  var ul = document.querySelector('ul');
  ul.appendChild(ul.firstChild);
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  transition: color 1s linear;
}

li:first-child { color: #f00; }</code>```

Foo
Bar
```

... and be able to start transitions all the same. Notice that all the JavaScript examples start transitions automatically, no user interaction required.

So, in conclusion, transitions are about state change, and said state change pertains to changes in style property values. These are independent of selectors or JavaScript, although selectors are a fundamental part of CSS and you do need JavaScript for most things.

Body:
Transitions are, as Paulie_D says, changes in state. What this "state" refers to, is simply the value of any style property (that can be animated, anyway). Even the spec describes it the same way:

Normally when the value of a CSS property changes, the rendered result is instantly updated, with the affected elements immediately changing from the old property value to the new property value. This section describes a way to specify transitions using new CSS properties. These properties are used to animate smoothly from the old state to the new state over time.

This means that you don't actually need a selector to start transitions. Styles can be changed via CSS, JavaScript, or the inline style attribute. All of these are subject to transitions, because they all modify style property values. Selectors just happen to be the most common way of doing it because selectors and declaration blocks are the two fundamental components that make up style rules, themselves the building blocks of CSS.

Most other ways of using transitions with or without user interaction do in fact involve JavaScript because CSS doesn't support much state change without requiring user interaction (outside of animations, which are a different beast from transitions), but that doesn't mean that JavaScript is inherently required for transitions to work, because transitions are about state change, regardless of how that state change is invoked (JS or not).

Most tutorials use :hover and :active to demonstrate transitions simply because user interaction is the easiest and most intuitive way for readers to see transitions in action, and to learn what it means for an element to change state (albeit a different kind of state, but the principle is the same). It's also by far the most common use case for transitions: animating changes in state in response to user interaction.

But you don't actually need to change property values with a user interaction pseudo-class in order for transitions to work. You can change them with any selector, even if user interaction is handled by a different element (and that element doesn't have to start transitions using :hover or :active either)...

label {
  transition: color 1s linear;
}

:checked + label {
  color: #f00;
}

<p><input type=checkbox id=check><label for=check>Label</label>

... or by the page itself...

h1 {
  transition: color 1s linear;
}

:target {
  color: #f00;
}

<p><a href=#sec1>Section 1</a> <a href=#sec2>Section 2</a>
<h1 id=sec1>Section 1</h1>
<h1 id=sec2>Section 2</h1>

Once you add JavaScript into the mix, you can set property values directly (i.e. not use a selector)...

setTimeout(function() {
  document.querySelector('p').style.color = '#f00';
}, 1000);

p {
  transition: color 1s linear;
}

<p>Wait for it...

... change an element's class, ID or other attribute...

setTimeout(function() {
  document.querySelector('p.foo').className = 'bar';
}, 1000);

setTimeout(function() {
  document.getElementById('foo').id = 'bar';
}, 2000);

setTimeout(function() {
  document.querySelector('p[data-attr]').dataset.attr = 'bar';
}, 3000);

p {
  transition: color 1s linear;
}

p.bar { color: #f00; }
p#bar { color: #090; }
p[data-attr=bar] { color: #00f; }

<p class=foo>Wait for it...
<p id=foo>Wait for it...
<p data-attr=foo>Wait for it...

... or even move elements around in the DOM tree (although this does have limitations — notice that the Foo item fails to start its transition because it's getting detached before being reattached, while the Bar item is able to start its transition once it notices it's now first because it never leaves the DOM tree)...

setTimeout(function() {
  var ul = document.querySelector('ul');
  ul.appendChild(ul.firstChild);
}, 1000);

li {
  transition: color 1s linear;
}

li:first-child { color: #f00; }

<ul><li>Foo<li>Bar</ul>

... and be able to start transitions all the same. Notice that all the JavaScript examples start transitions automatically, no user interaction required.

So, in conclusion, transitions are about state change, and said state change pertains to changes in style property values. These are independent of selectors or JavaScript, although selectors are a fundamental part of CSS and you do need JavaScript for most things.


问:
How to specify AWS credentials in C# .NET core console program
I am trying to test a .NET core console program to publish a message to SNS. As I had issues trying to get it to work in Lambda, I want to try it in a non-Lambda environment.  In Lambda, security is covered by the role, but in a console program, I presume that I have to specify my access key and secret somehow.

I've read this page: http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html#net-dg-config-creds-sdk-store, but still totally confused.

I'm running on my local development computer, not an EC2 instance. No intent to go to production with this, just trying to test some code.

I'm on Visual Studio 2015, .NET Core 1.0. I've used Nuget to get the following:
  "AWSSDK.Extensions.NETCore.Setup": "3.3.3",
  "AWSSDK.SimpleNotificationService": "3.3.0.23",

Based on the answer to How to set credentials on AWS SDK on NET Core? I created the /user/.aws/credentials file (assuming credentials was the file name and not the directory name).

But that question/answer doesn't address how to actually use this file.  The code I'm running is below.

```<code>    public static void Main(string[] args)
    {
        Console.WriteLine("Started");
        //var awsCredentials = new Amazon.Runtime.AWSCredentials()
        var client = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
        //var client = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(awsCredentials, Amazon.RegionEndpoint.EUWest2);
        //Amazon.SimpleNotificationService.Model.PublishResponse publishResp = null;
        SendMessage(client).Wait();
        Console.WriteLine("Completed call to SendMessage: Press enter to end:");
        Console.ReadLine();
    }
</code>```

The error I'm getting on the new client is:

```<code>An unhandled exception of type 'Amazon.Runtime.AmazonServiceException' occurred in AWSSDK.Core.dll

Additional information: Unable to find credentials
</code>```

I see there is a way to pass an AWSCredentials object to that constructor, but I don't understand how to build it.   Amazon.Runtime.AWSCredentials is an abstract class, so I can't use it in a "new" statement.

答:
Based on Dan Pantry's answer, here is a simple short answer with code highlighted (note the region enum in the second line):

```<code>var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("myaccesskey", "mysecretkey");
var client = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(
                              awsCredentials, Amazon.RegionEndpoint.EUWest2);
</code>```

Use a role if possible, but above works when needed.  Then the question is where to store the access key/secret key; could be environment variable, config file, prompt the user, or any of the usual suspects.

AWS-CLI and Python use credentials from here: c:\Users\username\.aws\credentials, so the C# could just read that file so as not to put the codes in the C# program itself. But then each user/developer that runs the program would need to set their credentials there.

There is also now a concept of running Lambda on your local machine, but I haven't tried it yet:
https://dzone.com/articles/run-aws-lambda-functions-locally-on-windows-machin#:~:text=Step%201%3A%20Download%20SAM%20local,version%20with%20the%20command%20below.&text=Step%203%3A%20Write%20your%20lambda,yaml%20on%20the%20root%20level.
So the point is that if you are going to do Lambda, but you need to test locally first, this would probably be worth trying.

Body:
I am trying to test a .NET core console program to publish a message to SNS. As I had issues trying to get it to work in Lambda, I want to try it in a non-Lambda environment.  In Lambda, security is covered by the role, but in a console program, I presume that I have to specify my access key and secret somehow.

I've read this page: http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html#net-dg-config-creds-sdk-store, but still totally confused.

I'm running on my local development computer, not an EC2 instance. No intent to go to production with this, just trying to test some code.

I'm on Visual Studio 2015, .NET Core 1.0. I've used Nuget to get the following:
  "AWSSDK.Extensions.NETCore.Setup": "3.3.3",
  "AWSSDK.SimpleNotificationService": "3.3.0.23",

Based on the answer to How to set credentials on AWS SDK on NET Core? I created the /user/.aws/credentials file (assuming credentials was the file name and not the directory name).

But that question/answer doesn't address how to actually use this file.  The code I'm running is below.

    public static void Main(string[] args)
    {
        Console.WriteLine("Started");
        //var awsCredentials = new Amazon.Runtime.AWSCredentials()
        var client = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
        //var client = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(awsCredentials, Amazon.RegionEndpoint.EUWest2);
        //Amazon.SimpleNotificationService.Model.PublishResponse publishResp = null;
        SendMessage(client).Wait();
        Console.WriteLine("Completed call to SendMessage: Press enter to end:");
        Console.ReadLine();
    }

The error I'm getting on the new client is:

An unhandled exception of type 'Amazon.Runtime.AmazonServiceException' occurred in AWSSDK.Core.dll

Additional information: Unable to find credentials

I see there is a way to pass an AWSCredentials object to that constructor, but I don't understand how to build it.   Amazon.Runtime.AWSCredentials is an abstract class, so I can't use it in a "new" statement.

Body:
Based on Dan Pantry's answer, here is a simple short answer with code highlighted (note the region enum in the second line):

var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("myaccesskey", "mysecretkey");
var client = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(
                              awsCredentials, Amazon.RegionEndpoint.EUWest2);

Use a role if possible, but above works when needed.  Then the question is where to store the access key/secret key; could be environment variable, config file, prompt the user, or any of the usual suspects.

AWS-CLI and Python use credentials from here: c:\Users\username\.aws\credentials, so the C# could just read that file so as not to put the codes in the C# program itself. But then each user/developer that runs the program would need to set their credentials there.

There is also now a concept of running Lambda on your local machine, but I haven't tried it yet:
https://dzone.com/articles/run-aws-lambda-functions-locally-on-windows-machin#:~:text=Step%201%3A%20Download%20SAM%20local,version%20with%20the%20command%20below.&text=Step%203%3A%20Write%20your%20lambda,yaml%20on%20the%20root%20level.
So the point is that if you are going to do Lambda, but you need to test locally first, this would probably be worth trying.

ContentLicense: CC BY-SA 4.0


问:
Access static resource in server-side code in NextJs?
Im using the static render feature of NextJS to generate a static version of my site thus I want to ensure that on the very first render of the page all the data it needs to render correctly is supplied.

I have a number of blog posts which I have stored as .md files in /static and want to access them in a page such as:

```<code>import * as fs from "fs";
...

export default class extends React.Component<IProps, any> {

  static async getInitialProps (props: IServerProps) {
    const post = (await getDb()).posts.find(p => p.id == props.query.id);
    const markdown = fs.readFileSync(`/static/posts/${post.markdownFileName}`);
    return { post, markdown }
  }
...
</code>```

But if try to run the above I get the following error:

This dependency was not found: * fs

So im not sure how I should go about accessing these static resources while on the server..

答:
Unfortunately Next.js doesn't allow the use of webpack loaders to handle different file types on the server (Although they are used to build the client-side bundles), but it is possible to use a Babel plugin. One such plugin for Markdown content can be found here: https://www.npmjs.com/package/babel-plugin-markdown

After configuring it in .babelrc:

```<code>{
  "plugins": ["markdown"]
}
</code>```

it's possible to use markdown.require() to pull in .md content:

```<code>const html = markdown.require('./foo.md')
</code>```

More options are described at the link!

Body:
Im using the static render feature of NextJS to generate a static version of my site thus I want to ensure that on the very first render of the page all the data it needs to render correctly is supplied.

I have a number of blog posts which I have stored as .md files in /static and want to access them in a page such as:

import * as fs from "fs";
...

export default class extends React.Component<IProps, any> {

  static async getInitialProps (props: IServerProps) {
    const post = (await getDb()).posts.find(p => p.id == props.query.id);
    const markdown = fs.readFileSync(`/static/posts/${post.markdownFileName}`);
    return { post, markdown }
  }
...

But if try to run the above I get the following error:

This dependency was not found: * fs

So im not sure how I should go about accessing these static resources while on the server..

Body:
Unfortunately Next.js doesn't allow the use of webpack loaders to handle different file types on the server (Although they are used to build the client-side bundles), but it is possible to use a Babel plugin. One such plugin for Markdown content can be found here: https://www.npmjs.com/package/babel-plugin-markdown

After configuring it in .babelrc:

{
  "plugins": ["markdown"]
}

it's possible to use markdown.require() to pull in .md content:

const html = markdown.require('./foo.md')

More options are described at the link!


问:
SQLite: the database is locked
I'm using flask with sqlalchemy and sqlite db. I have 2 ajax that send some data from html to my .py file.

The problem is every time when i do any of these 2 operations, the second one become unavailable because of lock of db. Also, if first chosen action will be deleting, then exception firing no matter what operation will be chosen after. with first choice of adding, we can add without limitations that's strange too, because functions seem similar.

I've tried timeouts, closing sessions in a different ways, the result is always the same.

Here are two functions-handlers:

```<code>app = Flask(__name__)
csrf = CSRFProtect(app)

app.config.from_object('config')
db = SQLAlchemy(app)

import forms
import models

@app.route('/delete', methods = ['GET', 'POST'])
def delete():
    if request.method == "POST":
        if request.form['type'] == "delete":
            print("delete")
            engine = create_engine(SQLALCHEMY_DATABASE_URI)
            Session = sessionmaker(bind=engine)
            session = Session()

            try:
                print("try")
                requested = request.form['id']
                print(requested)
                models.Income.query.filter(models.Income.id == requested).delete()
                session.commit()
            except:
                print("rollback")
                session.rollback()
            finally:
                print("fin")
                session.close()

            ellist = models.Income.query.all()
            return render_template("incomeSection.html", list=ellist)

@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == "POST":
        if request.form['type'] == "add":
            print('add')
            engine = create_engine(SQLALCHEMY_DATABASE_URI)
            Session = sessionmaker(bind=engine)
            session = Session()

            try:
                print("try")
                newItem = models.Income(name=request.form['name'], tag=request.form['tag'],
                                        account=request.form['account'],
                                        date=date(*(int(i) for i in request.form['date'].split("-"))))
                session.add(newItem)
                session.commit()
            except:
                print('rollback')
                session.rollback()
            finally:
                print("fin")
                session.close()

            ellist = models.Income.query.all()
            print(ellist)
            return render_template("incomeSection.html", list=ellist)
</code>```

I've read that this exception caused by non-closed connections, but I have .close() in every finally block. I think the problem might be because of the db = SQLAlchemy(app) but I don't know how to fix if that is the case. Because I use this variable to connect with db in forms.py where I have the form template and in models.py where I defined my tables within db.

答:
So, aperrently, thete was an issue with number of connections.
The thing that solved my problem was the context manager for sqlalchemy, i used this one:

```<code>class SQLAlchemyDBConnection(object):

def __init__(self, connection_string):
    self.connection_string = connection_string
    self.session = None

def __enter__(self):
    engine = create_engine(self.connection_string)
    Session = sessionmaker()
    self.session = Session(bind=engine)
    return self

def __exit__(self, exc_type, exc_val, exc_tb):
    self.session.commit()
    self.session.close()
</code>```

and in the handler just

```<code>with SQLAlchemyDBConnection(SQLALCHEMY_DATABASE_URI) as db:
            newItem = models.Income(*your params*)
            db.session.add(newItem)
</code>```

And now it works fine, but i still don't know what was the issue in version that was earlier. They are seem to be same just with or without context manager

Title: SQLite: the database is locked

Body:
I'm using flask with sqlalchemy and sqlite db. I have 2 ajax that send some data from html to my .py file.

The problem is every time when i do any of these 2 operations, the second one become unavailable because of lock of db. Also, if first chosen action will be deleting, then exception firing no matter what operation will be chosen after. with first choice of adding, we can add without limitations that's strange too, because functions seem similar.

I've tried timeouts, closing sessions in a different ways, the result is always the same.

Here are two functions-handlers:

app = Flask(__name__)
csrf = CSRFProtect(app)

app.config.from_object('config')
db = SQLAlchemy(app)

import forms
import models

@app.route('/delete', methods = ['GET', 'POST'])
def delete():
    if request.method == "POST":
        if request.form['type'] == "delete":
            print("delete")
            engine = create_engine(SQLALCHEMY_DATABASE_URI)
            Session = sessionmaker(bind=engine)
            session = Session()

            try:
                print("try")
                requested = request.form['id']
                print(requested)
                models.Income.query.filter(models.Income.id == requested).delete()
                session.commit()
            except:
                print("rollback")
                session.rollback()
            finally:
                print("fin")
                session.close()

            ellist = models.Income.query.all()
            return render_template("incomeSection.html", list=ellist)

@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == "POST":
        if request.form['type'] == "add":
            print('add')
            engine = create_engine(SQLALCHEMY_DATABASE_URI)
            Session = sessionmaker(bind=engine)
            session = Session()

            try:
                print("try")
                newItem = models.Income(name=request.form['name'], tag=request.form['tag'],
                                        account=request.form['account'],
                                        date=date(*(int(i) for i in request.form['date'].split("-"))))
                session.add(newItem)
                session.commit()
            except:
                print('rollback')
                session.rollback()
            finally:
                print("fin")
                session.close()

            ellist = models.Income.query.all()
            print(ellist)
            return render_template("incomeSection.html", list=ellist)

I've read that this exception caused by non-closed connections, but I have .close() in every finally block. I think the problem might be because of the db = SQLAlchemy(app) but I don't know how to fix if that is the case. Because I use this variable to connect with db in forms.py where I have the form template and in models.py where I defined my tables within db.

Body:
So, aperrently, thete was an issue with number of connections.
The thing that solved my problem was the context manager for sqlalchemy, i used this one:

class SQLAlchemyDBConnection(object):

def __init__(self, connection_string):
    self.connection_string = connection_string
    self.session = None

def __enter__(self):
    engine = create_engine(self.connection_string)
    Session = sessionmaker()
    self.session = Session(bind=engine)
    return self

def __exit__(self, exc_type, exc_val, exc_tb):
    self.session.commit()
    self.session.close()

and in the handler just

with SQLAlchemyDBConnection(SQLALCHEMY_DATABASE_URI) as db:
            newItem = models.Income(*your params*)
            db.session.add(newItem)

And now it works fine, but i still don't know what was the issue in version that was earlier. They are seem to be same just with or without context manager


问:
In Excel, how to identify matching data in order to report shared quantities?
So, I have a list of products where I report which manufacturing facility currently makes it, as well as the QTY I need to make. Separately, I have a list that tells me ALL facilities that are equipped to manufacture that product.

What I'm looking to do is make a report that can show me, at a glance, how much work is available to offload from one facility to another.

Current Manufacturer Builds

```<code>  Product  ||  MFGR  ||  QTY to Build
     A     ||   1    ||      100
     B     ||   2    ||      50
     C     ||   3    ||      100
</code>```

All Product/Manufacturer Combos

```<code>  Product  ||  MFGR
     A     ||   1
     A     ||   2
     B     ||   2
     B     ||   3
     C     ||   3
</code>```

So, from the above lists we can infer:

Product A can be made at either facility 1 or 2, but it's currently set to build at facility 1

Product B can be made at either facility 2 or 3, but it's currently set to build at facility 2

product C can only be made at facility 3

From all this, I would like to have a report that shows the following information:

```<code>  From MFGR  ||  To MFGR  ||  Avail QTY
      1      ||     2     ||     100
      1      ||     3     ||      0
      2      ||     1     ||      0
      2      ||     3     ||     50
      3      ||     1     ||      0
      3      ||     2     ||      0
</code>```

Where, in this report, it recognizes that:

Product A's build QTY CAN be offloaded from facility 1 to 2, so it reports a possible move of 100 from 1 to 2

Product B's build QTY CAN be offloaded from facility 2 to 3, so it reports a possible move of 50 from 2 to 3

Note that the report ignores the product (it will need to since my actual file has 100's of products, and like 10 facilities), though I recognize it needs to take it into consideration in the formula.

Is there a single-cell formula that can get this done? I was using SUMIFS() to grab the Build QTY of the "From MFGR", but I wasn't sure how to incorporate that with anything else.

答:
I've answered this question with detailed example, twice within the last week!

Detailed Instructions & More...

Stack Overflow: User defined concatenate

Stack Overflow: How can I turn part of the Excel data to columns to get a desired output?

Unpivot Excel Data

Stack Overflow: How do I ask a good question?

Stack Overflow: How do I Search?

Body:
So, I have a list of products where I report which manufacturing facility currently makes it, as well as the QTY I need to make. Separately, I have a list that tells me ALL facilities that are equipped to manufacture that product.

What I'm looking to do is make a report that can show me, at a glance, how much work is available to offload from one facility to another.

Current Manufacturer Builds

  Product  ||  MFGR  ||  QTY to Build
     A     ||   1    ||      100
     B     ||   2    ||      50
     C     ||   3    ||      100

All Product/Manufacturer Combos

  Product  ||  MFGR
     A     ||   1
     A     ||   2
     B     ||   2
     B     ||   3
     C     ||   3

So, from the above lists we can infer:

Product A can be made at either facility 1 or 2, but it's currently set to build at facility 1

Product B can be made at either facility 2 or 3, but it's currently set to build at facility 2

product C can only be made at facility 3

From all this, I would like to have a report that shows the following information:

  From MFGR  ||  To MFGR  ||  Avail QTY
      1      ||     2     ||     100
      1      ||     3     ||      0
      2      ||     1     ||      0
      2      ||     3     ||     50
      3      ||     1     ||      0
      3      ||     2     ||      0

Where, in this report, it recognizes that:

Product A's build QTY CAN be offloaded from facility 1 to 2, so it reports a possible move of 100 from 1 to 2

Product B's build QTY CAN be offloaded from facility 2 to 3, so it reports a possible move of 50 from 2 to 3

Note that the report ignores the product (it will need to since my actual file has 100's of products, and like 10 facilities), though I recognize it needs to take it into consideration in the formula.

Is there a single-cell formula that can get this done? I was using SUMIFS() to grab the Build QTY of the "From MFGR", but I wasn't sure how to incorporate that with anything else.


问:
Filtering a ListBox
I have a ListBox named lsbEntities. I want to filter it's items based on some selected radio button.

The code below is kind of pseudo, is their a better approach?

```<code>private List<string> _listBoxItemsToFilter;
private Thread tFilterEntityList;

enum EntityType
{
    Vehicle,
    Facility
}

private void FilterEntityList(EntityType entityType)
{
    _listBoxItemsToFilter = new List<string>();
    Dictionary<string,string> entitiesAndClassTypes;
    List<string> listBoxItems = new List<string>();

    for(int i = 0; i < lsbEntities.Count; i++)
    {
        //object listItem = lsbEntities.Items[i];
        listBoxItems.Add(lsbEntities[i].ToString());
    }

    // get associated types
    entityClassTypes = _controlFacade.GetClassTypes(listBoxItems);

    foreach (KeyValuePair<string,string>
            entityAndClass in entitiesAndClassTypes)
    {
        classType = entityAndClass.Value;

        if(classType != entityType)
        {
                _listBoxItemsToFilter.Add(entityAndClass.Key);
        }
    }

    RemoveFilterFromEntityListBox();
    AddFilterToEntityListBox();
}

private void AddFilterToEntityListBox()
{
    // DELEGATE NEEDED TO MODIFY LISTBOX FROM THREAD
    foreach(string listBoxItem in _listBoxItemsToFilter)
    {
        if(lsbEntities.Contains(listBoxItem)
        {
            // REMOVE WITH DELEGATE
        }
    }
}

private void RemoveFilterFromEntityListBox()
{
    // DELEGATE NEEDED TO MODIFY LISTBOX FROM THREAD
    if(_listBoxItemsToFilter != null)
    {
        foreach(string listBoxItem in _listBoxItemsToFilter)
        {
            if(!lsbEntities.Contains(listBoxItem)
            {
            // REMOVE WITH DELEGATE
            }
        }
    }
}

 // EXAMPLE CALL WHEN CLICKING RADIO-BUTTON
 private void rbVehicles_CheckedChanged(object sender, EventArgs e)
 {
     switch (rbVehicles.Checked)
     {
         case (true):
         {
             object entityType = (object)EntityType.Vehicle;
             tFilterEntityList = new Thread(FilterEntityList(entityType));
             tFilterEntityList.IsBackground = true;
             tFilterEntityList.Start();
             //FilterEntityList(EntityType.Vehicle);
             break;
         }
     }
 }
</code>```

I have only included an example of selecting to filter everything but VehicleS. The same approach would be used for the Facility class, where the thread would be re-instantiated.

答:
Here is a simple example showing one way to filter items in a ListBox. This could be improved by using a ListView or DataGridView in VirtualMode. It is very unclear to me what you are trying to do, so if this is not helpful I will remove it.</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

public class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    List<Entity> items = new List<Entity>()
    {
        new Entity(EntityType.Vehicle, "Car"),
        new Entity(EntityType.Vehicle, "Aeroplane"),
        new Entity(EntityType.Vehicle, "Truck"),
        new Entity(EntityType.Vehicle, "Bus"),
        new Entity(EntityType.Facility, "Garage"),
        new Entity(EntityType.Facility, "House"),
        new Entity(EntityType.Facility, "Shack"),
    };

    ListBox listBox;
    ComboBox comboBox;

    public Form1()
    {
        Text = "Filtering Demo";
        ClientSize = new Size(500, 320);
        Controls.Add(listBox = new ListBox
        {
            Location = new Point(10, 10),
            Size = new Size(200, 300),
        });
        Controls.Add(comboBox = new ComboBox
        {
            Location = new Point(230, 10),
            DropDownStyle = ComboBoxStyle.DropDownList,
            Items = { "All", EntityType.Vehicle, EntityType.Facility },
            SelectedIndex = 0,
        });

        comboBox.SelectedIndexChanged += UpdateFilter;
        UpdateFilter(comboBox, EventArgs.Empty);
    }

    void UpdateFilter(object sender, EventArgs e)
    {
        var filtered = items.Where((i) => comboBox.SelectedItem is string || (EntityType)comboBox.SelectedItem == i.EntityType);
        listBox.DataSource = new BindingSource(filtered, "");
    }
}

enum EntityType { Vehicle, Facility, }

class Entity : INotifyPropertyChanged
{
    public string Name { get; private set; }
    public EntityType EntityType { get; private set; }
    public Entity(EntityType entityType, string name) { EntityType = entityType; Name = name; }
    public override string ToString() { return Name ?? String.Empty; }
    // Implementing INotifyPropertyChanged to eliminate (caught) BindingSource exceptions
    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

Title: Filtering a ListBox

Body:
I have a ListBox named lsbEntities. I want to filter it's items based on some selected radio button.

The code below is kind of pseudo, is their a better approach?

private List<string> _listBoxItemsToFilter;
private Thread tFilterEntityList;

enum EntityType
{
    Vehicle,
    Facility
}

private void FilterEntityList(EntityType entityType)
{
    _listBoxItemsToFilter = new List<string>();
    Dictionary<string,string> entitiesAndClassTypes;
    List<string> listBoxItems = new List<string>();

    for(int i = 0; i < lsbEntities.Count; i++)
    {
        //object listItem = lsbEntities.Items[i];
        listBoxItems.Add(lsbEntities[i].ToString());
    }

    // get associated types
    entityClassTypes = _controlFacade.GetClassTypes(listBoxItems);

    foreach (KeyValuePair<string,string>
            entityAndClass in entitiesAndClassTypes)
    {
        classType = entityAndClass.Value;

        if(classType != entityType)
        {
                _listBoxItemsToFilter.Add(entityAndClass.Key);
        }
    }

    RemoveFilterFromEntityListBox();
    AddFilterToEntityListBox();
}

private void AddFilterToEntityListBox()
{
    // DELEGATE NEEDED TO MODIFY LISTBOX FROM THREAD
    foreach(string listBoxItem in _listBoxItemsToFilter)
    {
        if(lsbEntities.Contains(listBoxItem)
        {
            // REMOVE WITH DELEGATE
        }
    }
}

private void RemoveFilterFromEntityListBox()
{
    // DELEGATE NEEDED TO MODIFY LISTBOX FROM THREAD
    if(_listBoxItemsToFilter != null)
    {
        foreach(string listBoxItem in _listBoxItemsToFilter)
        {
            if(!lsbEntities.Contains(listBoxItem)
            {
            // REMOVE WITH DELEGATE
            }
        }
    }
}

 // EXAMPLE CALL WHEN CLICKING RADIO-BUTTON
 private void rbVehicles_CheckedChanged(object sender, EventArgs e)
 {
     switch (rbVehicles.Checked)
     {
         case (true):
         {
             object entityType = (object)EntityType.Vehicle;
             tFilterEntityList = new Thread(FilterEntityList(entityType));
             tFilterEntityList.IsBackground = true;
             tFilterEntityList.Start();
             //FilterEntityList(EntityType.Vehicle);
             break;
         }
     }
 }

I have only included an example of selecting to filter everything but VehicleS. The same approach would be used for the Facility class, where the thread would be re-instantiated.

Body:
Here is a simple example showing one way to filter items in a ListBox. This could be improved by using a ListView or DataGridView in VirtualMode. It is very unclear to me what you are trying to do, so if this is not helpful I will remove it.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

public class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    List<Entity> items = new List<Entity>()
    {
        new Entity(EntityType.Vehicle, "Car"),
        new Entity(EntityType.Vehicle, "Aeroplane"),
        new Entity(EntityType.Vehicle, "Truck"),
        new Entity(EntityType.Vehicle, "Bus"),
        new Entity(EntityType.Facility, "Garage"),
        new Entity(EntityType.Facility, "House"),
        new Entity(EntityType.Facility, "Shack"),
    };

    ListBox listBox;
    ComboBox comboBox;

    public Form1()
    {
        Text = "Filtering Demo";
        ClientSize = new Size(500, 320);
        Controls.Add(listBox = new ListBox
        {
            Location = new Point(10, 10),
            Size = new Size(200, 300),
        });
        Controls.Add(comboBox = new ComboBox
        {
            Location = new Point(230, 10),
            DropDownStyle = ComboBoxStyle.DropDownList,
            Items = { "All", EntityType.Vehicle, EntityType.Facility },
            SelectedIndex = 0,
        });

        comboBox.SelectedIndexChanged += UpdateFilter;
        UpdateFilter(comboBox, EventArgs.Empty);
    }

    void UpdateFilter(object sender, EventArgs e)
    {
        var filtered = items.Where((i) => comboBox.SelectedItem is string || (EntityType)comboBox.SelectedItem == i.EntityType);
        listBox.DataSource = new BindingSource(filtered, "");
    }
}

enum EntityType { Vehicle, Facility, }

class Entity : INotifyPropertyChanged
{
    public string Name { get; private set; }
    public EntityType EntityType { get; private set; }
    public Entity(EntityType entityType, string name) { EntityType = entityType; Name = name; }
    public override string ToString() { return Name ?? String.Empty; }
    // Implementing INotifyPropertyChanged to eliminate (caught) BindingSource exceptions
    public event PropertyChangedEventHandler PropertyChanged;
}

ContentLicense: CC BY-SA 2.5


问:
jinja for loop inside jinja for loop
I want a jinja loop inside of a jinja loop unfortunately I keep getting errors cause theres so many brackets. how can I have a for loop in a for loop like this?

```<code>{% for stock in stocks%}
  <tr>
      <td>{{stock.id}}</td>
      <td>{{stock.price}}</td>
      {% for i in stock_list %}
      <th>{{stock.{{i}}}}th>
      {% endfor %}
  </tr>
</code>```

Error Message was: expected name or number

答:
I think the problem is the nested brackets '{{stock.{{i}}}}'.

Just use the i variable directly: {{stock.i}} or {{stock[i]}}.

Your describe is not explicit, I can't test it. You can try it.

Title: jinja for loop inside jinja for loop

Body:
I want a jinja loop inside of a jinja loop unfortunately I keep getting errors cause theres so many brackets. how can I have a for loop in a for loop like this?

{% for stock in stocks%}

      {{stock.id}}
      {{stock.price}}
      {% for i in stock_list %}
      {{stock.{{i}}}}th>
      {% endfor %}

Error Message was: expected name or number


问:
barman + mark the failed/started backup with red color
With the following barman command we can see the backup status, while  STARTED/FAILED status indicated that backup inst created successfully

```<code>barman list-backup main-db-server
</code>```

Output:

```<code>main-db-server 20170913T115706 - STARTED
main-db-server 20170913T115214 - STARTED
main-db-server 20170913T114659 - STARTED
main-db-server 20170912T233003 - FAILED
main-db-server 20170912T145147 - Tue Sep 12 14:51:50 2017 - Size: 45.2 MiB - WAL Size: 68.6 KiB
main-db-server 20170912T140611 - Tue Sep 12 14:06:14 2017 - Size: 41.2 MiB - WAL Size: 6.3 MiB
main-db-server 20170912T140430 - Tue Sep 12 14:04:36 2017 - Size: 41.2 MiB - WAL Size: 38.6 KiB
</code>```

Is it possible in some way to pipe after the the barman syntax the tput command in order to marked the lines with FAILED/STARTED with red color, so the user can identify this lines as bad backup's?

Example:

```<code>barman list-backup main-db-server |  ... tput setaf 1  ... tput sgr0
</code>```

remark - "tput setaf 1"  --> will paint the characters with red

答:
You can use grep for that

barman list-backup main-db-server |  grep -E 'FAILED|STARTED' |   ... tput setaf 1  ... tput sgr0

Body:
With the following barman command we can see the backup status, while  STARTED/FAILED status indicated that backup inst created successfully

barman list-backup main-db-server

Output:

main-db-server 20170913T115706 - STARTED
main-db-server 20170913T115214 - STARTED
main-db-server 20170913T114659 - STARTED
main-db-server 20170912T233003 - FAILED
main-db-server 20170912T145147 - Tue Sep 12 14:51:50 2017 - Size: 45.2 MiB - WAL Size: 68.6 KiB
main-db-server 20170912T140611 - Tue Sep 12 14:06:14 2017 - Size: 41.2 MiB - WAL Size: 6.3 MiB
main-db-server 20170912T140430 - Tue Sep 12 14:04:36 2017 - Size: 41.2 MiB - WAL Size: 38.6 KiB

Is it possible in some way to pipe after the the barman syntax the tput command in order to marked the lines with FAILED/STARTED with red color, so the user can identify this lines as bad backup's?

Example:

barman list-backup main-db-server |  ... tput setaf 1  ... tput sgr0

remark - "tput setaf 1"  --> will paint the characters with red


问:
rendering multiple partials after issue description in redmine plugin
How to render multiple partials after issue show description below is my code in hooks.rb

```<code>render_on :view_issues_show_description_bottom, partial: 'issues/my_description'
render_on :view_issues_show_description_bottom, partial: 'issues/my_second_description'
</code>```

while rendering it is displaying the my_second_description page but not my_description page. Can anyone help me out of this

答:
I fixed the issue by using below code

```<code>render_on :view_issues_show_details_bottom,
    {:partial => "show_more_data"},
    {:partial => "show_even_more_data"}
</code>```

http://www.rubydoc.info/github/redmine/redmine/Redmine/Hook/ViewListener#render_on-class_method

Body:
How to render multiple partials after issue show description below is my code in hooks.rb

render_on :view_issues_show_description_bottom, partial: 'issues/my_description'
render_on :view_issues_show_description_bottom, partial: 'issues/my_second_description'

while rendering it is displaying the my_second_description page but not my_description page. Can anyone help me out of this

Body:
I fixed the issue by using below code

render_on :view_issues_show_details_bottom,
    {:partial => "show_more_data"},
    {:partial => "show_even_more_data"}

http://www.rubydoc.info/github/redmine/redmine/Redmine/Hook/ViewListener#render_on-class_method


问:
Query to get username from child table with specific condition
I have a table Admin and a child table AdminOfArea. I want to get the user name from Table2 where username only have one Region not multiple which is Liverpool. in this case only A and B are according to this scenario.

Table 1 looks like

```<code>|Username |  UserType  |
|  abc    |  Admin     |
|   A     |  Admin     |
|  xyz    |  Admin     |
|   B     |  Admin     |
</code>```

Table 2 looks like

```<code>|UserName  Region    |
| abc     Wales      |
| abc     Liverpool  |
| abc     Westsussex |
| A       Liverpool  |
| xyz     Wales      |
| xyz     Liverpool  |
| xyz     Westsussex |
| B       Liverpool  |
</code>```

答:
```<code>Select Username,count(Region) FROM AdminOfArea
GROUP BY Username
</code>```

Using Upper Query U will get Username along with total no of region that particular username have Example: abc have 3.

```<code>Select Username FROM AdminOfArea
GROUP BY Username
having count(Region) = 1
</code>```

Using Having Clause we have separated those username who is associated with only 1 region

Body:
I have a table Admin and a child table AdminOfArea. I want to get the user name from Table2 where username only have one Region not multiple which is Liverpool. in this case only A and B are according to this scenario.

Table 1 looks like

|Username |  UserType  |
|  abc    |  Admin     |
|   A     |  Admin     |
|  xyz    |  Admin     |
|   B     |  Admin     |

Table 2 looks like

|UserName  Region    |
| abc     Wales      |
| abc     Liverpool  |
| abc     Westsussex |
| A       Liverpool  |
| xyz     Wales      |
| xyz     Liverpool  |
| xyz     Westsussex |
| B       Liverpool  |

Body:
Select Username,count(Region) FROM AdminOfArea
GROUP BY Username

Using Upper Query U will get Username along with total no of region that particular username have Example: abc have 3.

Select Username FROM AdminOfArea
GROUP BY Username
having count(Region) = 1

Using Having Clause we have separated those username who is associated with only 1 region


问:
How to redirect stdout to a file and then restore stdout back?
Here is my code and I can't get it to work.

```<code>int pfd = open("file", O_WRONLY, 0777);
int saved = dup(1);
close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");

// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");
</code>```

I have added some edits to my code.

答:
You need to check the return values of your function calls.  For most functions, you should check for error conditions.  Doing so might have revealed the problem that if you want open() to create the requested file in the event that it does not initially exist, then you need to add the O_CREAT flag.

But that's not your main problem here -- you are dealing with a buffering issue.  The output from the first printf() is buffered in memory, so even though file descriptor 1 refers to your file at the time that printf() is called, the data you write do not immediately get flushed to the destination file.  You then restore the original stdout file handle, so when the data are actually flushed, they go to the (restored) original stdout.  Solve this by fflush()ing before switching stdout back:

```<code>int pfd = open("file", O_WRONLY | O_CREAT, 0777);
int saved = dup(1);

close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");
fflush(stdout);  // <-- THIS

// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");
</code>```

Note also that dup2() is cleaner and safer for duping a file descriptor onto a specific file descriptor number.  You do that when you restore, but you should also do it for the initial redirection.

Body:
Here is my code and I can't get it to work.

int pfd = open("file", O_WRONLY, 0777);
int saved = dup(1);
close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");

// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");

I have added some edits to my code.

Body:
You need to check the return values of your function calls.  For most functions, you should check for error conditions.  Doing so might have revealed the problem that if you want open() to create the requested file in the event that it does not initially exist, then you need to add the O_CREAT flag.

But that's not your main problem here -- you are dealing with a buffering issue.  The output from the first printf() is buffered in memory, so even though file descriptor 1 refers to your file at the time that printf() is called, the data you write do not immediately get flushed to the destination file.  You then restore the original stdout file handle, so when the data are actually flushed, they go to the (restored) original stdout.  Solve this by fflush()ing before switching stdout back:

int pfd = open("file", O_WRONLY | O_CREAT, 0777);
int saved = dup(1);

close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");
fflush(stdout);  // <-- THIS

// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");

Note also that dup2() is cleaner and safer for duping a file descriptor onto a specific file descriptor number.  You do that when you restore, but you should also do it for the initial redirection.


问:
Load external CSS into component
```<code>import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<div></div>',
    styleUrls: [
        'http://example.com/external.css',
        'app/local.css'
    ]
})
export class AppComponent {}
</code>```

The external.css does not load.

Is there any way to load the external CSS in an Angular 2 Component?

答:
Better approach is already posted here : https://stackoverflow.com/a/36265072/5219412

You only have to add this in your component's declaration :

```<code>@Component({
    ...
    encapsulation: ViewEncapsulation.None,
})
</code>```

As specified in the angular documentation : https://angular.io/guide/component-styles

Hope it helps.

Title: Load external CSS into component

Body:
import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '

',
    styleUrls: [
        'http://example.com/external.css',
        'app/local.css'
    ]
})
export class AppComponent {}

The external.css does not load.

Is there any way to load the external CSS in an Angular 2 Component?

Body:
Better approach is already posted here : https://stackoverflow.com/a/36265072/5219412

You only have to add this in your component's declaration :

@Component({
    ...
    encapsulation: ViewEncapsulation.None,
})

As specified in the angular documentation : https://angular.io/guide/component-styles

Hope it helps.


问:
Pushing a 2d array onto a C++ STL stack?
```<code>int test[5][5];
stack<int**> mystack;
mystack.push(test);
</code>```

I get the error:

no matching function for call to ‘std::stack > >::push(int [5][5])’
  /usr/include/c++/4.4/bits/stl_stack.h:182: note: candidates are: void std::stack<_Tp, _Sequence>::push(const typename _Sequence::value_type&) [with _Tp = int**, _Sequence = std::deque >]

I've never really used stacks before so I would appreciate any help. If I declare test as a one-dimensional array and stack as int*, it works fine.

Edit: I'm trying to implement backtracing for a sudokusolver. I have the sudoku grid as a 9x9 array of set objects (objects that hold the solution or possible solutions). I have to push the current state of the puzzle onto the stack, and then from there try guess and check. If a guess creates a contradiction (ie violates the rules of a sudoku), then I would pop from the stack to recover the puzzle before the invalid guess.

答:
In your example, test is not of type int**.

If you want a two-dimensional array, I would recommend using std::vector. This would certainly save your confusion with arrays and pointers...

```<code>typedef std::vector<std::vector<int> > two_d_vector;
two_d_vector test;
stack<two_d_vector> mystack;
mystack.push(test);
</code>```

Body:
int test[5][5];
stack<int**> mystack;
mystack.push(test);

I get the error:

no matching function for call to ‘std::stack > >::push(int [5][5])’
  /usr/include/c++/4.4/bits/stl_stack.h:182: note: candidates are: void std::stack<_Tp, _Sequence>::push(const typename _Sequence::value_type&) [with _Tp = int**, _Sequence = std::deque >]

I've never really used stacks before so I would appreciate any help. If I declare test as a one-dimensional array and stack as int*, it works fine.

Edit: I'm trying to implement backtracing for a sudokusolver. I have the sudoku grid as a 9x9 array of set objects (objects that hold the solution or possible solutions). I have to push the current state of the puzzle onto the stack, and then from there try guess and check. If a guess creates a contradiction (ie violates the rules of a sudoku), then I would pop from the stack to recover the puzzle before the invalid guess.

Body:
In your example, test is not of type int**.

If you want a two-dimensional array, I would recommend using std::vector. This would certainly save your confusion with arrays and pointers...

typedef std::vector<std::vector<int> > two_d_vector;
two_d_vector test;
stack<two_d_vector> mystack;
mystack.push(test);


问:
SQL Schema news feed
I am creating a newsfeed style app which will create a social network for a company.

When you create a status you have the option to select the audience who the status will be visible to, in this instance it will be different businesses within that company.

For example 'John' from 'Business 1' wants to post a status about their quarterly results but only want's people in his business to see it.

However 'Jane' from 'Business 2' is having a baby and want her post to be seen by the whole company (all businesses).

Initially I was planning to create the 'NewsFeed' table with an audience column which contained an array of each business the post would be visible to. eg: ["Business 1", "Business 5", "Business 7"] and the app would check if the business the user is in is contained in the array, if true then it would show the post.

Im not sure this is the most efficient method to do this and doesn't seem particularly scalable.

I have also considered creating a 'NewsFeed' table for each department and depending on the audience option selected on the status update it would insert it into those tables. However if we end up with a lot of businesses I imagine that could be inefficient also?

What would be the best way to structure the tables in the database in order to most efficiently implement this feature?

thanks

答:
Creating 2 / 3 tables will be a better option than having a single table -
Table 1 >> NewsFeed with columns NewsFeedId and NewsFeedText
Table 2>> NewsFeedPublish with columns NewsFeedId and BusinessId

For space efficient design, It's better to have table Business with BuisnessId and BusinessName but if you do not want to create this table, you can directly use BusinessName instead of BuisnessId in Table2.

Title: SQL Schema news feed


问:
Is there an alternative to rexec for Python sandboxing?
Implementing a 'sandbox' environment in Python used to be done with the rexec module (http://docs.python.org/library/rexec.html).  Unfortunately, it has been deprecated/removed due to some security vulnerabilities.  Is there an alternative?

My goal is to have Python code execute semi-trusted Python scripts.  In a perfect world, calls to any functions outside of a pre-defined set would raise exceptions.  From what I've read about rexec's deprecation, this may not be possible.  So I'll settle for as much as I can get.  I can spawn a separate process to run the scripts, which helps a lot.  But they could still abuse I/O or processor/memory resources.

答:
Your best bet for security in cPython is using OS-level sandboxing mechanisms and running untrusted code in a separate process constrained by the OS.

This is equivalent to using 'jython with java "sandboxing"', as per the answer above, but probably a little more difficult to configure.

OwnerDisplayName: DNS


答:
The relationship you're defining is a 1:M relationship. Each status could be visible to 0 or more business.

I would create a NewsFeed table and a Business table, then a table which sits between these two tables - lets say NewsFeedBusiness.

In the NewsFeedBusiness table, you have the NewsFeedID as a foreign key that references NewsFeed and you have the BusinessID as a foreign key to the Business table. I would also add a unique key on NewsFeedID + BusinessID to prevent a NewsFeed record from being in the same business twice.

Title: SQL Schema news feed

Body:
I am creating a newsfeed style app which will create a social network for a company.

When you create a status you have the option to select the audience who the status will be visible to, in this instance it will be different businesses within that company.

For example 'John' from 'Business 1' wants to post a status about their quarterly results but only want's people in his business to see it.

However 'Jane' from 'Business 2' is having a baby and want her post to be seen by the whole company (all businesses).

Initially I was planning to create the 'NewsFeed' table with an audience column which contained an array of each business the post would be visible to. eg: ["Business 1", "Business 5", "Business 7"] and the app would check if the business the user is in is contained in the array, if true then it would show the post.

Im not sure this is the most efficient method to do this and doesn't seem particularly scalable.

I have also considered creating a 'NewsFeed' table for each department and depending on the audience option selected on the status update it would insert it into those tables. However if we end up with a lot of businesses I imagine that could be inefficient also?

What would be the best way to structure the tables in the database in order to most efficiently implement this feature?

thanks


问:
Meteor + Vue runtime-only build
When using the Meteor + Vue integration with server-side rendering, I'm getting the following warning on both client and server:

You are using the runtime-only build of Vue where the template compiler is not available.

```<code>[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
</code>```

What does this mean and how do I fix it? Is the package doing something wrong? Generally, I'm following this example project.

答:
This was caused by just trying to render an empty Vue template. Vue mistakenly interprets this as the template compiler not working properly. Putting some simple code such as the following in the home .vue file fixes it:

```<code><template>
  <p>foo</p>
</template>
</code>```

Title: Meteor + Vue runtime-only build

Body:
When using the Meteor + Vue integration with server-side rendering, I'm getting the following warning on both client and server:

You are using the runtime-only build of Vue where the template compiler is not available.

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

What does this mean and how do I fix it? Is the package doing something wrong? Generally, I'm following this example project.

Body:
This was caused by just trying to render an empty Vue template. Vue mistakenly interprets this as the template compiler not working properly. Putting some simple code such as the following in the home .vue file fixes it:

<template>
  <p>foo</p>
</template>


问:
Running script with fixed internal commands arguments to include Qwebengine pepflashplayer
I made a PyQt5 QWebengine app i wanna make portable.
I found out that flash weren't working in the app.
After a lot of reading i found out that having pepflashplayer64_*.dll & manifest.json in folder

C:\Windows\System32\Macromed\Flash\ is working.

However i wanna ship the pepflashplayer with app, and
adding custom flash folder to PATH env var, do not have effect , or
sys.path.insert()

the command

```<code>myapp.py --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll
</code>```

works , but how to pass extra augments internally when script is launched ?

i tried dirty hack to run sys.arg[0] script with extra command but no success.

```<code>if __name__ == "__main__":
    # print sys.argv
    flash = (' --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll').split()
    # print flash
    noooo =  (sys.argv[0] + flash[0]).split()
    import sys
    app = QtWidgets.QApplication(noooo)
    # ... the rest of your handling: `sys.exit(app.exec_())`, etc.
</code>```

答:
okay i got it to work so i can make app the app with browser portable , and solution was simpler than i thought.
Parsing second internal argument like this.</p>

```<code>if __name__ == "__main__":
    programname = os.path.dirname(sys.argv[0]) #get current script full folder path
    pepperpflash = ' --ppapi-flash-path=' + programname + '/Flash/pepflashplayer64_27_0_0_187.dll'
    try:
        app = QtWidgets.QApplication(sys.argv + [pepperpflash])
    except:
        app = QtWidgets.QApplication(sys.argv)
    # ... the rest of your handling: `sys.exit(app.exec_())`, etc.
</code>```

Body:
I made a PyQt5 QWebengine app i wanna make portable.
I found out that flash weren't working in the app.
After a lot of reading i found out that having pepflashplayer64_*.dll & manifest.json in folder

C:\Windows\System32\Macromed\Flash\ is working.

However i wanna ship the pepflashplayer with app, and
adding custom flash folder to PATH env var, do not have effect , or
sys.path.insert()

the command

myapp.py --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll

works , but how to pass extra augments internally when script is launched ?

i tried dirty hack to run sys.arg[0] script with extra command but no success.

if __name__ == "__main__":
    # print sys.argv
    flash = (' --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll').split()
    # print flash
    noooo =  (sys.argv[0] + flash[0]).split()
    import sys
    app = QtWidgets.QApplication(noooo)
    # ... the rest of your handling: `sys.exit(app.exec_())`, etc.

Body:
okay i got it to work so i can make app the app with browser portable , and solution was simpler than i thought.
Parsing second internal argument like this.

if __name__ == "__main__":
    programname = os.path.dirname(sys.argv[0]) #get current script full folder path
    pepperpflash = ' --ppapi-flash-path=' + programname + '/Flash/pepflashplayer64_27_0_0_187.dll'
    try:
        app = QtWidgets.QApplication(sys.argv + [pepperpflash])
    except:
        app = QtWidgets.QApplication(sys.argv)
    # ... the rest of your handling: `sys.exit(app.exec_())`, etc.


问:
Navbar dropdown not working in Angular 4
Im a very beginner or just started with Angular 4. So as part of learning I tried to create few simple component. So there I tried to have a bootstrap navbar. Here is the code for Navbar

```<code>    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Test Menu</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Has submenu
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="#">Action</a>
                        <a class="dropdown-item" href="#">Another action</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">Something else here</a>
                    </div>
                </li>

                <li class="nav-item" [routerLinkActive]="['active']">
                    <a class="nav-link" [routerLink]="'/engagement']">Engagement</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dropdownToggle>
                        System
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown" *dropdownMenu>
                        <a class="dropdown-item" [routerLink]="['/admin/users']">Manage Users</a>
                        <a class="dropdown-item" [routerLink]="['/admin/servers']">Manage Servers</a>
                        <a class="dropdown-item" [routerLink]="['/admin/logs']">View Application Logs</a>
                    </div>
                </li>
            </ul>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </div>
    </nav>
</code>```

Here is the constructor part

```<code>import { Component, OnInit } from '@angular/core';
import { BsDropdownMenuDirective } from 'ngx-bootstrap';
import * as $ from 'jquery';

@Component({
    selector: 'nav-menu',
    templateUrl: './navmenu.component.html',
    styleUrls: ['./navmenu.component.css']
})
export class NavMenuComponent implements OnInit {
    ngOnInit(): void {

    }

}
</code>```

But in my app component html I used this selector, the menu is showing but the dropdown is not working or its not showing the dropdown part of the dropdown menu.

Here is my app.component.html where Im using the menu

```<code><nav-menu></nav-menu>
<div class='container-fluid'>
  <router-outlet></router-outlet>
</div>
</code>```

Kindly suggest what should I do to make the dropdown menu to show when we click or mouse over the parent. In this case the Menu Has submenu contains submenu, but its not  showing

Body:
Im a very beginner or just started with Angular 4. So as part of learning I tried to create few simple component. So there I tried to have a bootstrap navbar. Here is the code for Navbar

        Test Menu
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Home

                    Link

Has submenu

                        Action
                        Another action

                        Something else here

                    Engagement

                        System

                        Manage Users
                        Manage Servers
                        View Application Logs

            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

Here is the constructor part

import { Component, OnInit } from '@angular/core';
import { BsDropdownMenuDirective } from 'ngx-bootstrap';
import * as $ from 'jquery';

@Component({
    selector: 'nav-menu',
    templateUrl: './navmenu.component.html',
    styleUrls: ['./navmenu.component.css']
})
export class NavMenuComponent implements OnInit {
    ngOnInit(): void {

    }

}

But in my app component html I used this selector, the menu is showing but the dropdown is not working or its not showing the dropdown part of the dropdown menu.

Here is my app.component.html where Im using the menu

  <router-outlet></router-outlet>

Kindly suggest what should I do to make the dropdown menu to show when we click or mouse over the parent. In this case the Menu Has submenu contains submenu, but its not  showing

Body:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

Please add this code to src/index.html file after body tag


问:
Regex find string after key inside qoutes
Input:

blalasdl8ujd "key":"value", blblabla asdw
  "alo":"ebobo",blabla"www":"zzzz"

or

blalasdl8ujd key [any_chars_here] "value", blabla asdw
  "alo":"ebobo", bla"www":"zzzz"

I'm tring to extract value having only key and knowing that value is covered with "

Following regex key.*"(.*?)" returns the last match covered with " ("zzzz").
I need to fix it to return first.

https://regex101.com/r/CDfhBT/1

答:
There's probably a somewhat more pythonic way to do this, but:

```<code>s1 = 'blalasdl8ujd "key":"value", blblabla asdw "alo":"ebobo",blabla"www":"zzzz"'
s2 = 'blalasdl8ujd key [any_chars_here] "value", blabla asdw "alo":"ebobo", bla"www":"zzzz"'

def getValue(string, keyName = 'key'):
    """Find next quoted value after a key that may or may not be quoted"""
    startKey = string.find(keyName)
    # if key is quoted, adjust value search range to exclude its closing quote
    endKey = string.find('"',startKey) if string[startKey-1]=='"' else startKey + len(keyName)
    startValue = string.find('"',endKey+1)+1
    return string[startValue:string.find('"',startValue+1)]

getValue(s1) #'value'
getValue(s2) #'value'
</code>```

I was inspired by the elegance of this answer, but handling the quoted and unquoted cases makes it more than a 1-liner.

You can use a comprehension such as:

```<code>next(y[1][1:-1] for y in [[l for l in x.split(':')]
     for  x in s2.split(',')] if 'key' in y[0]) # returns 'value' w/o quotes
</code>```

But that won't handle the case of s2.

Body:
There's probably a somewhat more pythonic way to do this, but:

s1 = 'blalasdl8ujd "key":"value", blblabla asdw "alo":"ebobo",blabla"www":"zzzz"'
s2 = 'blalasdl8ujd key [any_chars_here] "value", blabla asdw "alo":"ebobo", bla"www":"zzzz"'

def getValue(string, keyName = 'key'):
    """Find next quoted value after a key that may or may not be quoted"""
    startKey = string.find(keyName)
    # if key is quoted, adjust value search range to exclude its closing quote
    endKey = string.find('"',startKey) if string[startKey-1]=='"' else startKey + len(keyName)
    startValue = string.find('"',endKey+1)+1
    return string[startValue:string.find('"',startValue+1)]

getValue(s1) #'value'
getValue(s2) #'value'

I was inspired by the elegance of this answer, but handling the quoted and unquoted cases makes it more than a 1-liner.

You can use a comprehension such as:

next(y[1][1:-1] for y in [[l for l in x.split(':')]
     for  x in s2.split(',')] if 'key' in y[0]) # returns 'value' w/o quotes

But that won't handle the case of s2.


问:
python - calculate orthographic similarity between words of a list
I need to calculate orthographic similarity (edit/Levenshtein distance) among words in a given corpus.

As Kirill suggested below, I tried to do the following:

```<code>import csv, itertools, Levenshtein
import numpy as np

# import the list of words from csv file
path = '/Users/my path'
file = path + 'file.csv'

with open(file, 'rb') as f:
    reader = csv.reader(f)
    wordlist = list(reader)

wordlist = np.array(wordlist) #make it a np array
wordlist2 = wordlist[:,0] #subset the first column of the imported list

for a, b in itertools.product(wordlist, wordlist):
    if a < b:
        print(a, b, Levenshtein.distance(a, b))
</code>```

However, the following error pops up:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand the ambiguity in the code, but can someone help me figure out how to solve this? Thanks!

答:
Here's the code I came up with thank to the help of Kirill.</p>

```<code>import csv#, StringIO
import itertools, Levenshtein

# open the newline-separated list of words
path = '/Users/your path'
file = path + 'wordlists.txt'
output = path + 'ortho_similarities.txt'
words = sorted(set(s.strip() for s in open(file)))

# the following loop take all possible pairwise combinations
# of the words in the list words, and calculate the LD
# and then let's write everything in a csv file
with open(output, 'wb') as f:
   writer = csv.writer(f, delimter=",", lineterminator="\n")
   for a, b in itertools.product(words, words):
      if a < b:
        write.writerow([a, b, Levenshtein.distance(a,b)])
</code>```

Body:
I need to calculate orthographic similarity (edit/Levenshtein distance) among words in a given corpus.

As Kirill suggested below, I tried to do the following:

import csv, itertools, Levenshtein
import numpy as np

# import the list of words from csv file
path = '/Users/my path'
file = path + 'file.csv'

with open(file, 'rb') as f:
    reader = csv.reader(f)
    wordlist = list(reader)

wordlist = np.array(wordlist) #make it a np array
wordlist2 = wordlist[:,0] #subset the first column of the imported list

for a, b in itertools.product(wordlist, wordlist):
    if a < b:
        print(a, b, Levenshtein.distance(a, b))

However, the following error pops up:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand the ambiguity in the code, but can someone help me figure out how to solve this? Thanks!

Body:
Here's the code I came up with thank to the help of Kirill.

import csv#, StringIO
import itertools, Levenshtein

# open the newline-separated list of words
path = '/Users/your path'
file = path + 'wordlists.txt'
output = path + 'ortho_similarities.txt'
words = sorted(set(s.strip() for s in open(file)))

# the following loop take all possible pairwise combinations
# of the words in the list words, and calculate the LD
# and then let's write everything in a csv file
with open(output, 'wb') as f:
   writer = csv.writer(f, delimter=",", lineterminator="\n")
   for a, b in itertools.product(words, words):
      if a < b:
        write.writerow([a, b, Levenshtein.distance(a,b)])