问:
How to write SQL statements in succession without error
I am running a CREATE VIEW statement which is perfectly self-contained and runs perfect on its own. Two lines below I run a separate SELECT statement to view the results, which works perfect on its own.

However, I run the whole script together and it doesn't work.

Code looks something like this:

```<code>--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;

--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work
</code>```

The error message is "Incorrect syntax near the keyword 'SELECT'."

答:
Add batch separator, Go, stmt between, End of create view stmt and your select from view.

also will need to add check if view exists and drop it first stmt or change to alter or create view depending on version of sql.

```<code>IF OBJECT_ID('FOO') IS NOT NULL
DROP VIEW FOO;
GO

CREATE VIEW FOO
AS
SELECT * FROM sysobjects;
GO
SELECT * FROM FOO
GO
</code>```

Body:
I am running a CREATE VIEW statement which is perfectly self-contained and runs perfect on its own. Two lines below I run a separate SELECT statement to view the results, which works perfect on its own.

However, I run the whole script together and it doesn't work.

Code looks something like this:

--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;

--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work

The error message is "Incorrect syntax near the keyword 'SELECT'."

Body:
Add batch separator, Go, stmt between, End of create view stmt and your select from view.

also will need to add check if view exists and drop it first stmt or change to alter or create view depending on version of sql.

IF OBJECT_ID('FOO') IS NOT NULL
DROP VIEW FOO;
GO

CREATE VIEW FOO
AS
SELECT * FROM sysobjects;
GO
SELECT * FROM FOO
GO


来源: stackexchange

问:
Blocking launch of WPF Dialog from a different thread
We want to create and launch a modal dialog box over the main window. This process is initiated from a different thread - for some reason. This different thread calls the execute method - and must be blocked until the dialog box closes. The question is - how? On this code the execute won't be blocked. The Join() call also does not work as expected.

```<code>public void Execute()
{
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
    // newWindowThread.Join();
}

private void ThreadStartingPoint()
{
    this.ParameterDialog = new ParameterDialog();
    this.ParameterDialog.ShowDialog();
    System.Windows.Threading.Dispatcher.Run();
}
</code>```

Any idea how to implement this behavior? Thanks in advance!

答:
Without knowing how your whole setup works, here is a quick example of how to utilize the Dispatcher to interact with the UI layer from a seperate thread. I used the examples from the microsoft wpf library here as my starting point. I stripped out some of the code that is not applicable.

MainWindow.xaml.cs

```<code> public partial class MainWindow : Window
 {
    public delegate void NextPrimeDelegate();

    private bool _continueCalculating;

    private Action MyCallback = () =>
    {
        //****Carry out your Code (Execute) Here****
        var myPopup = new PopUp();
        myPopup.ShowDialog();
    };
    public MainWindow()
    {
        InitializeComponent();
    }

    private void StartOrStop(object sender, EventArgs e)
    {
        if (_continueCalculating)
        {
            _continueCalculating = false;
            startStopButton.Content = "Resume";
        }
        else
        {
            _continueCalculating = true;
            startStopButton.Content = "Stop";
            startStopButton.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                new NextPrimeDelegate(MyCallback));
        }
    }
}
</code>```

MyPopUp.xaml

```<code><Window x:Class="SingleThreadedApplication.PopUp"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SingleThreadedApplication"
    mc:Ignorable="d"
    Title="PopUp" Height="200" Width="300">
<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close"
                    Executed="CloseCommandHandler"/>
</Window.CommandBindings>

<Grid>
    <TextBlock Text="My Popup" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    <Button Content="Close" HorizontalAlignment="Right" VerticalAlignment="Bottom" Command="ApplicationCommands.Close"/>
</Grid>
</code>```

Add this method to the PopUp.xaml.cs

```<code>private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
   this.Close();
}
</code>```

This hopefully can give you a starting point to interact with the UI layer via different Threads.

ContentLicense: CC BY-SA 4.0

Body:
We want to create and launch a modal dialog box over the main window. This process is initiated from a different thread - for some reason. This different thread calls the execute method - and must be blocked until the dialog box closes. The question is - how? On this code the execute won't be blocked. The Join() call also does not work as expected.

public void Execute()
{
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
    // newWindowThread.Join();
}

private void ThreadStartingPoint()
{
    this.ParameterDialog = new ParameterDialog();
    this.ParameterDialog.ShowDialog();
    System.Windows.Threading.Dispatcher.Run();
}

Any idea how to implement this behavior? Thanks in advance!

Body:
Without knowing how your whole setup works, here is a quick example of how to utilize the Dispatcher to interact with the UI layer from a seperate thread. I used the examples from the microsoft wpf library here as my starting point. I stripped out some of the code that is not applicable.

MainWindow.xaml.cs

 public partial class MainWindow : Window
 {
    public delegate void NextPrimeDelegate();

    private bool _continueCalculating;

    private Action MyCallback = () =>
    {
        //****Carry out your Code (Execute) Here****
        var myPopup = new PopUp();
        myPopup.ShowDialog();
    };
    public MainWindow()
    {
        InitializeComponent();
    }

    private void StartOrStop(object sender, EventArgs e)
    {
        if (_continueCalculating)
        {
            _continueCalculating = false;
            startStopButton.Content = "Resume";
        }
        else
        {
            _continueCalculating = true;
            startStopButton.Content = "Stop";
            startStopButton.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                new NextPrimeDelegate(MyCallback));
        }
    }
}

MyPopUp.xaml

<Window x:Class="SingleThreadedApplication.PopUp"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SingleThreadedApplication"
    mc:Ignorable="d"
    Title="PopUp" Height="200" Width="300">
<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close"
                    Executed="CloseCommandHandler"/>
</Window.CommandBindings>

<Grid>
    <TextBlock Text="My Popup" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    <Button Content="Close" HorizontalAlignment="Right" VerticalAlignment="Bottom" Command="ApplicationCommands.Close"/>
</Grid>

Add this method to the PopUp.xaml.cs

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
   this.Close();
}

This hopefully can give you a starting point to interact with the UI layer via different Threads.


问:
Bash: how to certain lines but exclude certain lines in between?
I have a file that looks like this:

```<code>a: 0
a: 0
a: 0
a: 1
b: 1
c: 1
d: 1
e: 1
f: 1
a: 2
b: 2
c: 2
d: 2
e: 2
f: 2
a: 3
b: 3
c: 3
d: 3
e: 3
f: 3
c: 4
c: 4
c: 4
</code>```

I want to capture and output all of the a and c lines of the form line><anything other than an a or c line><c line> so the output would look like:

```<code>a: 1
c: 1

a: 2
c: 2

a: 3
c: 3
</code>```

Note that neither the a: 0 lines at the beginning nor the c: 4 lines at the end are captured because they don't follow the pattern I mentioned. Note also that the b lines between the a and c lines are removed.

I've been trying to do this with lookarounds usings Bash's pcregrep, but haven't found a solution yet. Any ideas?

Thanks!

答:
Using awk

Try:

```<code>$ awk -F: '$1=="a"{aline=$0} $1=="c"{if(aline)print aline ORS $0 ORS; aline=""}' file
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3
</code>```

How it works

By default, awk reads in one line at a time.

-F:

This tells awk to use : as the field separator.

$1=="a"{aline=$0}

Everytime an a line is observed, save the line in variable aline.

$1=="c"{if(aline)print aline ORS $0 ORS; aline=""}

Every time a c line is observed, check to see if we have a nonempty aline.  If so, print aline and the current line, separated by newline characters.  Also, set aline back to an empty string.

Multiline version

For those who prefer their commands spread over several lines:

```<code>awk -F: '
    $1=="a"{
        aline=$0
    }

   $1=="c"{
        if(aline)
            print aline ORS $0 ORS
        aline=""
    }' file
</code>```

Using sed

```<code>$ sed -n '/^a/h; /^c/{x;/^a/{p;x;s/$/\n/;p};h}' file
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3
</code>```

How it works

-n

This tells sed not to print anything unless we explicitly ask it to.

/^a/h

Any time we have a line that starts with a, we save it to the hold space.

/^c/{ x; /^a/{ p; x; s/$/\n/; p}; h}

Any time we have a line that starts with c, we:

We swap (x) the pattern space with the hold space.

If the new pattern space starts with a, then we print (p) it, and swap (x) again, add a new line to the end of the new pattern space (s/$/\n/) and print (p) it.

Lastly we save the current pattern space (which starts with a c) to the hold space.

Body:
I have a file that looks like this:

a: 0
a: 0
a: 0
a: 1
b: 1
c: 1
d: 1
e: 1
f: 1
a: 2
b: 2
c: 2
d: 2
e: 2
f: 2
a: 3
b: 3
c: 3
d: 3
e: 3
f: 3
c: 4
c: 4
c: 4

I want to capture and output all of the a and c lines of the form <anything other than an a or c line><c line> so the output would look like:

a: 1
c: 1

a: 2
c: 2

a: 3
c: 3

Note that neither the a: 0 lines at the beginning nor the c: 4 lines at the end are captured because they don't follow the pattern I mentioned. Note also that the b lines between the a and c lines are removed.

I've been trying to do this with lookarounds usings Bash's pcregrep, but haven't found a solution yet. Any ideas?

Thanks!

Body:
Using awk

Try:

$ awk -F: '$1=="a"{aline=$0} $1=="c"{if(aline)print aline ORS $0 ORS; aline=""}' file
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3

How it works

By default, awk reads in one line at a time.

-F:

This tells awk to use : as the field separator.

$1=="a"{aline=$0}

Everytime an a line is observed, save the line in variable aline.

$1=="c"{if(aline)print aline ORS $0 ORS; aline=""}

Every time a c line is observed, check to see if we have a nonempty aline.  If so, print aline and the current line, separated by newline characters.  Also, set aline back to an empty string.

Multiline version

For those who prefer their commands spread over several lines:

awk -F: '
    $1=="a"{
        aline=$0
    }

   $1=="c"{
        if(aline)
            print aline ORS $0 ORS
        aline=""
    }' file

Using sed

$ sed -n '/^a/h; /^c/{x;/^a/{p;x;s/$/\n/;p};h}' file
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3

How it works

-n

This tells sed not to print anything unless we explicitly ask it to.

/^a/h

Any time we have a line that starts with a, we save it to the hold space.

/^c/{ x; /^a/{ p; x; s/$/\n/; p}; h}

Any time we have a line that starts with c, we:

We swap (x) the pattern space with the hold space.

If the new pattern space starts with a, then we print (p) it, and swap (x) again, add a new line to the end of the new pattern space (s/$/\n/) and print (p) it.

Lastly we save the current pattern space (which starts with a c) to the hold space.


问:
Denormalized many-to-many mapping
In SQL Server 2008 R2 I have a table with the following structure

```<code>(
  Id     INT NOT NULL PRIMARY KEY,
  Left1  INT NOT NULL,
  Left2  INT NULL,
  Right1 NVARCHAR(128) NOT NULL,
  Right2 NVARCHAR(128) NOT NULL,
  Right3 NVARCHAR(128) NULL,
  Right4 NVARCHAR(128) NULL,
  Right5 NVARCHAR(128) NULL,
  Right6 NVARCHAR(128) NULL
)
</code>```

Which is used to map Left1 and Left2, coming from a system ("Left") into Right1-6, going to another system ("Right").

I need to ensure that the Left columns are unique, which I have done with a unique index, and that the Left-Right combinations are also unique.

I cannot use an index here because the maximum column size supported is 900 bytes. I need to avoid splitting the table in Left, Right and Left2Right - as it's way too tedious and error prone with my use cases.

What is the correct way of enforcing the uniqueness of the combination?

My requirements are:

In the whole table there MUST be no rows with the same values for Left1 and Left2 (solved)

In the whole table there MUST be no rows with the same values for Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6 (I need help here)

答:
One idea: create a lookup table of all possible "Right" values, assign them integer surrogate keys, use those surrogate keys in your Left2Right table, and build your unique constraint on them. Denormalized and ugly as sin, but it could do the trick.

(Added)

You could also try building a hash of the values and constraining on that. The poor mans’ version would be to add a calcluated row using checksum:

```<code>ALTER TABLE MyTable
 Add RightHash AS checksum(Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6)
</code>```

and add a unique constraint on that (it may have to be a persisted calculated column to do this). The main problem with this is that different sets of initial values could produce the same checksum values. You could use one of the (much more) robust hashing algorithms via the hashbytes function, which would have the same limitation (possible duplicate hash values) but the chance of collision would be significantly smaller.

ContentLicense: CC BY-SA 3.0

Title: Denormalized many-to-many mapping

Body:
In SQL Server 2008 R2 I have a table with the following structure

(
  Id     INT NOT NULL PRIMARY KEY,
  Left1  INT NOT NULL,
  Left2  INT NULL,
  Right1 NVARCHAR(128) NOT NULL,
  Right2 NVARCHAR(128) NOT NULL,
  Right3 NVARCHAR(128) NULL,
  Right4 NVARCHAR(128) NULL,
  Right5 NVARCHAR(128) NULL,
  Right6 NVARCHAR(128) NULL
)

Which is used to map Left1 and Left2, coming from a system ("Left") into Right1-6, going to another system ("Right").

I need to ensure that the Left columns are unique, which I have done with a unique index, and that the Left-Right combinations are also unique.

I cannot use an index here because the maximum column size supported is 900 bytes. I need to avoid splitting the table in Left, Right and Left2Right - as it's way too tedious and error prone with my use cases.

What is the correct way of enforcing the uniqueness of the combination?

My requirements are:

In the whole table there MUST be no rows with the same values for Left1 and Left2 (solved)

In the whole table there MUST be no rows with the same values for Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6 (I need help here)

Body:
One idea: create a lookup table of all possible "Right" values, assign them integer surrogate keys, use those surrogate keys in your Left2Right table, and build your unique constraint on them. Denormalized and ugly as sin, but it could do the trick.

(Added)

You could also try building a hash of the values and constraining on that. The poor mans’ version would be to add a calcluated row using checksum:

ALTER TABLE MyTable
 Add RightHash AS checksum(Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6)

and add a unique constraint on that (it may have to be a persisted calculated column to do this). The main problem with this is that different sets of initial values could produce the same checksum values. You could use one of the (much more) robust hashing algorithms via the hashbytes function, which would have the same limitation (possible duplicate hash values) but the chance of collision would be significantly smaller.


问:
routing inside code sandbox, failing due to withRouter
When I hit submit button I need to redirect to this page pageOne, so I googled and found a react router and used this line this.props.history.push("/anotherPage");, but its not redirecting.
Its throwing an error Invariant failed: You should not use <Route> outside a <Router>
Can you tell me how to fix it.
Providing my code snippet and sandbox below.

https://codesandbox.io/s/material-demo-n9o7s

```<code><!-- language-all: lang-or-tag-here -->

anotherPage = () => {
  console.log("redictToStepper --->");
  this.props.history.push("/anotherPage");
};

render() {
  const { classes } = this.props;
  const { checkBoxvalues } = this.state;

  return (
    <div className={classes.root}>increase when I hit submit button</div>
  );
}

export default withRouter(withStyles(styles)(RadioButtonsGroup));
</code>```

答:
You need to wrap your most-outer component using BrowserRouter, so it will provided the needed props and behavior to its children.

On your index.js replace your render with:

import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <Route exact path="/" component={Demo} />
    <Route exact path="/anotherPage" component={PageOne} />
  </BrowserRouter>, document.querySelector('#root'));

```

To render your components inside each route, please refer to react router documentation.

Body:
When I hit submit button I need to redirect to this page pageOne, so I googled and found a react router and used this line this.props.history.push("/anotherPage");, but its not redirecting.
Its throwing an error Invariant failed: You should not use <Route> outside a <Router>
Can you tell me how to fix it.
Providing my code snippet and sandbox below.

https://codesandbox.io/s/material-demo-n9o7s

anotherPage = () => {
  console.log("redictToStepper --->");
  this.props.history.push("/anotherPage");
};

render() {
  const { classes } = this.props;
  const { checkBoxvalues } = this.state;

  return (

increase when I hit submit button

  );
}

export default withRouter(withStyles(styles)(RadioButtonsGroup));

Body:
You need to wrap your most-outer component using BrowserRouter, so it will provided the needed props and behavior to its children.

On your index.js replace your render with:

import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <Route exact path="/" component={Demo} />
    <Route exact path="/anotherPage" component={PageOne} />
  </BrowserRouter>, document.querySelector('#root'));

To render your components inside each route, please refer to react router documentation.


问:
How to run some tasks in parallel, and others sequentially?
I would like to run some CD/CI tasks in parallel (independent docker builds for instance), and some others sequentially (the registry upload of these images once they are built, for instance).

The documentation gives an example of standalone tasks which are built in parallel by default:

```<code>test:
  script: cat file1.txt file2.txt | grep -q 'Hello world'

package:
  script: cat file1.txt file2.txt | gzip > packaged.gz
  artifacts:
    paths:
    - packaged.gz
</code>```

They force the sequentiality of these tasks though the stages entry:

```<code>stages:
  - test
  - package
</code>```

How can I mix both? To have, say, the tasks build_one and build_two run in parallel, and then (sequentially) package? Something along the lines of

```<code>stages:
  - build_one, build_two   # <-- these two run in parallel
  - package   # <-- this one runs only when both parallel tasks above completed successfully
</code>```

答:
Each task can be assigned a stage in which to run, and stages run sequentially in the order they are defined. If multiple tasks are assigned to the same stage, they run in parallel during that stage.

Here's an example that fits your requirement. Both build tasks run at the same time, then the package task runs afterward:

```<code>before_script:
  - echo "do some runner environment prep"

stages:
  - build
  - package

build_task1:
  stage: build
  script:
    - echo "do build1 stuff"

build_task2:
  stage: build
  script:
    - echo "do build2 stuff"

package_task:
  stage: package
  script:
    - echo "do package stuff"
</code>```

And here's a successful pipeline run using this above pipeline definition:

Body:
I would like to run some CD/CI tasks in parallel (independent docker builds for instance), and some others sequentially (the registry upload of these images once they are built, for instance).

The documentation gives an example of standalone tasks which are built in parallel by default:

test:
  script: cat file1.txt file2.txt | grep -q 'Hello world'

package:
  script: cat file1.txt file2.txt | gzip > packaged.gz
  artifacts:
    paths:
    - packaged.gz

They force the sequentiality of these tasks though the stages entry:

stages:
  - test
  - package

How can I mix both? To have, say, the tasks build_one and build_two run in parallel, and then (sequentially) package? Something along the lines of

stages:
  - build_one, build_two   # <-- these two run in parallel
  - package   # <-- this one runs only when both parallel tasks above completed successfully

Body:
Each task can be assigned a stage in which to run, and stages run sequentially in the order they are defined. If multiple tasks are assigned to the same stage, they run in parallel during that stage.

Here's an example that fits your requirement. Both build tasks run at the same time, then the package task runs afterward:

before_script:
  - echo "do some runner environment prep"

stages:
  - build
  - package

build_task1:
  stage: build
  script:
    - echo "do build1 stuff"

build_task2:
  stage: build
  script:
    - echo "do build2 stuff"

package_task:
  stage: package
  script:
    - echo "do package stuff"

And here's a successful pipeline run using this above pipeline definition:


问:
Assigning a value to a field depending on values in other fields in MySQL
I have 2 MySQL tables, one for stories and one for chapters, I have the fields created_at and main_story in the chapters table, I also have last_chapter_date and story_name in the stories table, I want the stories table to check for the latest row created in the chapters table and assign it's created_at value to the last_chapter_date field.

How do I do that?

I am sorry if my question isn't so clear, but I don't really know how to make it more clear, plus the title doesn't really explain it so well, sorry.
If you need any other information I will try my best.

Edited to provide this link for better visual explaination:
https://drive.google.com/open?id=1IfQ60Ct1mQMzgvY-UqeLdYm1D7dSTCPh

答:
```<code>stories
story_id | last_chapter_date | story_name

chapter
story_id | created_at | main_story
</code>```

I hope you have the foreign key in the chapter table as shown above, if not then its better to create the table this way and later on you can query for the latest chapter by using this query

```<code>SELECT * FROM chapter c WHERE c.story_id = <your story_id> ORDER BY created_at DESC LIMIT 1;
</code>```

Body:
stories
story_id | last_chapter_date | story_name

chapter
story_id | created_at | main_story

I hope you have the foreign key in the chapter table as shown above, if not then its better to create the table this way and later on you can query for the latest chapter by using this query

SELECT * FROM chapter c WHERE c.story_id = <your story_id> ORDER BY created_at DESC LIMIT 1;


问:
How to Skip 500 Internal Server Error and Continue Webscraping using BeautifulSoup?
I am Doing Webscraping using Python BeautifulSoup.

Getting an Error 'HTTP Error 500: Internal Server Error'.

Below is My Code

```<code>import requests
from bs4 import BeautifulSoup
import pdb
from urllib.request import urlopen
import csv
from urllib.error import HTTPError

for IPRD_ID in range(1,10):
   url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
   page = urlopen(url)
   soup = BeautifulSoup(page, "lxml")
   table = soup.findAll('table', style="width:100%")
   try:
      for tr in table:
          a = (tr.get_text())
   except:
      print('exe')
</code>```

As we have seen I am doing Using range function which Starts from 1 to 10.I checked code step by step.At IPRD_ID=3 page server error is there no data.So its creating 500 Internal Errorenter image description here

As we have seen no data so its coming error
     enter image description here

HTTP Error 500: Internal Server Error
we have seen one IPRD_ID=3 which is having error,If i give more range 1 to 100 may have more error pages.So,I want help that how to skip like this pages and move forward for webscraping

答:
In your case urlopen(URL) raises urllib.error.HTTPError exception. You can catch this exception directly, or more general-purpose exception like class Exception(BaseException): pass. Also, you can make delay between HTTP requests (This is extremely recommended in your case), as it is in my code...

```<code>import time
import requests
from bs4 import BeautifulSoup
import pdb
import urllib
from urllib.request import urlopen
import csv
from urllib.error import HTTPError

for IPRD_ID in range(1,10):
    url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
    try:
        page = urlopen(url)
    except urllib.error.HTTPError as exc:
        print('Something went wrong.')
        time.sleep(10) # wait 10 seconds and then make http request again
        continue
    else:
        print('if client get http response, start parsing.')
        soup = BeautifulSoup(page, "lxml")
        table = soup.findAll('table', style="width:100%")
        try:
            for tr in table:
                a = tr.get_text()
        except Exception as exc:
            print('Something went wrong during parsing !!!')
        finally:
            time.sleep(5) # wait 5 seconds if success, and then make HTTP request.
</code>```

Hope, it helps you.

Body:
I am Doing Webscraping using Python BeautifulSoup.

Getting an Error 'HTTP Error 500: Internal Server Error'.

Below is My Code

import requests
from bs4 import BeautifulSoup
import pdb
from urllib.request import urlopen
import csv
from urllib.error import HTTPError

for IPRD_ID in range(1,10):
   url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
   page = urlopen(url)
   soup = BeautifulSoup(page, "lxml")
   table = soup.findAll('table', style="width:100%")
   try:
      for tr in table:
          a = (tr.get_text())
   except:
      print('exe')

As we have seen I am doing Using range function which Starts from 1 to 10.I checked code step by step.At IPRD_ID=3 page server error is there no data.So its creating 500 Internal Errorenter image description here

As we have seen no data so its coming error
     enter image description here

HTTP Error 500: Internal Server Error
we have seen one IPRD_ID=3 which is having error,If i give more range 1 to 100 may have more error pages.So,I want help that how to skip like this pages and move forward for webscraping

Body:
In your case urlopen(URL) raises urllib.error.HTTPError exception. You can catch this exception directly, or more general-purpose exception like class Exception(BaseException): pass. Also, you can make delay between HTTP requests (This is extremely recommended in your case), as it is in my code...

import time
import requests
from bs4 import BeautifulSoup
import pdb
import urllib
from urllib.request import urlopen
import csv
from urllib.error import HTTPError

for IPRD_ID in range(1,10):
    url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
    try:
        page = urlopen(url)
    except urllib.error.HTTPError as exc:
        print('Something went wrong.')
        time.sleep(10) # wait 10 seconds and then make http request again
        continue
    else:
        print('if client get http response, start parsing.')
        soup = BeautifulSoup(page, "lxml")
        table = soup.findAll('table', style="width:100%")
        try:
            for tr in table:
                a = tr.get_text()
        except Exception as exc:
            print('Something went wrong during parsing !!!')
        finally:
            time.sleep(5) # wait 5 seconds if success, and then make HTTP request.

Hope, it helps you.


问:
additional text display when form field is clicked - react
i'm making a form in react and currently when the field is clicked it adds a blue border (which i would like to keep) but i would like some additional text to appear underneath, and i'm not sure how to do this?

basically, i have a field for first name and when its clicked i'd like "Enter your first name" to appear underneath this field.

here's what i currently have:

```<code><div className="form-group form-row">
    <label
       id="firstNameLabel"
       className="col-md-2 col-form-label text-md-right"
       htmlFor="firstName1"
       readOnly
    >
      First Name*
    </label>
    <div className="col-md-10">
         <input
         type="text"
         className="form-control"
         name="firstName1"
         ref="firstName1"
         placeholder="First Name"
         value={this.state.firstName1}
         onChange={this.handleChange}
         required
     />
     <div className="error" id="firstnameError" />
   </div>
 </div>
</code>```

答:
It goes like this:

In the event you want to watch for, store some flag in state, e.g.

```<code>this.setState({userClicked:true})
</code>```

The event you want to watch for could be onFocus, i.e.

```<code><input
     type="text"
     className="form-control"
     name="firstName1"
     ref="firstName1"
     placeholder="First Name"
     value={this.state.firstName1}
     onFocus={()=>{ this.setState({userClicked:true}) }}
     onChange={this.handleChange}
     required
   />
</code>```

You can also use onBlur to set the flag to false, when input loses focus,
Then in render put below code where you want the notification to appear:

```<code>....
{this.state.userClicked && <div>Enter first name</div>}
</code>```

Above line will make sure the div is rendered when userClicked is true.

Body:
i'm making a form in react and currently when the field is clicked it adds a blue border (which i would like to keep) but i would like some additional text to appear underneath, and i'm not sure how to do this?

basically, i have a field for first name and when its clicked i'd like "Enter your first name" to appear underneath this field.

here's what i currently have:

      First Name*

         <input
         type="text"
         className="form-control"
         name="firstName1"
         ref="firstName1"
         placeholder="First Name"
         value={this.state.firstName1}
         onChange={this.handleChange}
         required
     />

Body:
It goes like this:

In the event you want to watch for, store some flag in state, e.g.

this.setState({userClicked:true})

The event you want to watch for could be onFocus, i.e.

<input
     type="text"
     className="form-control"
     name="firstName1"
     ref="firstName1"
     placeholder="First Name"
     value={this.state.firstName1}
     onFocus={()=>{ this.setState({userClicked:true}) }}
     onChange={this.handleChange}
     required
   />

You can also use onBlur to set the flag to false, when input loses focus,
Then in render put below code where you want the notification to appear:

....
{this.state.userClicked && <div>Enter first name</div>}

Above line will make sure the div is rendered when userClicked is true.


答: You need to put a GO between the statements.  The semicolon is insufficient to tell the parser that they are separate batches.</p>

Title: How to write SQL statements in succession without error

Body:
I am running a CREATE VIEW statement which is perfectly self-contained and runs perfect on its own. Two lines below I run a separate SELECT statement to view the results, which works perfect on its own.

However, I run the whole script together and it doesn't work.

Code looks something like this:

--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;

--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work

The error message is "Incorrect syntax near the keyword 'SELECT'."


问:
Manually inject service into directive from component
I have directive

```<code>     @Directive({
      selector:'[appAsyncNameValidator][formControlName],[appAsyncNameValidator][ngModel]',
      providers: [
        {
          provide: NG_ASYNC_VALIDATORS,
          useExisting: forwardRef(() => AsyncNameValidatorDirective), multi: true
        }
      ]
    })

    export class AsyncNameValidatorDirective implements Validator {
       constructor(private service: any service that implements IForValidation) {
       }

      validate(c: AbstractControl): Observable<any> {
         return doSomethig(c); // => use in doSomethig service.getByName(c.value)
      }
    }

export interface IForValidation{
       getByName(name: string);
    }
</code>```

And component

```<code>@Component({
  selector: 'app-edit-role',
  template: `<input type="text" class="form-control" id="roleName" name="roleName"
             placeholder="Role name..." [(ngModel)]="role.name" appAsyncNameValidator
             required #roleName="ngModel">`,
  styleUrls: ['./edit-role.component.scss']
})

export class EditRoleComponent implements OnInit {
    constructor() {
    }
}
</code>```

And I want to make this directive generic for all services. How to inject any service into directive from component ?

答:
Edit

I've added next inputs to my directive

```<code>@Input() service: any;

@Input() methodName: string;
</code>```

And used it like this in my doSomethig(c) method:

```<code>this.service[this.methodName](value);
</code>```

In component you have to use it in next way:

```<code><input type="text" class="form-control" id="roleName" name="roleName" placeholder="Role name..."

          [(ngModel)]="role.name" appAsyncNameValidator [service]="roleService" [methodName]="'methodName'"

          required #roleName="ngModel">
</code>```

Hope this will help somebody.

Body:
I have directive

     @Directive({
      selector:'[appAsyncNameValidator][formControlName],[appAsyncNameValidator][ngModel]',
      providers: [
        {
          provide: NG_ASYNC_VALIDATORS,
          useExisting: forwardRef(() => AsyncNameValidatorDirective), multi: true
        }
      ]
    })

    export class AsyncNameValidatorDirective implements Validator {
       constructor(private service: any service that implements IForValidation) {
       }

      validate(c: AbstractControl): Observable<any> {
         return doSomethig(c); // => use in doSomethig service.getByName(c.value)
      }
    }

export interface IForValidation{
       getByName(name: string);
    }

And component

@Component({
  selector: 'app-edit-role',
  template: `<input type="text" class="form-control" id="roleName" name="roleName"
             placeholder="Role name..." [(ngModel)]="role.name" appAsyncNameValidator
             required #roleName="ngModel">`,
  styleUrls: ['./edit-role.component.scss']
})

export class EditRoleComponent implements OnInit {
    constructor() {
    }
}

And I want to make this directive generic for all services. How to inject any service into directive from component ?

Body:
Edit

I've added next inputs to my directive

@Input() service: any;

@Input() methodName: string;

And used it like this in my doSomethig(c) method:

this.service[this.methodName](value);

In component you have to use it in next way:

<input type="text" class="form-control" id="roleName" name="roleName" placeholder="Role name..."

          [(ngModel)]="role.name" appAsyncNameValidator [service]="roleService" [methodName]="'methodName'"

          required #roleName="ngModel">

Hope this will help somebody.


问:
Create a 2d array/list in python 3 based on only one number to create a blank matrix
I am attempting to create a 2D array/list that can dynamically change based on one number, so say I input the number 3, it would create a 2d array like this, with three rows and three columns. inputting 10 would create an array with 10 columns and 10 rows, etc.

```<code>array = [
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
]
</code>```

I have researched quite a bit on both google and stack overflow, neither have turned up results that actually help me a whole lot.

what I have at the moment is a function that takes one parameter (numberOfCells) and uses for loops to attempt to fill the array, it returns TypeError: 'int' object is not iterable, so I am open to suggestions to implement this in other ways

both of the chunks of code below will be creating a new cell using this class

class Cell:

    def __init__(self, id):
        self.infected = False
        self.dead = False
        self.id = id

    def printId(self):
        print(self.id)
```

<p><br><hr><br></p>

<pre class="lang-py prettyprint-override"><code>def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = [[]]
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            env.append(list(i))

    # env = list([row] * column)  # create a 2D array/list based on number of cells
    print(env)

createTestingEnv(3)
</code>```

(above) this code returns an error, so i don't know if this is the right approach.

(below) this code sort of works, but it doesn't produce the result that I would like

def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = list([row] * column)  # create a 2D array/list based on number of cells
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            k = Cell(i + j)
            k.printId()

createTestingEnv(10)
```

I'm new to python, is there something I should be doing differently?
or am I taking a totally wrong approach to this? If so, how should i go about doing this?

Thanks, Asher

答:
Try this </p>

```<code>def make_array(n):
   return [ [0]*n for i in range(n)]
</code>```

Body:
I am attempting to create a 2D array/list that can dynamically change based on one number, so say I input the number 3, it would create a 2d array like this, with three rows and three columns. inputting 10 would create an array with 10 columns and 10 rows, etc.

array = [
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
]

I have researched quite a bit on both google and stack overflow, neither have turned up results that actually help me a whole lot.

what I have at the moment is a function that takes one parameter (numberOfCells) and uses for loops to attempt to fill the array, it returns TypeError: 'int' object is not iterable, so I am open to suggestions to implement this in other ways

both of the chunks of code below will be creating a new cell using this class

class Cell:

    def __init__(self, id):
        self.infected = False
        self.dead = False
        self.id = id

    def printId(self):
        print(self.id)

def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = [[]]
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            env.append(list(i))

    # env = list([row] * column)  # create a 2D array/list based on number of cells
    print(env)

createTestingEnv(3)

(above) this code returns an error, so i don't know if this is the right approach.

(below) this code sort of works, but it doesn't produce the result that I would like

def createTestingEnv(numberOfCells):
    # creates a simulated cell tissue
    row = list(range(numberOfCells + 1))  # +1 because range uses < not <=
    column = numberOfCells
    env = list([row] * column)  # create a 2D array/list based on number of cells
    for i in range(numberOfCells):
        for j in range(numberOfCells):
            k = Cell(i + j)
            k.printId()

createTestingEnv(10)

I'm new to python, is there something I should be doing differently?
or am I taking a totally wrong approach to this? If so, how should i go about doing this?

Thanks, Asher

Body:
Try this

def make_array(n):
   return [ [0]*n for i in range(n)]


问:
why is mySQL missing a column?
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.</p>

```<code>INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')
</code>```

答:
I believe you are missing the table name.

It should be:

Insert Into [Table_name]
([Columns])
Values ([Values])

Title: why is mySQL missing a column?

Body:
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.

INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')


问:
NSLog/OSLog intermittently showing up in console
I've noticed that my NSLog (and I've also tried it with os_log) statements are not showing up consistently in the console application.

Here's some code that runs when my app starts up.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        NSLog("xyz didFinishLaunchingWithOptions")
        FirebaseApp.configure()
        NSLog("xyz FirebaseApp.configure() done")
        let db = FirestoreDelegate.db()
        let now = Date()
        NSLog("xyz about to write")
        db.collection("atest").document(DateUtils.formatTimestampGMT(now)).setData(["ts": now, "note":"delegate startup"]) {
            err in
            if let err = err {
                NSLog ("xyz error ats \(err)")
                return
            }
            NSLog("xyz wrote to ats \(DateUtils.formatTimestampGMT(now))")
        }
        NSLog("xyz after write")
        ... extraneous code removed
}
```

When I run, sometimes I see "xyz didFinishLaunchingWithOptions" and "wrote to ats", but none of the other log statements. Sometimes I see them all, but it's pretty inconsistent. Are they getting filtered or optimized out somehow?

I'm not debugging through xcode, I'm just running the app on my phone and viewing the logs through the console app on my computer.

答:
I didn't figure out why the logging is inconsistent. Instead I created a custom logger that writes to a file.

public class FileWriter {
    static func getTs() -> String {
        let timestampFormat = DateFormatter()
        timestampFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        return timestampFormat.string(from: Date())
    }

    static func write(_ text: String) {
        do {
            let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
            let url = dir.appendingPathComponent("log.txt")
            if !FileManager.default.fileExists(atPath: url.path) {
                FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil)
            }
            let fileHandle = try FileHandle(forWritingTo: url)

            let line = "\(getTs()) \(text)\n"
            let data = line.data(using: String.Encoding.utf8)!
            fileHandle.seekToEndOfFile()
            fileHandle.write(data)

            fileHandle.closeFile()
        } catch let error as NSError {
            print ("error \(error)")
        }
    }
}
```

To read the file, I added the following keys to my Info.plist "UIFileSharingEnabled"
, "LSSupportsOpeningDocumentsInPlace" and then I could open the file on my phone with the Files app.

Body:
I've noticed that my NSLog (and I've also tried it with os_log) statements are not showing up consistently in the console application.

Here's some code that runs when my app starts up.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        NSLog("xyz didFinishLaunchingWithOptions")
        FirebaseApp.configure()
        NSLog("xyz FirebaseApp.configure() done")
        let db = FirestoreDelegate.db()
        let now = Date()
        NSLog("xyz about to write")
        db.collection("atest").document(DateUtils.formatTimestampGMT(now)).setData(["ts": now, "note":"delegate startup"]) {
            err in
            if let err = err {
                NSLog ("xyz error ats \(err)")
                return
            }
            NSLog("xyz wrote to ats \(DateUtils.formatTimestampGMT(now))")
        }
        NSLog("xyz after write")
        ... extraneous code removed
}

When I run, sometimes I see "xyz didFinishLaunchingWithOptions" and "wrote to ats", but none of the other log statements. Sometimes I see them all, but it's pretty inconsistent. Are they getting filtered or optimized out somehow?

I'm not debugging through xcode, I'm just running the app on my phone and viewing the logs through the console app on my computer.

Body:
I didn't figure out why the logging is inconsistent. Instead I created a custom logger that writes to a file.

public class FileWriter {
    static func getTs() -> String {
        let timestampFormat = DateFormatter()
        timestampFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        return timestampFormat.string(from: Date())
    }

    static func write(_ text: String) {
        do {
            let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
            let url = dir.appendingPathComponent("log.txt")
            if !FileManager.default.fileExists(atPath: url.path) {
                FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil)
            }
            let fileHandle = try FileHandle(forWritingTo: url)

            let line = "\(getTs()) \(text)\n"
            let data = line.data(using: String.Encoding.utf8)!
            fileHandle.seekToEndOfFile()
            fileHandle.write(data)

            fileHandle.closeFile()
        } catch let error as NSError {
            print ("error \(error)")
        }
    }
}

To read the file, I added the following keys to my Info.plist "UIFileSharingEnabled"
, "LSSupportsOpeningDocumentsInPlace" and then I could open the file on my phone with the Files app.


问:
Case expression returning multiple rows
I'm trying to set up a binary column showing if a student has registered for the S1 or S2 term.

If the value is 0, a second row is generated. Is it possible to limit to one row for each record?

```<code>select A.ID BSU_ID,
       A.person_uid BAN_ID,
       A.NAME STU_NAME,
       B.STUDENT_CLASSIFICATION_DESC BSU_Class,
       A.ACADEMIC_YEAR YEAR,
       A.ACADEMIC_PERIOD TERM,
       case when A.SUB_ACADEMIC_PERIOD in ('S1') then 1 else 0 end as S1_Enroll,
       case when A.SUB_ACADEMIC_PERIOD in ('S2') then 1 else 0 end as S2_Enroll

from odsmgr.student_course A,
     odsmgr.student B

where a.person_uid = b.person_uid
  and A.id = b.id
  and A.name = b.name
  and A.academic_period = '201950'
  and B.academic_period = '201950'
  and A.COURSE_BILLING_CREDITS >0.0
  and A.registration_status is not null

order by 1
</code>```

Sample Output (some columns removed for brevity):

```<code>|BSU_ID     |STU_NAME     |BSU_CLASS   |S1_ENROLL   |S2_ENROLL
|999        |Michele M    |Non-Degree  |1           |0
|999        |Michele M    |Non-Degree  |0           |1
|999        |Michele M    |Non-Degree  |1           |0
|999        |Michele M    |Non-Degree  |0           |1
</code>```

答:
use row_number()   </p>

```<code>select * from ( select
    A.ID BSU_ID,
    A.person_uid BAN_ID,
    A.NAME STU_NAME,
    B.STUDENT_CLASSIFICATION_DESC BSU_Class,
    A.ACADEMIC_YEAR YEAR,
    A.ACADEMIC_PERIOD TERM,
    case when A.SUB_ACADEMIC_PERIOD in ('S1') then 1 else 0 end as S1_Enroll,
    case when A.SUB_ACADEMIC_PERIOD in ('S2') then 1 else 0 end as S2_Enroll,
    row_number() over(partition by A.person_uid order by A.ACADEMIC_PERIOD ) rn

    from odsmgr.student_course A join
    odsmgr.student B

    on
    a.person_uid = b.person_uid
    and A.id = b.id
    and A.name = b.name
    and A.academic_period = '201950'
    and B.academic_period = '201950'
    where
     A.COURSE_BILLING_CREDITS >0.0
    and A.registration_status is not null
  ) cte where rn=1
</code>```

Title: Case expression returning multiple rows

Body:
I'm trying to set up a binary column showing if a student has registered for the S1 or S2 term.

If the value is 0, a second row is generated. Is it possible to limit to one row for each record?

select A.ID BSU_ID,
       A.person_uid BAN_ID,
       A.NAME STU_NAME,
       B.STUDENT_CLASSIFICATION_DESC BSU_Class,
       A.ACADEMIC_YEAR YEAR,
       A.ACADEMIC_PERIOD TERM,
       case when A.SUB_ACADEMIC_PERIOD in ('S1') then 1 else 0 end as S1_Enroll,
       case when A.SUB_ACADEMIC_PERIOD in ('S2') then 1 else 0 end as S2_Enroll

from odsmgr.student_course A,
     odsmgr.student B

where a.person_uid = b.person_uid
  and A.id = b.id
  and A.name = b.name
  and A.academic_period = '201950'
  and B.academic_period = '201950'
  and A.COURSE_BILLING_CREDITS >0.0
  and A.registration_status is not null

order by 1

Sample Output (some columns removed for brevity):

|BSU_ID     |STU_NAME     |BSU_CLASS   |S1_ENROLL   |S2_ENROLL
|999        |Michele M    |Non-Degree  |1           |0
|999        |Michele M    |Non-Degree  |0           |1
|999        |Michele M    |Non-Degree  |1           |0
|999        |Michele M    |Non-Degree  |0           |1

Body:
use row_number()

select * from ( select
    A.ID BSU_ID,
    A.person_uid BAN_ID,
    A.NAME STU_NAME,
    B.STUDENT_CLASSIFICATION_DESC BSU_Class,
    A.ACADEMIC_YEAR YEAR,
    A.ACADEMIC_PERIOD TERM,
    case when A.SUB_ACADEMIC_PERIOD in ('S1') then 1 else 0 end as S1_Enroll,
    case when A.SUB_ACADEMIC_PERIOD in ('S2') then 1 else 0 end as S2_Enroll,
    row_number() over(partition by A.person_uid order by A.ACADEMIC_PERIOD ) rn

    from odsmgr.student_course A join
    odsmgr.student B

    on
    a.person_uid = b.person_uid
    and A.id = b.id
    and A.name = b.name
    and A.academic_period = '201950'
    and B.academic_period = '201950'
    where
     A.COURSE_BILLING_CREDITS >0.0
    and A.registration_status is not null
  ) cte where rn=1


问:
Get icon from Mime type that looks exactly like icon in files app in Android
I want to get the exact same file icon that files app using. I want to get the icon by mime type or extension. Is there any API that returns icon by mime type.

I've tried this solution.
https://stackoverflow.com/a/8248593/7024263

but it returns the icon of an app that handles that kind of files

I want icon like shown in
image

答:
Yes, but only on Android Q and higher: getTypeInfo() on ContentResolver.

With luck, it will be added to ContentResolverCompat.


问:
How to inject DbContext into repository constructor in ASP.NET core
I am writing my first ASP.NET Core Web API and am trying to work out how to inject my DbContext object into my repository constructor. I followed the EF part of this tutorial where the DbContext is registered to the service collection via services.AddDbContext<DbContext> and services.GetRequiredService<DbContext>() is used to initialize the database values.

```<code>    public class Startup
    {

        public IConfiguration Configuration {

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton<IItemRepository, ItemRepository>();
            services.AddSingleton<IUserRepository, UserRepository>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });

            services.AddDbContext<RAFYCContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        }
    }
</code>```

```<code>    public class Program
    {
        public static void Main(string[] args)
        {
            //CreateWebHostBuilder(args).Build().Run();

            IWebHost host = CreateWebHostBuilder(args).Build();

            using (IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider services = scope.ServiceProvider;
                try
                {
                    RAFYCContext context = services.GetRequiredService<RAFYCContext>();
                    DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    ILogger logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }
    }
</code>```

I am able to inject the DbContext into the Controller and then call a repository method to assign it to the UserRepository:

```<code>    public class UserController : ControllerBase
    {
        IUserRepository _userRepo;

        public UserController(IUserRepository userRepo, RAFYCContext context)
        {
            _userRepo = userRepo;
            _userRepo.SetDbContext(context);
        }
    }
</code>```

```<code>    public class UserRepository : IUserRepository
    {
        public RAFYCContext _context;

        public UserRepository() { }

        public void SetDbContext(RAFYCContext context)
        {
            this._context = context;
        }
    }
</code>```

This works, however I would like to inject the DbContext into the constructor of my repository rather than assigning it in the Controller constructor after instantiation, like below:

```<code>    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        IUserRepository _userRepo;

        public UserController(IUserRepository userRepo)
        {
            _userRepo = userRepo;
        }
    }
</code>```

```<code>    public class UserRepository : IUserRepository
    {
        RAFYCContext _context;

        public UserRepository(RAFYCContext context)
        {
            _context = context;
        }
    }
</code>```

With this code I get the following error:

InvalidOperationException: Cannot consume scoped service
  'RAFYC.MobileAppService.Models.RAFYCContext' from singleton
  'RAFYC.MobileAppService.Repositories.IUserRepository'

Does anyone know if this is possible with ASP.NET Core (2.2)?

答:
AddDbContext adds a DbContext as scoped by default, which would cause problems with the singleton repositories.

It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.

Reference Dependency injection in ASP.NET Core: Service lifetimes

I would suggest adding the repositories as scoped as well if possible.

```<code>services.AddScoped<IItemRepository, ItemRepository>();
services.AddScoped<IUserRepository, UserRepository>();
</code>```

Body:
I am writing my first ASP.NET Core Web API and am trying to work out how to inject my DbContext object into my repository constructor. I followed the EF part of this tutorial where the DbContext is registered to the service collection via services.AddDbContext<DbContext> and services.GetRequiredService<DbContext>() is used to initialize the database values.

    public class Startup
    {

        public IConfiguration Configuration {

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton<IItemRepository, ItemRepository>();
            services.AddSingleton<IUserRepository, UserRepository>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });

            services.AddDbContext<RAFYCContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            //CreateWebHostBuilder(args).Build().Run();

            IWebHost host = CreateWebHostBuilder(args).Build();

            using (IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider services = scope.ServiceProvider;
                try
                {
                    RAFYCContext context = services.GetRequiredService<RAFYCContext>();
                    DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    ILogger logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }
    }

I am able to inject the DbContext into the Controller and then call a repository method to assign it to the UserRepository:

    public class UserController : ControllerBase
    {
        IUserRepository _userRepo;

        public UserController(IUserRepository userRepo, RAFYCContext context)
        {
            _userRepo = userRepo;
            _userRepo.SetDbContext(context);
        }
    }

    public class UserRepository : IUserRepository
    {
        public RAFYCContext _context;

        public UserRepository() { }

        public void SetDbContext(RAFYCContext context)
        {
            this._context = context;
        }
    }

This works, however I would like to inject the DbContext into the constructor of my repository rather than assigning it in the Controller constructor after instantiation, like below:

    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        IUserRepository _userRepo;

        public UserController(IUserRepository userRepo)
        {
            _userRepo = userRepo;
        }
    }

    public class UserRepository : IUserRepository
    {
        RAFYCContext _context;

        public UserRepository(RAFYCContext context)
        {
            _context = context;
        }
    }

With this code I get the following error:

InvalidOperationException: Cannot consume scoped service
  'RAFYC.MobileAppService.Models.RAFYCContext' from singleton
  'RAFYC.MobileAppService.Repositories.IUserRepository'

Does anyone know if this is possible with ASP.NET Core (2.2)?

Body:
AddDbContext adds a DbContext as scoped by default, which would cause problems with the singleton repositories.

It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.

Reference Dependency injection in ASP.NET Core: Service lifetimes

I would suggest adding the repositories as scoped as well if possible.

services.AddScoped<IItemRepository, ItemRepository>();
services.AddScoped<IUserRepository, UserRepository>();


问:
R - Loop over several files
I want to apply this code on several lists of dataframes (df).

```<code>df1<- lapply(df1, function(x) {
  x$Date <- as.Date((x$Date), format="%Y-%m-%d")
  x})
</code>```

The dataframe lists are called df1, df2, df3, df4 and abc1, abc2, abc3, abc4. The Date-column is always on the same place.

I tried this to get the df1-4 done, but it doesn't work.

```<code>for (i in 1:4) {
  df[i] <- lapply(df[i], function(x) {
  x$Date <- as.Date((x$Date), format="%Y-%m-%d")
  x})}
</code>```

I also thought about getting all the filenames into a list and looping with that:

```<code>df_list = c("df1","df2", "df3", "df4", "abc1", "abc2", "abc3", "abc4")
</code>```

But I haven't succeeded with that. I want to keep the original names of the files. Any suggestions?

答:
```<code>for(i in 1:length(df_list)) {
  df_list[[i]] <- lapply(df_list[[i]], function(x) {
    x$Date <- as.Date((x$Date), format="%Y-%m-%d")
    x})
}
</code>```

Does this work for you?

For me it does:

```<code>class(df_list[[1]][[1]]$Date)
[1] "Date"
</code>```

Your error seemed to happen because you used [] instead of [[]]. You have to use double brackets to refer to the data.frame.

Title: R - Loop over several files

Body:
I want to apply this code on several lists of dataframes (df).

df1<- lapply(df1, function(x) {
  x$Date <- as.Date((x$Date), format="%Y-%m-%d")
  x})

The dataframe lists are called df1, df2, df3, df4 and abc1, abc2, abc3, abc4. The Date-column is always on the same place.

I tried this to get the df1-4 done, but it doesn't work.

for (i in 1:4) {
  df[i] <- lapply(df[i], function(x) {
  x$Date <- as.Date((x$Date), format="%Y-%m-%d")
  x})}

I also thought about getting all the filenames into a list and looping with that:

df_list = c("df1","df2", "df3", "df4", "abc1", "abc2", "abc3", "abc4")

But I haven't succeeded with that. I want to keep the original names of the files. Any suggestions?

Body:
for(i in 1:length(df_list)) {
  df_list[[i]] <- lapply(df_list[[i]], function(x) {
    x$Date <- as.Date((x$Date), format="%Y-%m-%d")
    x})
}

Does this work for you?

For me it does:

class(df_list[[1]][[1]]$Date)
[1] "Date"

Your error seemed to happen because you used [] instead of [[]]. You have to use double brackets to refer to the data.frame.


问:
How to import excel file from angular to asp.core, than read data and push it in List
I have found package like NPOI, but i dont know how to stream file, or how to convert it to bit before sending to asp.core. Curently i am using Angular 6</p>

答:
Here's some old code that might help.  Note that the first method was added because I found it was quicker to send the data from Angular to the controller, process, and then send back as opposed to processing the data in JavaScript.</p>

```<code>    /// <summary>
    /// Converts an uploaded Excel file (multipart) to a JSON object. Useful for converting large Excel files instead
    /// of doing so in the browser, due to performance issues with SheetJS JavaScript library.
    /// </summary>
    [HttpPost]
    [Route("ConvertedFile")]
    [SwaggerResponse(HttpStatusCode.OK, "Success", typeof(List<Dictionary<string, object>>))]
    public async Task<IHttpActionResult> GetConvertedFile()
    {
        var fileData = await processUploadFile();

        fileData = removeEmptyRows(fileData);

        return Ok(fileData);
    }

    /// <summary>
    /// Converts an uploaded Excel file (multipart) to a JSON object. Sends the file to be processed.
    /// </summary>
    [HttpPost]
    [Route("")]
    [Authorize]
    [SwaggerResponse(HttpStatusCode.OK, "Success")]
    public Task<IHttpActionResult> UploadExcelFile()
    {
        var uploadFileData = await processUploadFile();

        // Do something with uploadFileData...

        return Ok();
    }

    /// <summary>
    /// Processes the upload file by converting uploaded Excel file (XLSX) to "JSON" object.
    /// </summary>
    /// <returns></returns>
    /// <exception cref="HttpResponseException"></exception>
    private async Task<List<Dictionary<string, object>>> processUploadFile()
    {
        var documentData = new List<Dictionary<string, object>>();

        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
        }

        try
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            // Manage the multipart file in memory, not on the file system
            MultipartMemoryStreamProvider streamProvider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(streamProvider);

            // Should have only one "content" or file.
            HttpContent content = streamProvider.Contents.FirstOrDefault();

            // Convert the HttpContent to a Stream
            using (Stream fileUploadStream = await content.ReadAsStreamAsync())
            {
                // Convert the Excel file stream to a List of "rows"
                documentData = ExcelManager.ExcelDataReader(fileUploadStream);

                if (documentData != null)
                {
                    // header rows are not represented in the Values.
                    Log.Information("Order Data - Processed {0} lines of file data", documentData.Count);
                }
                else
                {
                    Log.Warning("File processing error. No data.");
                }
            }

            sw.Stop();

            Log.Debug("Excel File took {0} ms", sw.ElapsedMilliseconds);
        }
        catch (Exception ex)
        {
            Log.Error(ex, string.Format("Test File Processing error."));
            throw;
        }

        return documentData;
    }

    /// <summary>
    /// Removes the empty rows.
    /// </summary>
    /// <param name="documentData">
    /// Represent a list of excel rows. Each list item represent a row. Each Dictionary key represent the column
    /// name. Dictionary value represent cell value.
    /// </param>
    /// <returns></returns>
    private List<Dictionary<string, object>> removeEmptyRows(List<Dictionary<string, object>> documentData)
    {
        // build a new collection that only contains rows that have at least one column with a value
        List<Dictionary<string, object>> nonEmptyRows = new List<Dictionary<string, object>>();

        if (documentData != null && documentData.Count > 0)
        {
            // evaluate each item in the list
            foreach (var item in documentData)
            {
                bool isRowEmpty = false;

                // evaluate each Key/Value pair.
                // RowID, State, and Message are the fields added to the document for state tracking.
                // Do not consider those fields.
                foreach (var key in item.Keys)
                {
                    if (key != "RowID" && key != "State" && key != "Message")
                    {
                        var value = item[key];

                        Type type = value.GetType();

                        isRowEmpty = type.Name == "DBNull";
                    }

                    // if an non-null value is found within the current row then stop processing this item and
                    // continue on to the next item (excel row).
                    if (!isRowEmpty)
                    {
                        break;
                    }
                }

                // if the row has user supplied data then include it
                if (!isRowEmpty)
                {
                    nonEmptyRows.Add(item);
                }
            }

            Log.Information("Removed {0} empty rows from excel File", documentData.Count - nonEmptyRows.Count);
        }

        return nonEmptyRows;
    }

using Excel;
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
public static class ExcelManager
{
    /// <summary>
    /// Read the steam file to convert it into a list of dictionaries
    /// </summary>
    /// <param name="fileUploadStream">The file stream</param>
    /// <param name="columnNames">The column names to be read in the excel file</param>
    /// <returns></returns>
    public static List<Dictionary<string, object>> ExcelDataReader(Stream fileUploadStream)
    {
        List<Dictionary<string, object>> docData = new List<Dictionary<string, object>>();

        IExcelDataReader excelReader = null;

        try
        {
            excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileUploadStream);

            // Columns names are not handled
            excelReader.IsFirstRowAsColumnNames = true;

            bool isEmpty = isFileEmpty(excelReader);

            if (!isEmpty)
            {
                // note: files that have only the header row will throw an exception when AsDataSet is called.
                DataSet ds = excelReader.AsDataSet();

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Dictionary<string, object> data = new Dictionary<string, object>();

                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        data[col.ColumnName] = row[col];
                    }
                    //This filter duplicates inserts with the same OrderLinkId
                    if ((docData.Exists(e => e.Values.ElementAt(0).Equals(data.Values.ElementAt(0)) && e.Values.ElementAt(1).Equals(data.Values.ElementAt(1))) == false))
                    {
                        docData.Add(data);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex, "");
            throw;
        }
        finally
        {
            excelReader.Close();
        }

        return docData;
    }

    /// <summary>
    /// Verifies the file has at least one row of data. No header fields are used in the file.
    /// </summary>
    /// <param name="excelReader">The excel reader.</param>
    /// <returns></returns>
    private static bool isFileEmpty(IExcelDataReader excelReader)
    {
        try
        {
            while (excelReader.Read())
            {
                return false;
            }
        }
        catch (Exception)
        {
            // swallow this exception.
        }

        return true;
    }
}
</code>```

Body:
Here's some old code that might help.  Note that the first method was added because I found it was quicker to send the data from Angular to the controller, process, and then send back as opposed to processing the data in JavaScript.

    /// <summary>
    /// Converts an uploaded Excel file (multipart) to a JSON object. Useful for converting large Excel files instead
    /// of doing so in the browser, due to performance issues with SheetJS JavaScript library.
    /// </summary>
    [HttpPost]
    [Route("ConvertedFile")]
    [SwaggerResponse(HttpStatusCode.OK, "Success", typeof(List<Dictionary<string, object>>))]
    public async Task<IHttpActionResult> GetConvertedFile()
    {
        var fileData = await processUploadFile();

        fileData = removeEmptyRows(fileData);

        return Ok(fileData);
    }

    /// <summary>
    /// Converts an uploaded Excel file (multipart) to a JSON object. Sends the file to be processed.
    /// </summary>
    [HttpPost]
    [Route("")]
    [Authorize]
    [SwaggerResponse(HttpStatusCode.OK, "Success")]
    public Task<IHttpActionResult> UploadExcelFile()
    {
        var uploadFileData = await processUploadFile();

        // Do something with uploadFileData...

        return Ok();
    }

    /// <summary>
    /// Processes the upload file by converting uploaded Excel file (XLSX) to "JSON" object.
    /// </summary>
    /// <returns></returns>
    /// <exception cref="HttpResponseException"></exception>
    private async Task<List<Dictionary<string, object>>> processUploadFile()
    {
        var documentData = new List<Dictionary<string, object>>();

        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
        }

        try
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            // Manage the multipart file in memory, not on the file system
            MultipartMemoryStreamProvider streamProvider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(streamProvider);

            // Should have only one "content" or file.
            HttpContent content = streamProvider.Contents.FirstOrDefault();

            // Convert the HttpContent to a Stream
            using (Stream fileUploadStream = await content.ReadAsStreamAsync())
            {
                // Convert the Excel file stream to a List of "rows"
                documentData = ExcelManager.ExcelDataReader(fileUploadStream);

                if (documentData != null)
                {
                    // header rows are not represented in the Values.
                    Log.Information("Order Data - Processed {0} lines of file data", documentData.Count);
                }
                else
                {
                    Log.Warning("File processing error. No data.");
                }
            }

            sw.Stop();

            Log.Debug("Excel File took {0} ms", sw.ElapsedMilliseconds);
        }
        catch (Exception ex)
        {
            Log.Error(ex, string.Format("Test File Processing error."));
            throw;
        }

        return documentData;
    }

    /// <summary>
    /// Removes the empty rows.
    /// </summary>
    /// <param name="documentData">
    /// Represent a list of excel rows. Each list item represent a row. Each Dictionary key represent the column
    /// name. Dictionary value represent cell value.
    /// </param>
    /// <returns></returns>
    private List<Dictionary<string, object>> removeEmptyRows(List<Dictionary<string, object>> documentData)
    {
        // build a new collection that only contains rows that have at least one column with a value
        List<Dictionary<string, object>> nonEmptyRows = new List<Dictionary<string, object>>();

        if (documentData != null && documentData.Count > 0)
        {
            // evaluate each item in the list
            foreach (var item in documentData)
            {
                bool isRowEmpty = false;

                // evaluate each Key/Value pair.
                // RowID, State, and Message are the fields added to the document for state tracking.
                // Do not consider those fields.
                foreach (var key in item.Keys)
                {
                    if (key != "RowID" && key != "State" && key != "Message")
                    {
                        var value = item[key];

                        Type type = value.GetType();

                        isRowEmpty = type.Name == "DBNull";
                    }

                    // if an non-null value is found within the current row then stop processing this item and
                    // continue on to the next item (excel row).
                    if (!isRowEmpty)
                    {
                        break;
                    }
                }

                // if the row has user supplied data then include it
                if (!isRowEmpty)
                {
                    nonEmptyRows.Add(item);
                }
            }

            Log.Information("Removed {0} empty rows from excel File", documentData.Count - nonEmptyRows.Count);
        }

        return nonEmptyRows;
    }

using Excel;
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
public static class ExcelManager
{
    /// <summary>
    /// Read the steam file to convert it into a list of dictionaries
    /// </summary>
    /// <param name="fileUploadStream">The file stream</param>
    /// <param name="columnNames">The column names to be read in the excel file</param>
    /// <returns></returns>
    public static List<Dictionary<string, object>> ExcelDataReader(Stream fileUploadStream)
    {
        List<Dictionary<string, object>> docData = new List<Dictionary<string, object>>();

        IExcelDataReader excelReader = null;

        try
        {
            excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileUploadStream);

            // Columns names are not handled
            excelReader.IsFirstRowAsColumnNames = true;

            bool isEmpty = isFileEmpty(excelReader);

            if (!isEmpty)
            {
                // note: files that have only the header row will throw an exception when AsDataSet is called.
                DataSet ds = excelReader.AsDataSet();

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Dictionary<string, object> data = new Dictionary<string, object>();

                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        data[col.ColumnName] = row[col];
                    }
                    //This filter duplicates inserts with the same OrderLinkId
                    if ((docData.Exists(e => e.Values.ElementAt(0).Equals(data.Values.ElementAt(0)) && e.Values.ElementAt(1).Equals(data.Values.ElementAt(1))) == false))
                    {
                        docData.Add(data);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex, "");
            throw;
        }
        finally
        {
            excelReader.Close();
        }

        return docData;
    }

    /// <summary>
    /// Verifies the file has at least one row of data. No header fields are used in the file.
    /// </summary>
    /// <param name="excelReader">The excel reader.</param>
    /// <returns></returns>
    private static bool isFileEmpty(IExcelDataReader excelReader)
    {
        try
        {
            while (excelReader.Read())
            {
                return false;
            }
        }
        catch (Exception)
        {
            // swallow this exception.
        }

        return true;
    }
}


问:
Is this package registered correctly on npm?
UWS is deprecated, now you can install μWebSockets like so

npm install uNetworking/uWebSockets.js#v15.10.0

It gets installed but when you want to update your packages npm update you get

```<code>npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/uWebSockets.js - Not found
npm ERR! 404
npm ERR! 404  'uWebSockets.js@^15.10.0' is not in the npm registry.
npm ERR! 404 Your package name is not valid, because
npm ERR! 404  1. name can no longer contain capital letters
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/user/.npm/_logs/2019-05-29T10_19_50_672Z-debug.log
</code>```

The owner believes it's NPM's fault since he registered the previous package and since you can install the current package using npm why wouldn't you be able to update?

When you search for it on npmjs.com, the new package doesn't show, so I wonder how is it possible to install it in the first place if it's not registered and how to fix it without affecting the current users?

答:
Contacted npmjs.com, they didn't know why it was happening, nor the owner of the repository.

When Artem Arkhipov commented saying that he did not encounter any errors, I uninstalled and reinstalled the package and everything seem to be working.

If anyone ever encounter this error, please let me know, and I'll tell the owner of the repository how to fix it.

Body:
UWS is deprecated, now you can install μWebSockets like so

npm install uNetworking/uWebSockets.js#v15.10.0

It gets installed but when you want to update your packages npm update you get

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/uWebSockets.js - Not found
npm ERR! 404
npm ERR! 404  'uWebSockets.js@^15.10.0' is not in the npm registry.
npm ERR! 404 Your package name is not valid, because
npm ERR! 404  1. name can no longer contain capital letters
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/user/.npm/_logs/2019-05-29T10_19_50_672Z-debug.log

The owner believes it's NPM's fault since he registered the previous package and since you can install the current package using npm why wouldn't you be able to update?

When you search for it on npmjs.com, the new package doesn't show, so I wonder how is it possible to install it in the first place if it's not registered and how to fix it without affecting the current users?


问:
Regex in Java for "greater than" or "less than" without using bracket "<|>" symbols
I need a regular expression for Java Pattern.compile("<|>") that would match greater than and less than symbols without actually using bracket symbols. Is there some special character that would mean ">" or "<" symbol?

Additional info: The reason is that my legacy system passes regular expressions from a resource file that first gets parsed using some html tags, and extra brackets confuse the parser, so it errors out. The solution is to substitute ">" and "<" with something else that Java Pattern would interpret as ">" and "<".

What I tried: Pattern.compile("&grt;") does not get interpreted as ">"

答:
There are several ways to do that:

You could write it down as ASCII ordinals, like this: ((char) 60) + "|" + ((char) 62);

You could use Unicode escape sequences in the regular expression: \\u003c|\\u003e;

You could use Java Unicode escape sequences, like this: \u003c|\u003e.

About that last point — it is seldom used, but the programmer may use Unicode escape sequences anywhere in the Java source code. For instance,

```<code>public\u0020class\u0020Main {
    public\u0020static\u0020void\u0020main(String[] args) { }
}
</code>```

is valid Java code.

Body:
There are several ways to do that:

You could write it down as ASCII ordinals, like this: ((char) 60) + "|" + ((char) 62);

You could use Unicode escape sequences in the regular expression: \\u003c|\\u003e;

You could use Java Unicode escape sequences, like this: \u003c|\u003e.

About that last point — it is seldom used, but the programmer may use Unicode escape sequences anywhere in the Java source code. For instance,

public\u0020class\u0020Main {
    public\u0020static\u0020void\u0020main(String[] args) { }
}

is valid Java code.


问:
Why multiple driver issue with some assignments but not others in verilog simulation
Hi why is it that VCS simulation allows for some assignments from 2 different always block, while for some others it is not allowed

In the code below:
While compiling with the variable pass_val but without rollover_n the compile and run of the code seems fine. No issue

However when I introduced rollover_n as seen in the code below, I get the compiler error "illegal combination of procedural drivers", pointing that rollover_n is assigned in 2 different always block.

Both of these rollover_n and pass_val are assigned values in 2 different always block, but rollover_n gets an error message, while pass_val is allowed

here is the pseudocode :

```<code>
input power
input[47:0] input_array
logic [11:0] slice[3:0]
logic [11:0] moving_comparator
logic [11:0] pass_val

initial
slice[3:0] = {0,0,0,0};
moving_comparator = 0;
pass_val = 0;:

//bit slicing block
always_comb begin
  if(enable[0]==1 && power==1)
    slice[0] = input_array[11:0];
  else if (power==0)
    slice[0] = 0;
  if(enable[1]==1 && power==1)
    slice[1] = input_array[23:12];
  else if (power==0)
    slice[1] = 0;
  if(enable[2]==1 && power==1)
    slice[2] = input_array[35:24];
  else if (power==0)
    slice[2] = 0;
  if(enable[3]==1 && power==1)
    slice[3] = input_array[47:36];
  else if (power==0)
    slice[3] = 0;

  foreach(slice[i])begin
    if(moving_comparator<slice[i] && power==1)moving_comparator = slice[i];
    else if (power==0) moving_comparator = 0;
  end
    pass_val = moving_comparator;
    if(pass_val == 0 && ((|enable) == 1)) rollover_n = 1;//~(|moving_comparator) ;// just to trigger the arbitration block in case assignment to pass_val is actually 0
    else seqnum_rollover_n = 0;
    foreach(slice[i])begin //IMPORTANT!! make sure moving comparator dont compare with stale values from prev selects
        slice[i] = 0;
    end
    moving_comparator = 0;
end

//arbitration block
always @(pass_val,compare,rollover_n) begin
  if(pass_val>compare)begin output=pass_val;
    pass_val = 0;
  end
  else begin
    output=compare;
  end

  if(rollover_n) begin
    rollover_n = 0;
 end
end

</code>```

So, why is it that pass_val is allowed to be assigned values in

always @(pass_val,compare,rollover_n) and always_comb but rollover_n is not

答:
I copied your code and ran it with some typos fixed (missing semi-colons in the inputs definitions and added begin/end to initial block. I get an error for both nets.

Parsing design file 'test.sv' Top Level Modules:
         test No TimeScale specified

Error-[ICPD] Illegal combination of drivers
  test.sv, 8

  Illegal combination of procedural drivers

  Variable "pass_val" is driven by an invalid combination of procedural
  drivers. Variables written onleft-hand of "always_comb" cannot be written

   to by any other processes, including other "always_comb" processes.

  This variable is declared at "test.sv", 8: logic [11:0] pass_val;

  The first driver is at "test.sv", 60: pass_val = 0;

  The second driver is at "test.sv", 25: always_comb  begin   if ((enable[0] == 1'b1) && (power == 1'b1))
  begin    ...

Error-[ICPD] Illegal combination of drivers
  test.sv, 13
   Illegal combination of procedural drivers

  Variable "rollover_n" is driven by an invalid combination of procedural
   drivers. Variables written on left-hand of "always_comb" cannot be written

   to by any other processes, including other "always_comb" processes.
   This variable is declared at "test.sv", 13: logic rollover_n;

   The first driver is at "test.sv", 67: rollover_n = 0;

  The second driver is at "test.sv", 25: always_comb  begin   if ((enable[0] == 1'b1) && (power == 1'b1))
  begin    ...

2 errors CPU time: .066 seconds to compile

Body:
Hi why is it that VCS simulation allows for some assignments from 2 different always block, while for some others it is not allowed

In the code below:
While compiling with the variable pass_val but without rollover_n the compile and run of the code seems fine. No issue

However when I introduced rollover_n as seen in the code below, I get the compiler error "illegal combination of procedural drivers", pointing that rollover_n is assigned in 2 different always block.

Both of these rollover_n and pass_val are assigned values in 2 different always block, but rollover_n gets an error message, while pass_val is allowed

here is the pseudocode :

input power
input[47:0] input_array
logic [11:0] slice[3:0]
logic [11:0] moving_comparator
logic [11:0] pass_val

initial
slice[3:0] = {0,0,0,0};
moving_comparator = 0;
pass_val = 0;:

//bit slicing block
always_comb begin
  if(enable[0]==1 && power==1)
    slice[0] = input_array[11:0];
  else if (power==0)
    slice[0] = 0;
  if(enable[1]==1 && power==1)
    slice[1] = input_array[23:12];
  else if (power==0)
    slice[1] = 0;
  if(enable[2]==1 && power==1)
    slice[2] = input_array[35:24];
  else if (power==0)
    slice[2] = 0;
  if(enable[3]==1 && power==1)
    slice[3] = input_array[47:36];
  else if (power==0)
    slice[3] = 0;

  foreach(slice[i])begin
    if(moving_comparator<slice[i] && power==1)moving_comparator = slice[i];
    else if (power==0) moving_comparator = 0;
  end
    pass_val = moving_comparator;
    if(pass_val == 0 && ((|enable) == 1)) rollover_n = 1;//~(|moving_comparator) ;// just to trigger the arbitration block in case assignment to pass_val is actually 0
    else seqnum_rollover_n = 0;
    foreach(slice[i])begin //IMPORTANT!! make sure moving comparator dont compare with stale values from prev selects
        slice[i] = 0;
    end
    moving_comparator = 0;
end

//arbitration block
always @(pass_val,compare,rollover_n) begin
  if(pass_val>compare)begin output=pass_val;
    pass_val = 0;
  end
  else begin
    output=compare;
  end

  if(rollover_n) begin
    rollover_n = 0;
 end
end

So, why is it that pass_val is allowed to be assigned values in

always @(pass_val,compare,rollover_n) and always_comb but rollover_n is not


问:
Can't Send Email using Visual Basic from Windows 7 pc: "The operation has timed out"
When trying to send an email using a Visual Basic Console App I get an error: "The operation timed out".  I'm sending from a Windows 7 pc.  Can this be done?

I've found many posts that say it fails because there is no SMTP client on Windows 7.  However, I downloaded smpt4dev and get the same results when I try to connect to that via "localhost".

But I can telnet to the server from the same pc and get no errors. I can also send  an email using these telnet commands:

```<code>telnet SMTP.domain.xyz 25
helo SMTP.domain.xyz
mail from: f@domain.com
rcpt to: t@domain.com
data
subject: test email
.
quit
</code>```

I have tried this with a few different smtp servers and I get the same results.  I know that my server name, port, username and pw are correct.

```<code>Imports System.Net.Mail

Try
         Dim SMTPClientObj As New Net.Mail.SmtpClient
         SMTPClientObj.UseDefaultCredentials = False
         SMTPClientObj.Credentials = New System.Net.NetworkCredential(username, password)
         SMTPClientObj.Host = "mysmtpserver"
         SMTPClientObj.Port = 25
         SMTPClientObj.EnableSsl = False

         Dim e_mail As New MailMessage()
         e_mail.From = New MailAddress("test@test.com")
         e_mail.To.Add("test2@test.com")
         e_mail.Subject = "Email Sending Test"
         e_mail.IsBodyHtml = False
         e_mail.Body = "Test email from VB"

         SMTPClientObj.Send(e_mail)

         Dim x As New Mail.SmtpStatusCode
         Console.WriteLine("SmtpStatusCode: " & CStr(x))

         Console.WriteLine("Mail Sent.")

    Catch ex As Exception
         Dim x As New Mail.SmtpStatusCode
         Console.WriteLine("SmtpStatusCode: " & CStr(x))
         MsgBox(ex.Message)
         MsgBox(ex.ToString)
         MsgBox(ex.InnerException)
    End Try
</code>```

At this point I'd just like to be able to get more details on the error instead of the simple timed out message.  But I've never used the SmtpStatusCode before and am not sure how to use it.

The ex.InnerException prompt is always blank.

Can you give me any pointers on how to get more detailed error info?  Or what I need to do to get this to work on my windows 7 pc?

Thank you

答:
Turns out Digital Guardian was blocking port 25.  McAfee wasn't the problem nor was Group policy.

Thanks to everyone for their assistance.

Body:
When trying to send an email using a Visual Basic Console App I get an error: "The operation timed out".  I'm sending from a Windows 7 pc.  Can this be done?

I've found many posts that say it fails because there is no SMTP client on Windows 7.  However, I downloaded smpt4dev and get the same results when I try to connect to that via "localhost".

But I can telnet to the server from the same pc and get no errors. I can also send  an email using these telnet commands:

telnet SMTP.domain.xyz 25
helo SMTP.domain.xyz
mail from: f@domain.com
rcpt to: t@domain.com
data
subject: test email
.
quit

I have tried this with a few different smtp servers and I get the same results.  I know that my server name, port, username and pw are correct.

Imports System.Net.Mail

Try
         Dim SMTPClientObj As New Net.Mail.SmtpClient
         SMTPClientObj.UseDefaultCredentials = False
         SMTPClientObj.Credentials = New System.Net.NetworkCredential(username, password)
         SMTPClientObj.Host = "mysmtpserver"
         SMTPClientObj.Port = 25
         SMTPClientObj.EnableSsl = False

         Dim e_mail As New MailMessage()
         e_mail.From = New MailAddress("test@test.com")
         e_mail.To.Add("test2@test.com")
         e_mail.Subject = "Email Sending Test"
         e_mail.IsBodyHtml = False
         e_mail.Body = "Test email from VB"

         SMTPClientObj.Send(e_mail)

         Dim x As New Mail.SmtpStatusCode
         Console.WriteLine("SmtpStatusCode: " & CStr(x))

         Console.WriteLine("Mail Sent.")

    Catch ex As Exception
         Dim x As New Mail.SmtpStatusCode
         Console.WriteLine("SmtpStatusCode: " & CStr(x))
         MsgBox(ex.Message)
         MsgBox(ex.ToString)
         MsgBox(ex.InnerException)
    End Try

At this point I'd just like to be able to get more details on the error instead of the simple timed out message.  But I've never used the SmtpStatusCode before and am not sure how to use it.

The ex.InnerException prompt is always blank.

Can you give me any pointers on how to get more detailed error info?  Or what I need to do to get this to work on my windows 7 pc?

Thank you


问:
Make Jackson more friendly for input JSON
Do I have a way to make Jackson less exacting to the input JSON. E.g. JSONObject provides following allowances:

The constructors are more forgiving in the texts they will accept:

An extra , (comma) may appear just before the closing brace.

Strings may be quoted with ' (single quote).

Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.*

Keys can be followed by = or => as well as by :.

Values can be followed by ; (semicolon) as well as by , (comma).

Numbers may have the 0x- (hex) prefix.

The most interesting for me is 3rd point. It allows to following conversion:

```<code>new JSONObject("{A : 1}");
</code>```

... but for jackson I will get an error with the same input json:

```<code>new ObjectMapper().readTree("{ A : 1}"); // throws an exception
</code>```

Exception:

```<code>org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting double-quote to start field name
   at [Source: java.io.StringReader@26d4f1; line: 1, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
at org.codehaus.jackson.impl.JsonParserBase._reportError(JsonParserBase.java:636)
at org.codehaus.jackson.impl.JsonParserBase._reportUnexpectedChar(JsonParserBase.java:569)
at org.codehaus.jackson.impl.ReaderBasedParser._handleUnusualFieldName(ReaderBasedParser.java:342)
at org.codehaus.jackson.impl.ReaderBasedParser._parseFieldName(ReaderBasedParser.java:235)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:125)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:180)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeAny(JsonNodeDeserializer.java:210)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:52)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:13)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1130)
</code>```

答: Check out this related question.  It shows how to configure an ObjectMapper to do what you want, and it also has some good discussion about why you might not want to do that :)

Body:
Do I have a way to make Jackson less exacting to the input JSON. E.g. JSONObject provides following allowances:

The constructors are more forgiving in the texts they will accept:

An extra , (comma) may appear just before the closing brace.

Strings may be quoted with ' (single quote).

Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.*

Keys can be followed by = or => as well as by :.

Values can be followed by ; (semicolon) as well as by , (comma).

Numbers may have the 0x- (hex) prefix.

The most interesting for me is 3rd point. It allows to following conversion:

new JSONObject("{A : 1}");

... but for jackson I will get an error with the same input json:

new ObjectMapper().readTree("{ A : 1}"); // throws an exception

Exception:

org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting double-quote to start field name
   at [Source: java.io.StringReader@26d4f1; line: 1, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
at org.codehaus.jackson.impl.JsonParserBase._reportError(JsonParserBase.java:636)
at org.codehaus.jackson.impl.JsonParserBase._reportUnexpectedChar(JsonParserBase.java:569)
at org.codehaus.jackson.impl.ReaderBasedParser._handleUnusualFieldName(ReaderBasedParser.java:342)
at org.codehaus.jackson.impl.ReaderBasedParser._parseFieldName(ReaderBasedParser.java:235)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:125)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:180)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeAny(JsonNodeDeserializer.java:210)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:52)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:13)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1130)