问:
Bootstrap 4 - the content in the navigation bar moves slightly to the right when the page is shorter than the screen height
Bootstrap 4 - the content in the  navigation bar moves slightly to the right when the page is shorter than the screen height - this doesn't happen with longer pages. I have posted the code from two pages. A home page which is the longer page and a login page which is shorter and twitches.

I am wondering if the solution is to give a minimum height for the content - though I would prefer not to override Boostrap

Longer content with static non twitching navbar

```<code>
<!-- head start -->
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Home page of MVC test </title>
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/main.css">

    <!-- Custom CSS -->
    <link href="/css/blog-home.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>
<!-- head end -->
<body>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark">
   <div class="container">
    <a class="navbar-brand" href="#">MVC Test</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation_bar" aria-controls="navigation_bar" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
     <div class="collapse navbar-collapse" id="navigation_bar">
        <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
            <li  class='nav-item active'><a href='http://mvc.test/home' class='nav-link'  >Home</a></li><li class='nav-item'><a href='http://mvc.test/posts' class='nav-link'  >Posts</a></li><li class='nav-item'><a href='http://mvc.test/about' class='nav-link'  >About</a></li><li class='nav-item'><a href='http://mvc.test/register' class='nav-link'  >Register</a></li><li class='nav-item'><a href='http://mvc.test/login' class='nav-link'  >Login</a></li>        </ul>
        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="search" placeholder="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
    </div>
   </div>
</nav>
<!-- page content start -->
<div class="container">
    <!-- start of row -->
    <div class="row">
        <!-- page content left start -->
        <div class="col-md-8">
            <h1 class="page-header">
                Home            </h1>
            <h2 ><a href = "#" >A first post - I do say</a ></h2 >
<p class="lead">
    by <a href="index.php">Start Bootstrap</a>
</p>
<p><span class="glyphicon glyphicon-time"></span>2020-02-03 11:00:00</p>
<hr>
<img class="img-fluid" src="http://placehold.it/900x300" alt="">
<hr>
<p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
    <hr>
<h2 ><a href = "#" >A second post</a ></h2 >
<p class="lead">
    by <a href="index.php">Start Bootstrap</a>
</p>
<p><span class="glyphicon glyphicon-time"></span>2020-02-03 16:00:00</p>
<hr>
<img class="img-fluid" src="http://placehold.it/900x300" alt="">
<hr>
<p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
    <hr>
        </div>
        <!-- page content left end -->
        <!-- page content right start -->
        <div class="col-md-4 bg-light ">
                <!-- Blog Search Well -->
    <div class="pt-3 ml-1">
        <h4>Blog Search</h4>
        <div class="input-group">
            <input type="text" class="form-control">
            <span class="input-group-btn">
                            <button class="btn btn-default" type="button">
                                <span class="glyphicon glyphicon-search"></span>
                        </button>
                        </span>
        </div>
        <!-- /.input-group -->
    </div>

    <!-- Blog Categories Well -->
    <div class="pt-1 ml-1">
        <h4>Blog Categories</h4>
        <div class="row">
            <div class="col-lg-6">
                <ul class="list-unstyled">
                    <li><a href="#">Category Name</a>
                    </li>
                    <li><a href="#">Category Name</a>
                    </li>
                    <li><a href="#">Category Name</a>
                    </li>
                    <li><a href="#">Category Name</a>
                    </li>
                </ul>
            </div>
            <!-- /.col-lg-6 -->
            <div class="col-lg-6">
                <ul class="list-unstyled">
                    <li><a href="#">Category Name</a>
                    </li>
                    <li><a href="#">Category Name</a>
                    </li>
                    <li><a href="#">Category Name</a>
                    </li>
                    <li><a href="#">Category Name</a>
                    </li>
                </ul>
            </div>
            <!-- /.col-lg-6 -->
        </div>
        <!-- /.row -->
    </div>

    <!-- Side Widget Well -->
    <div class="bg-light">
        <h4>Side Widget Well</h4>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.</p>
    </div>
        </div>
        <!-- page content right end -->
    </div>
    <!-- end of row -->
    <!-- Footer -->
<footer>
    <div class="row">
        <div class="col-md-12">
            <p>Copyright © Your Website 2014 </p>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</footer>

</div>
<!-- end of container -->

<!-- jQuery -->

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>

</body>

</html>
<!-- page content end -->
</code>```

Shorter content with content that moves or twitches to the right

```<code>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>This is a login title </title>
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/main.css">

    <!-- Custom CSS -->
    <link href="/css/blog-home.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark">
   <div class="container">
    <a class="navbar-brand" href="#">MVC Test</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation_bar" aria-controls="navigation_bar" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
     <div class="collapse navbar-collapse" id="navigation_bar">
        <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
            <li class='nav-item'><a href='http://mvc.test/home' class='nav-link'  >Home</a></li><li class='nav-item'><a href='http://mvc.test/posts' class='nav-link'  >Posts</a></li><li class='nav-item'><a href='http://mvc.test/about' class='nav-link'  >About</a></li><li class='nav-item'><a href='http://mvc.test/register' class='nav-link'  >Register</a></li><li  class='nav-item active'><a href='http://mvc.test/login' class='nav-link'  >Login</a></li>        </ul>
        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="search" placeholder="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
    </div>
   </div>
</nav>

    <!-- Page Content -->
    <div class="container">

    <div class="row">
        <div class="col-md-12 ">

                <div class="col-md-6 mx-auto">
                    <div class="card card-light bg-light mt-5">
                                                <h2>Login to your account</h2>
                        <p>Please fill in your credentials</p>
                        <form action="http://mvc.test/login" method="post" >
                            <div class="form-group">
                                <label for="email">Email: <sup>*</sup></label>
                                <input type="email" name="email" class="form-control form-control-lg " value="">
                                <span class="invalid-feedback"></span>
                            </div>
                            <div class="form-group">
                                <label for="password">Password: <sup>*</sup></label>
                                <input type="password" name="password" class="form-control form-control-lg " value="">
                                <span class="invalid-feedback"></span>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <input type="submit" value="Login" class="btn btn-success btn-block">
                                </div>
                                <div class="col">
                                    <a href="http://mvc.test/register" class="btn btn-default btn-block" role="button">Don't have an account? Login</a>
                                </div>
                            </div>
                    </div>
                </div>
        </div>

    </div>
    <div class="row">
        <div class="col-md-12"  >

        </div>

    </div>

    <!-- /.row -->
    <hr>
<!-- Footer -->
<footer>
    <div class="row">
        <div class="col-md-12">
            <p>Copyright © Your Website 2014 </p>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</footer>

</div>
<!-- end of container -->

<!-- jQuery -->

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>

</body>

</html>

</code>```

thanks C

答:
```<code>html {
    overflow-y: scroll;
}
</code>```

This is a solution to my 'twitching' nav bar, see above. I've read that this is not a good CSS and that it doesn't work in opera - however I've seen that the BBC website uses this if that means anything.

Body:
Bootstrap 4 - the content in the  navigation bar moves slightly to the right when the page is shorter than the screen height - this doesn't happen with longer pages. I have posted the code from two pages. A home page which is the longer page and a login page which is shorter and twitches.

I am wondering if the solution is to give a minimum height for the content - though I would prefer not to override Boostrap

Longer content with static non twitching navbar

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Home page of MVC test </title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/main.css">

    <link href="/css/blog-home.css" rel="stylesheet">

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

    </button>

Home

Posts

About

Register

Login

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

                Home

A first post - I do say

    by Start Bootstrap

2020-02-03 11:00:00

"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

Read More

A second post

    by Start Bootstrap

2020-02-03 16:00:00

"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

Read More

Blog Search

            <input type="text" class="form-control">

                            <button class="btn btn-default" type="button">

                        </button>

Blog Categories

Category Name

Category Name

Category Name

Category Name

Category Name

Category Name

Category Name

Category Name

Side Widget Well

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.

Copyright © Your Website 2014

Shorter content with content that moves or twitches to the right

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>This is a login title </title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/main.css">

    <link href="/css/blog-home.css" rel="stylesheet">

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

    </button>

Home

Posts

About

Register

Login

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

Login to your account

Please fill in your credentials

                        <form action="http://mvc.test/login" method="post" >

                                Email: *
                                <input type="email" name="email" class="form-control form-control-lg " value="">

                                Password: *
                                <input type="password" name="password" class="form-control form-control-lg " value="">

                                    <input type="submit" value="Login" class="btn btn-success btn-block">

                                    Don't have an account? Login

Copyright © Your Website 2014

thanks C

Body:
html {
    overflow-y: scroll;
}

This is a solution to my 'twitching' nav bar, see above. I've read that this is not a good CSS and that it doesn't work in opera - however I've seen that the BBC website uses this if that means anything.


来源: stackexchange

问:
CreateProcess error=2 when the path really exists
I'm working with the java ProcessBuilder class to start an instance of nmap on my windows workstation.

The following code produces an exception:

```<code>java.io.IOException: Cannot run program "C:\Program Files (x86)\Nmap\nmap.exe -T4 -A -v --max-scan-delay 0ms --min-rate 1000000 --max-retries 0  -oX -  192.168.1.1 ": CreateProcess error=2, The system cannot find the file specified
</code>```

The value of command is:

```<code>C:\Program Files (x86)\Nmap\nmap.exe -T4 -A -v --max-scan-delay 0ms --min-rate 1000000 --max-retries 0  -oX -  192.168.1.1
</code>```

Running the command is generated right in a command window executes properly.

Any ideas?

```<code>String command = this.getCommand().toString();
        ExecutionResults results = new ExecutionResults();
        ProcessBuilder procBuilder = new ProcessBuilder(new String[]{command.toString()});

        try {
            Process e = procBuilder.start();
            results.setErrors(this.convertStream(e.getErrorStream()));
            results.setOutput(this.convertStream(e.getInputStream()));
</code>```

答:
It might be because of a couple of reasons from my experience

Firewall would be removed certain files necessary for the installer. So would suggest to uninstall and reinstall

Can also be because of spaces in the folder path, would suggest to install in new folder which does not have spaces in the path.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with the java ProcessBuilder class to start an instance of nmap on my windows workstation.

The following code produces an exception:

java.io.IOException: Cannot run program "C:\Program Files (x86)\Nmap\nmap.exe -T4 -A -v --max-scan-delay 0ms --min-rate 1000000 --max-retries 0  -oX -  192.168.1.1 ": CreateProcess error=2, The system cannot find the file specified

The value of command is:

C:\Program Files (x86)\Nmap\nmap.exe -T4 -A -v --max-scan-delay 0ms --min-rate 1000000 --max-retries 0  -oX -  192.168.1.1

Running the command is generated right in a command window executes properly.

Any ideas?

String command = this.getCommand().toString();
        ExecutionResults results = new ExecutionResults();
        ProcessBuilder procBuilder = new ProcessBuilder(new String[]{command.toString()});

        try {
            Process e = procBuilder.start();
            results.setErrors(this.convertStream(e.getErrorStream()));
            results.setOutput(this.convertStream(e.getInputStream()));

ContentLicense: CC BY-SA 4.0


问:
python connecting to Azure database
I am connecting Azure database from python. while doing I have to pass below parameters. What I have to specify in the 'driver' as string.</p>

```<code>enter code here

server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].
[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
</code>```

答:
If you installed Microsoft ODBC Driver 17 on your environment. Then the value for driver should be driver = '{ODBC Driver 17 for SQL Server}'. You can download different ODBC drivers here.

The working python samle:

```<code>    import pyodbc
    server = 'test.database.windows.net'
    database = ''
    username = ''
    password = ''
    driver = '{ODBC Driver 17 for SQL Server}'
    cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server +
                      ';PORT=1433;DATABASE='+database+';Uid=testsql;Pwd={your_password_here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30')
    cursor = cnxn.cursor()
    cursor.execute(
        "select * from Persons")
    row = cursor.fetchone()
    while row:
        print(str(row[0]) + " " + str(row[1]))
        row = cursor.fetchone()
</code>```

Title: python connecting to Azure database

Body:
I am connecting Azure database from python. while doing I have to pass below parameters. What I have to specify in the 'driver' as string.

enter code here

server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].
[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()

Body:
If you installed Microsoft ODBC Driver 17 on your environment. Then the value for driver should be driver = '{ODBC Driver 17 for SQL Server}'. You can download different ODBC drivers here.

The working python samle:

    import pyodbc
    server = 'test.database.windows.net'
    database = ''
    username = ''
    password = ''
    driver = '{ODBC Driver 17 for SQL Server}'
    cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server +
                      ';PORT=1433;DATABASE='+database+';Uid=testsql;Pwd={your_password_here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30')
    cursor = cnxn.cursor()
    cursor.execute(
        "select * from Persons")
    row = cursor.fetchone()
    while row:
        print(str(row[0]) + " " + str(row[1]))
        row = cursor.fetchone()


问:
Cannot locate my php ini file on live server?
I tried different solutions suggested here, but still cannot find the file through cPanel on my live server.

I'm running

```<code>phpinfo();
</code>```

And getting this result:

```<code>Configuration File (php.ini) Path   /opt/alt/php56/etc
</code>```

I cannot find these folders: /opt/alt/php56
But I could find the etc folder, however the file is not there, and I made sure I checked "View hidden files" options

What else could be done?

答:
Try this command and find the path of PHP</p>

```<code>which php
</code>```

Body:
I tried different solutions suggested here, but still cannot find the file through cPanel on my live server.

I'm running

phpinfo();

And getting this result:

Configuration File (php.ini) Path   /opt/alt/php56/etc

I cannot find these folders: /opt/alt/php56
But I could find the etc folder, however the file is not there, and I made sure I checked "View hidden files" options

What else could be done?

Body:
Try this command and find the path of PHP

which php


问:
ValueError: Found input variables with inconsistent numbers of samples: [755, 8]
i have made the model but while creating the confusion matrix i'm getting some error.

the code is as follows:

```<code>from sklearn.utils import shuffle
data,Label = shuffle(A,label,random_state=2)
train_data = [data,Label]
                                                #loading the dataset
X,Y = [train_data[0],train_data[1]]
                                                 #splitting into train and test set
 X_train,X_test,Y_train,Y_test= train_test_split(X,Y,test_size=0.4,random_state
    =4)
                                                    #splitting test into test and validation set

 x_test,x_validation,y_test,y_validation=train_test_split(X_test,Y_test,test_size=0.5,random_state=4)

print (X_train.shape)
</code>```

the output is:

```<code>(2266, 196608)

X_train = X_train.reshape((X_train.shape[0],256,256,3))

x_validation = x_validation.reshape((x_validation.shape[0],256,256,3))

x_test =x_test.reshape((x_test.shape[0],256,256,3))

X_train = X_train.astype('float32')

x_validation = x_validation.astype('float32')

x_test = x_test.astype('float32')

X_train=X_train/255

x_test = x_test / 255

x_validation = x_validation/255

Y_train = np_utils.to_categorical(Y_train,8)

y_validation = np_utils.to_categorical(y_validation,8)

y_test = np_utils.to_categorical(y_test,8)

print(y_test.shape)
(755, 8)
</code>```

then i created the model and found the test accuracy.
Now while creating confusion matrix i'm getting some error

```<code>print(confusion_matrix(y_test,folder))
</code>```

The error is as follows:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-83-6d9d65ab1411> in <module>
----> 1 print(confusion_matrix(y_test,folder))

 ~\Anaconda3\lib\site-packages\sklearn\metrics\classification.py in confusion_matrix(y_true, y_pred, labels, sample_weight)
    251
    252     """
--> 253     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
    254     if y_type not in ("binary", "multiclass"):
    255         raise ValueError("%s is not supported" % y_type)

~\Anaconda3\lib\site-packages\sklearn\metrics\classification.py in _check_targets(y_true, y_pred)
     69     y_pred : array or indicator matrix
     70     """
---> 71     check_consistent_length(y_true, y_pred)
     72     type_true = type_of_target(y_true)
     73     type_pred = type_of_target(y_pred)

~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
    203     if len(uniques) > 1:
    204         raise ValueError("Found input variables with inconsistent numbers of"
--> 205                          " samples: %r" % [int(l) for l in lengths])
    206
    207

ValueError: Found input variables with inconsistent numbers of samples: [755, 8]
</code>```

please help me with this

答:
```<code>steps=(len(test_generator))
</code>```

Solved my problem.

Body:
i have made the model but while creating the confusion matrix i'm getting some error.

the code is as follows:

from sklearn.utils import shuffle
data,Label = shuffle(A,label,random_state=2)
train_data = [data,Label]
                                                #loading the dataset
X,Y = [train_data[0],train_data[1]]
                                                 #splitting into train and test set
 X_train,X_test,Y_train,Y_test= train_test_split(X,Y,test_size=0.4,random_state
    =4)
                                                    #splitting test into test and validation set

 x_test,x_validation,y_test,y_validation=train_test_split(X_test,Y_test,test_size=0.5,random_state=4)

print (X_train.shape)

the output is:

(2266, 196608)

X_train = X_train.reshape((X_train.shape[0],256,256,3))

x_validation = x_validation.reshape((x_validation.shape[0],256,256,3))

x_test =x_test.reshape((x_test.shape[0],256,256,3))

X_train = X_train.astype('float32')

x_validation = x_validation.astype('float32')

x_test = x_test.astype('float32')

X_train=X_train/255

x_test = x_test / 255

x_validation = x_validation/255

Y_train = np_utils.to_categorical(Y_train,8)

y_validation = np_utils.to_categorical(y_validation,8)

y_test = np_utils.to_categorical(y_test,8)

print(y_test.shape)
(755, 8)

then i created the model and found the test accuracy.
Now while creating confusion matrix i'm getting some error

print(confusion_matrix(y_test,folder))

The error is as follows:

ValueError                                Traceback (most recent call last)
<ipython-input-83-6d9d65ab1411> in <module>
----> 1 print(confusion_matrix(y_test,folder))

 ~\Anaconda3\lib\site-packages\sklearn\metrics\classification.py in confusion_matrix(y_true, y_pred, labels, sample_weight)
    251
    252     """
--> 253     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
    254     if y_type not in ("binary", "multiclass"):
    255         raise ValueError("%s is not supported" % y_type)

~\Anaconda3\lib\site-packages\sklearn\metrics\classification.py in _check_targets(y_true, y_pred)
     69     y_pred : array or indicator matrix
     70     """
---> 71     check_consistent_length(y_true, y_pred)
     72     type_true = type_of_target(y_true)
     73     type_pred = type_of_target(y_pred)

~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
    203     if len(uniques) > 1:
    204         raise ValueError("Found input variables with inconsistent numbers of"
--> 205                          " samples: %r" % [int(l) for l in lengths])
    206
    207

ValueError: Found input variables with inconsistent numbers of samples: [755, 8]

please help me with this

Body:
steps=(len(test_generator))

Solved my problem.


问:
Unable to Field identify bean named 'entityManagerFactory' as using Auto-wiring annotation to Repository
Error

APPLICATION FAILED TO START

Description:

```<code>Field ProRepo in com.pvs.products.testservice.ProService required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations: @org.springframework.beans.factory.annotation.Autowired(required=true)
</code>```

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

Code

build.gradle

```<code>plugins {
    id 'org.springframework.boot' version '2.1.12.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
    id 'war'
    id 'java-library'
    id "com.dorongold.task-tree" version "1.4"
}

group = 'com.pvs'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
    jcenter()
}

dependencies {

    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'io.springfox:springfox-swagger2:2.6.1'
    compile 'io.springfox:springfox-swagger-ui:2.6.1'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-web'

    implementation "com.fasterxml.jackson.module:jackson-module-kotlin"
    implementation "org.jetbrains.kotlin:kotlin-reflect"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation "com.okta.spring:okta-spring-boot-starter:1.2.1"
    implementation 'org.apache.cxf:cxf-rt-frontend-jaxrs:3.1.6'

    //Spring  Framework
//  implementation 'org.springframework.security:spring-security-config:4.2.8.RELEASE'
//  implementation 'org.springframework.security:spring-security-core:4.2.8.RELEASE'
//  implementation 'org.springframework.security:spring-security-web:4.2.8.RELEASE'
    implementation 'org.springframework:spring-core:5.1.5.RELEASE'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.amqp:spring-rabbit-test'
//  testImplementation 'org.springframework.security:spring-security-test'

    compile group: 'org.springframework', name: 'spring-core', version: '5.1.5.RELEASE'
    implementation 'org.springframework:spring-jdbc:4.3.20.RELEASE'
    implementation 'org.springframework:spring-orm:4.3.20.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-data-solr'
//  implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

//  implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'

    implementation 'org.springframework.boot:spring-boot-starter-web'
//  compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: '2.1.2.RELEASE'
    compile 'org.mariadb.jdbc:mariadb-java-client:1.5.7'
    compile 'org.springframework.boot:spring-boot-starter-data-redis'

    implementation 'com.h2database:h2'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
//  compile group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.2.1.RELEASE'

    //JDBC
//  implementation 'org.springframework.boot:spring-boot-starter-jdbc'
//  implementation 'org.springframework.session:spring-session-jdbc'
    implementation 'org.springframework:spring-jdbc:4.3.20.RELEASE'

    //Hibernate
    implementation 'org.hibernate:hibernate-core:5.2.12.Final'
    implementation 'org.hibernate:hibernate-ehcache:5.2.12.Final'

    testCompile 'org.hibernate:hibernate-ehcache:5.2.12.Final'
    compile 'org.apache.commons:commons-lang3:3.1'

    implementation 'org.apache.lucene:lucene-core:6.3.0'
    implementation 'org.apache.solr:solr-core:6.3.0'
    implementation 'org.apache.solr:solr-solrj:6.3.0'
    implementation 'org.apache.solr:solr-velocity:6.3.0'

    implementation 'com.zaxxer:HikariCP:3.2.0'

    compile (group: 'org.apache.solr', name: 'solr-velocity', version: '6.3.0') {
        exclude group: 'org.slf4j', module: 'jcl-over-slf4j'
    }

    compile group: 'org.bytedeco', name: 'javacv-platform', version: '1.5.2'

    //XML and JSON
    implementation 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate5'

    //Java org
    implementation 'net.sf.jpf:jpf-boot:1.5'
    implementation 'net.sf.jpf:jpf:1.5'
    implementation 'com.ibm.icu:icu4j:3.8'

    //MySQL
    implementation 'org.hsqldb:hsqldb:2.2.8'
    implementation 'org.hsqldb:sqltool:2.2.8'

    //Hibernate
    //compile 'org.hibernate:hibernate-c3p0:4.1.9.Final'
    compile 'org.hibernate:hibernate-ehcache:4.1.9.Final'

    //Lombok
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    //    newly added
    compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.4.12.Final'
    compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.1'
    compile group: 'org.springframework.data', name: 'spring-data-redis', version: '2.1.12.RELEASE'
//  //commented above librabry with old version
//  compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure'
//  compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.2.4.RELEASE', ext: 'pom'

}
</code>```

application.yml

```<code>spring:
  main:
    allow-bean-definition-overriding: true
  security:
    username: abc
    password: abc

  datasource:
    driverClassName: org.mariadb.jdbc.Driver
     url: jdbc:mariadb:failover://192.168.100.101:3306/tentDB?autoReconnect=true

    username: root
    password: roor

    timeBetweenEvictionRunsMillis: 1000
    testWhileIdle: true
    validationQuery: SELECT 1
  jpa:
    hibernate.ddl-auto: update
    generate-ddl: true
    show-sql: true

logging:
  level:
    org:
      springframework:
        security: DEBUG

endpoints:
  info:
    enabled: true
    id: information
    sensitive: false

management:
  security:
    enabled: true
  endpoints:
    shutdown:
      enabled: true
      enabled-by-default: false
      info:
        enabled: true
    web:
      base-path: /
      exposure:
        include: *

</code>```

Model

```<code>@Entity
@Table(name = "pv_product")
public class product{
//properties are defined inside
}
</code>```

Repository

```<code>@Repository
public interface ProRepo extends JpaRepository<pv_product, BigInteger> {
    @Override
    List<pv_product> findAll();
}
</code>```

Service

```<code>@Component
public class ProService {
    @Autowired
    ProRepo proRepo;
//methods are implemented
}
</code>```

I am using Gradle imports

JPA dependency already imported

```<code>@SpringBootApplication(scanBasePackages={"com.pvs.product", "com.pvs.pvscore"})
@EnableJpaRepositories

</code>```

Update
After removing DataSourceAutoCondifguration it gave this error;

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoSuchFieldError: HANA

</code>```

答:
Please clean your gradle.build file from hibernate dependencies , spring-jdbc and spring-orm.
As spring-boot-starter-jpa has hibernate as transitive dependency.</p>

Body:
Error

APPLICATION FAILED TO START

Description:

Field ProRepo in com.pvs.products.testservice.ProService required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations: @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

Code

build.gradle

plugins {
    id 'org.springframework.boot' version '2.1.12.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
    id 'war'
    id 'java-library'
    id "com.dorongold.task-tree" version "1.4"
}

group = 'com.pvs'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
    jcenter()
}

dependencies {

    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'io.springfox:springfox-swagger2:2.6.1'
    compile 'io.springfox:springfox-swagger-ui:2.6.1'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-web'

    implementation "com.fasterxml.jackson.module:jackson-module-kotlin"
    implementation "org.jetbrains.kotlin:kotlin-reflect"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation "com.okta.spring:okta-spring-boot-starter:1.2.1"
    implementation 'org.apache.cxf:cxf-rt-frontend-jaxrs:3.1.6'

    //Spring  Framework
//  implementation 'org.springframework.security:spring-security-config:4.2.8.RELEASE'
//  implementation 'org.springframework.security:spring-security-core:4.2.8.RELEASE'
//  implementation 'org.springframework.security:spring-security-web:4.2.8.RELEASE'
    implementation 'org.springframework:spring-core:5.1.5.RELEASE'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.amqp:spring-rabbit-test'
//  testImplementation 'org.springframework.security:spring-security-test'

    compile group: 'org.springframework', name: 'spring-core', version: '5.1.5.RELEASE'
    implementation 'org.springframework:spring-jdbc:4.3.20.RELEASE'
    implementation 'org.springframework:spring-orm:4.3.20.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-data-solr'
//  implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

//  implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'

    implementation 'org.springframework.boot:spring-boot-starter-web'
//  compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: '2.1.2.RELEASE'
    compile 'org.mariadb.jdbc:mariadb-java-client:1.5.7'
    compile 'org.springframework.boot:spring-boot-starter-data-redis'

    implementation 'com.h2database:h2'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
//  compile group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.2.1.RELEASE'

    //JDBC
//  implementation 'org.springframework.boot:spring-boot-starter-jdbc'
//  implementation 'org.springframework.session:spring-session-jdbc'
    implementation 'org.springframework:spring-jdbc:4.3.20.RELEASE'

    //Hibernate
    implementation 'org.hibernate:hibernate-core:5.2.12.Final'
    implementation 'org.hibernate:hibernate-ehcache:5.2.12.Final'

    testCompile 'org.hibernate:hibernate-ehcache:5.2.12.Final'
    compile 'org.apache.commons:commons-lang3:3.1'

    implementation 'org.apache.lucene:lucene-core:6.3.0'
    implementation 'org.apache.solr:solr-core:6.3.0'
    implementation 'org.apache.solr:solr-solrj:6.3.0'
    implementation 'org.apache.solr:solr-velocity:6.3.0'

    implementation 'com.zaxxer:HikariCP:3.2.0'

    compile (group: 'org.apache.solr', name: 'solr-velocity', version: '6.3.0') {
        exclude group: 'org.slf4j', module: 'jcl-over-slf4j'
    }

    compile group: 'org.bytedeco', name: 'javacv-platform', version: '1.5.2'

    //XML and JSON
    implementation 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate5'

    //Java org
    implementation 'net.sf.jpf:jpf-boot:1.5'
    implementation 'net.sf.jpf:jpf:1.5'
    implementation 'com.ibm.icu:icu4j:3.8'

    //MySQL
    implementation 'org.hsqldb:hsqldb:2.2.8'
    implementation 'org.hsqldb:sqltool:2.2.8'

    //Hibernate
    //compile 'org.hibernate:hibernate-c3p0:4.1.9.Final'
    compile 'org.hibernate:hibernate-ehcache:4.1.9.Final'

    //Lombok
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    //    newly added
    compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.4.12.Final'
    compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.1'
    compile group: 'org.springframework.data', name: 'spring-data-redis', version: '2.1.12.RELEASE'
//  //commented above librabry with old version
//  compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure'
//  compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.2.4.RELEASE', ext: 'pom'

}

application.yml

spring:
  main:
    allow-bean-definition-overriding: true
  security:
    username: abc
    password: abc

  datasource:
    driverClassName: org.mariadb.jdbc.Driver
     url: jdbc:mariadb:failover://192.168.100.101:3306/tentDB?autoReconnect=true

    username: root
    password: roor

    timeBetweenEvictionRunsMillis: 1000
    testWhileIdle: true
    validationQuery: SELECT 1
  jpa:
    hibernate.ddl-auto: update
    generate-ddl: true
    show-sql: true

logging:
  level:
    org:
      springframework:
        security: DEBUG

endpoints:
  info:
    enabled: true
    id: information
    sensitive: false

management:
  security:
    enabled: true
  endpoints:
    shutdown:
      enabled: true
      enabled-by-default: false
      info:
        enabled: true
    web:
      base-path: /
      exposure:
        include: *

Model

@Entity
@Table(name = "pv_product")
public class product{
//properties are defined inside
}

Repository

@Repository
public interface ProRepo extends JpaRepository<pv_product, BigInteger> {
    @Override
    List<pv_product> findAll();
}

Service

@Component
public class ProService {
    @Autowired
    ProRepo proRepo;
//methods are implemented
}

I am using Gradle imports

JPA dependency already imported

@SpringBootApplication(scanBasePackages={"com.pvs.product", "com.pvs.pvscore"})
@EnableJpaRepositories

Update
After removing DataSourceAutoCondifguration it gave this error;

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoSuchFieldError: HANA


问:
element.parentNode gives different result from page and chrome extension context for web components
I have following problem:
I'm taking the same element from context of web page and chrome extension I'm developing.
When I'm calling

```<code>element.parentNode
</code>```

From context of page ("top" in devTools) I'm reciving #document-fragment. When I do exactly saem thing from extension context (content script of extension), I'm getting reference to some web component "force-record-layout-item" (this element is host for fetched before document-fragment).
On picture blue - element, yellow - parent from chrome extension context.

What is the reason of situation like this? How can I fetch same parent for both contexts?
(I occured also similar situation where in context of chrome extension parentNode was inside of shadow root relatively to parentNode of the same element from page context and can not figure out why)

答:
Both should be using the same DOM, I think you are trying to access the elements at different times (before or after the fetch completes) is what makes the difference.
Try to run the code in your content script with a few seconds of delay to test this. IF that does it then you could try using a Mutation Observer to execute your code when that element changes. You could also play around with the run_at attribute of your content script in the manifest.</p>

Body:
I have following problem:
I'm taking the same element from context of web page and chrome extension I'm developing.
When I'm calling

element.parentNode

From context of page ("top" in devTools) I'm reciving #document-fragment. When I do exactly saem thing from extension context (content script of extension), I'm getting reference to some web component "force-record-layout-item" (this element is host for fetched before document-fragment).
On picture blue - element, yellow - parent from chrome extension context.

What is the reason of situation like this? How can I fetch same parent for both contexts?
(I occured also similar situation where in context of chrome extension parentNode was inside of shadow root relatively to parentNode of the same element from page context and can not figure out why)


问:
Ruby, forming API request without implicitly stating each parameter
I'm trying to make a request to a web service (fwix), and in my rails app I've created the following initializer, which works... sorta, I have two problems however:

For some reason the values of the parameters need to have +'s as the spaces, is this a standard thing that I can accomplish with ruby? Additionally is this a standard way to form a url? I thought that spaces were %20.

In my code how can I take any of the options sent in and just use them instead of having to state each one like query_items << "api_key=#{options[:api_key]}" if options[:api_key]

The following is my code, the trouble area I'm having are the lines starting with query_items for each parameter in the last method, any ideas would be awesome!

```<code>require 'httparty'
module Fwix
  class API
    include HTTParty

    class JSONParser < HTTParty::Parser
      def json
        JSON.parse(body)
      end
    end

    parser JSONParser
    base_uri "http://geoapi.fwix.com"

    def self.query(options = {})
      begin
        query_url = query_url(options)
        puts "querying: #{base_uri}#{query_url}"
        response = get( query_url )
      rescue
        raise "Connection to Fwix API failed" if response.nil?
      end
    end

    def self.query_url(input_options = {})
      @defaults ||= {
        :api_key => "my_api_key",
      }

      options = @defaults.merge(input_options)
      query_url = "/content.json?"
      query_items = []
      query_items << "api_key=#{options[:api_key]}" if options[:api_key]
      query_items << "province=#{options[:province]}" if options[:province]
      query_items << "city=#{options[:city]}" if options[:city]
      query_items << "address=#{options[:address]}" if options[:address]

      query_url += query_items.join('&')
      query_url
    end
  end
end
</code>```

答:
For 1)
You API provider is expecting '+' because the API is expecting in a CGI formatted string instead of URL formatted string.

```<code>require 'cgi'
my_query = "hel lo"
CGI.escape(my_query)
</code>```

this should give you

```<code>"hel+lo"
</code>```

as you expect

for Question 2) I would do something like

```<code>query_items = options.keys.collect { |key| "#{key.to_s}=#{options[key]}" }
</code>```

Body:
I'm trying to make a request to a web service (fwix), and in my rails app I've created the following initializer, which works... sorta, I have two problems however:

For some reason the values of the parameters need to have +'s as the spaces, is this a standard thing that I can accomplish with ruby? Additionally is this a standard way to form a url? I thought that spaces were %20.

In my code how can I take any of the options sent in and just use them instead of having to state each one like query_items << "api_key=#{options[:api_key]}" if options[:api_key]

The following is my code, the trouble area I'm having are the lines starting with query_items for each parameter in the last method, any ideas would be awesome!

require 'httparty'
module Fwix
  class API
    include HTTParty

    class JSONParser < HTTParty::Parser
      def json
        JSON.parse(body)
      end
    end

    parser JSONParser
    base_uri "http://geoapi.fwix.com"

    def self.query(options = {})
      begin
        query_url = query_url(options)
        puts "querying: #{base_uri}#{query_url}"
        response = get( query_url )
      rescue
        raise "Connection to Fwix API failed" if response.nil?
      end
    end

    def self.query_url(input_options = {})
      @defaults ||= {
        :api_key => "my_api_key",
      }

      options = @defaults.merge(input_options)
      query_url = "/content.json?"
      query_items = []
      query_items << "api_key=#{options[:api_key]}" if options[:api_key]
      query_items << "province=#{options[:province]}" if options[:province]
      query_items << "city=#{options[:city]}" if options[:city]
      query_items << "address=#{options[:address]}" if options[:address]

      query_url += query_items.join('&')
      query_url
    end
  end
end

Body:
For 1)
You API provider is expecting '+' because the API is expecting in a CGI formatted string instead of URL formatted string.

require 'cgi'
my_query = "hel lo"
CGI.escape(my_query)

this should give you

"hel+lo"

as you expect

for Question 2) I would do something like

query_items = options.keys.collect { |key| "#{key.to_s}=#{options[key]}" }


问:
Name Of Generic "Pipe" Concept for Physical Communication?
I currently have an idea rolling around in my head about how to abstract away (to some degree) common data transfer mechanisms of embedded systems such as CAN, UART, SPI, I2C, Ethernet, etc. Ideally I would want to have something like the concept of a Pipe, but that the interface doesn't really care about what physical medium/protocol the data is flowing over. If I say "transfer this data through the pipe", it just works. Obviously there would have to be some protocol specific details in the construction of this pipe object but outside of that it shouldn't matter.

Is there an industry accepted name for what I'm trying to do?

Is this concept even a good idea? I feel like it will be useful for my purposes but I don't know if it's pointless in the grand scheme of the embedded engineering world.

答:
Is there an industry accepted name for what I'm trying to do?

Hardware Abstraction Layer (HAL) comes closest. Keep in mind that the mentioned buses are hardware standards that don't define higher-layer protocols. At higher levels, this might be called "sockets", though that typically refers to IP specifically.

Is this concept even a good idea?

Probably not, unless you have specific requirements.

For example, it would be a good idea if you wish to replace an old RS-485 network with CAN but maintain the old hardware. It would then make sense to have as much of the software compatible as possible in that specific project.

Otherwise, from a general point of view, each of these buses are picked to suit quite different requirements. CAN when you need rugged & reliable, UART when you need backwards-compatibility, SPI when you need fast, synchronous, close-to-metal on-board communication, Ethernet when you need fast communication over long distances etc etc. The hardware requirements of one bus might exclude another.

For example, if I want my MCU to communicate with a "dumb" LCD, only SPI makes sense. I might have to toggle additional I/O pins together with the SPI signals. I might want to use DMA. Etc. In that context, there is no benefit for me if I have to use an abstract communication API which is portable to CAN, Ethernet etc. That's just bloat - this code will never run on any of those buses!

It makes far more sense to develop a HAL per bus type, so that you have one SPI HAL which is portable between microcontrollers. That's common and actually useful.


问:
React - how to set inline CSS for each element of map function?
I have an application in React where I'm trying to read in data from a JSON file. The JSON file is in the following format:

```<code>[
    {
        "name": "Max",
        "age": "21",
    },

    {
        "name": "Sam",
        "age": "18",
    }

    ........
]
</code>```

I have successfully read in the right data and displayed it on my screen, like this:

```<code>function foo(){
    const styling = css`
        font-size: 30px;
    `;

    return(
        <div>
            {people.map((person, i) => <Format key={i} {...person} css={styling}/>)}
        </div>
    );
}
</code>```

Although all the information correctly displays on the screen, the styling is not getting applied to each person. How could I change this?

EDIT

Format component:

```<code>function Format({name, age}){
   return (
      <div>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}
</code>```

答:
```<code>function Format({name, age, css}){
   return (
      <div css={css}>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}
</code>```

you passed styled to your component but you didnt use them in your child component

and plus using idx as key is not the best practice. following article explains why.
https://reactjs.org/docs/lists-and-keys.html

if name is unique you can pass each items name to mapped children.

Body:
I have an application in React where I'm trying to read in data from a JSON file. The JSON file is in the following format:

[
    {
        "name": "Max",
        "age": "21",
    },

    {
        "name": "Sam",
        "age": "18",
    }

    ........
]

I have successfully read in the right data and displayed it on my screen, like this:

function foo(){
    const styling = css`
        font-size: 30px;
    `;

    return(

            {people.map((person, i) => <Format key={i} {...person} css={styling}/>)}

    );
}

Although all the information correctly displays on the screen, the styling is not getting applied to each person. How could I change this?

EDIT

Format component:

function Format({name, age}){
   return (

{name}

{age}

   );
}

Body:
function Format({name, age, css}){
   return (
      <div css={css}>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}

you passed styled to your component but you didnt use them in your child component

and plus using idx as key is not the best practice. following article explains why.
https://reactjs.org/docs/lists-and-keys.html

if name is unique you can pass each items name to mapped children.


问:
Extract rows with duplicates entries in one column satisfying a given condition in another column
I have a sample dataframe with duplicate entries in the first column given below:

```<code>df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0
</code>```

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

```<code>aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2
</code>```

but I have not been able to solve the problem.

Desired Output: The output should look like this:

```<code>df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0
</code>```

Thanks!

答:
Here is a base R solution using

```<code>dfout <- do.call(rbind,
                 c(make.row.names = F,
                   Map(function(v) v[head(which(v$Type==1),1):nrow(v),],split(df,df$ID))))
</code>```

such that

```<code>> dfout
   ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0
</code>```

Body:
I have a sample dataframe with duplicate entries in the first column given below:

df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2

but I have not been able to solve the problem.

Desired Output: The output should look like this:

df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0

Thanks!

Body:
Here is a base R solution using

dfout <- do.call(rbind,
                 c(make.row.names = F,
                   Map(function(v) v[head(which(v$Type==1),1):nrow(v),],split(df,df$ID))))

such that

> dfout
   ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0


问:
Jmeter cyclic running tests
I want to run cyclical tests in jmeter. I want them to run every day and than run for 10 minutes (every day for 10 minutes). How to do it?</p>

答:
For running test for 10 minutes there are following options:

In the Thread Group tick "Specify Thead lifetime" and put 600 into "Duration" field:

Or use Runtime Controller which allows setting how long its children are allowed to run

With regards to running the test every day, you can go for:

Windows Task Scheduler

Linux/Unix crontab

MacOS launchd

or you can put the JMeter job under the orchestration of a Continuous Integration server, any of them can run specified job on the schedule or basing on various different triggers, tracks job status (successful or failed), some of them provide performance trends

Title: Jmeter cyclic running tests


问:
R variable inside a string
I would like to know if it is possible to pass a variable inside a string with R like in php. For example:</p>

```<code>args <- commandArgs(TRUE)
variable1 <- args[1]

variable2 <- "I am argument:",variable1,"text continue"
</code>```

答:
There are variety of ways to get the output :

```<code>variable1 <- args[1]
</code>```

1) Using sprintf as mentioned by @Roland

```<code>sprintf("I am argument: %s text continue",variable1)
</code>```

2) Using glue

```<code>glue::glue("I am argument: {variable1} text continue")
</code>```

3) a) str_c

```<code>stringr::str_c("I am argument:",variable1,"text continue")
</code>```

b) stri_c

```<code>stringi::stri_c("I am argument:",variable1,"text continue")
</code>```

Title: R variable inside a string

Body:
I would like to know if it is possible to pass a variable inside a string with R like in php. For example:

args <- commandArgs(TRUE)
variable1 <- args[1]

variable2 <- "I am argument:",variable1,"text continue"

Body:
There are variety of ways to get the output :

variable1 <- args[1]

1) Using sprintf as mentioned by @Roland

sprintf("I am argument: %s text continue",variable1)

2) Using glue

glue::glue("I am argument: {variable1} text continue")

3) a) str_c

stringr::str_c("I am argument:",variable1,"text continue")

b) stri_c

stringi::stri_c("I am argument:",variable1,"text continue")


问:
Safely convert (vector of shared_ptr to objects) to (vector of shared_ptr to constant objects)
```<code>class A {};

typedef shared_ptr<const A*> AConstPtr;
typedef shared_ptr<A*> APtr;

vector<APtr> ptr;

const vector<AConstPtr>* foo()
{
    return &ptr;
}
</code>```

This code does not compile, because "there is no implicit conversion from vector<Aptr>* to const vector<AConstPtr> * "
Is there anyway to make this work, without creating a new vector, and without using an unsafe cast?

The reason why I need this is because I have a class that stores a list internally as vector<APtr>, but needs to expose a completely const version of it through its interface.

答:
There's no way to do such a conversion since different shared_ptrs aren't related types.

First, are you really sure that you need to expose the implementation detail that there's an internal vector of shared pointers? That's really going to tie you to that implementation and it won't be subject to change without breaking API.

What about using @Cubbi's suggestion and having your interface be interators with begin and end methods instead? Then you can easily represent a container to the outside clients without tying yourself to vector.

Body:
class A {};

typedef shared_ptr<const A*> AConstPtr;
typedef shared_ptr APtr;

vector<APtr> ptr;

const vector<AConstPtr>* foo()
{
    return &ptr;
}

This code does not compile, because "there is no implicit conversion from vector<Aptr>* to const vector<AConstPtr> * "
Is there anyway to make this work, without creating a new vector, and without using an unsafe cast?

The reason why I need this is because I have a class that stores a list internally as vector<APtr>, but needs to expose a completely const version of it through its interface.


问:
Using If else in SQL Select statement
I have a select statement which will return 2 columns.

```<code>ID | IDParent
</code>```

Then in my program I have to test if IDParent is < 1 then use ID ELSE use IDParent

Is there a way to use an If Else like condition in SQL to return only single value?

答:
Here are two ways "IF" Or "CASE".

```<code>SELECT IF(COLUMN_NAME = "VALUE", "VALUE_1", "VALUE_2") AS COLUMN_NAME
FROM TABLE_NAME;
</code>```

OR

```<code>SELECT (CASE WHEN COLUMN_NAME = "VALUE" THEN 'VALUE_1' ELSE 'VALUE_2' END) AS COLUMN_NAME
FROM TABLE_NAME;
</code>```

Title: Using If else in SQL Select statement

Body:
I have a select statement which will return 2 columns.

ID | IDParent

Then in my program I have to test if IDParent is < 1 then use ID ELSE use IDParent

Is there a way to use an If Else like condition in SQL to return only single value?

Body:
Here are two ways "IF" Or "CASE".

SELECT IF(COLUMN_NAME = "VALUE", "VALUE_1", "VALUE_2") AS COLUMN_NAME
FROM TABLE_NAME;

OR

SELECT (CASE WHEN COLUMN_NAME = "VALUE" THEN 'VALUE_1' ELSE 'VALUE_2' END) AS COLUMN_NAME
FROM TABLE_NAME;


问:
how to format 12 hours time in Raspi lcd with I2C

I would like to change my lcd 24 hours time format to 12 hours

```<code>import lcddriver
import time
import datetime

display = lcddriver.lcd()

try:
    print("Writing to display")
    display.lcd_display_string("Time", 1)
    while True:
        display.lcd_display_string(str(datetime.datetime.now().time()), 2)

except KeyboardInterrupt:
    print("Cleaning up!")
    display.lcd_clear()
</code>```

答:
You could use datetime module in python like this:

```<code>import lcddriver
import time
import datetime

display = lcddriver.lcd()

try:
    print("Writing to display")
    display.lcd_display_string("Time", 1)
    while True:
        datestr = datetime.datetime.now().strftime("%I:%M:%S %p")
        display.lcd_display_string(datestr, 2)

except KeyboardInterrupt:
    print("Cleaning up!")
    display.lcd_clear()
</code>```

For example, if current time is 15:40:50 then datetime.datetime.now().strftime("%I:%M:%S %p") outputs 03:40:50 PM

Hope it helps you!

Body:
I would like to change my lcd 24 hours time format to 12 hours

import lcddriver
import time
import datetime

display = lcddriver.lcd()

try:
    print("Writing to display")
    display.lcd_display_string("Time", 1)
    while True:
        display.lcd_display_string(str(datetime.datetime.now().time()), 2)

except KeyboardInterrupt:
    print("Cleaning up!")
    display.lcd_clear()

Body:
You could use datetime module in python like this:

import lcddriver
import time
import datetime

display = lcddriver.lcd()

try:
    print("Writing to display")
    display.lcd_display_string("Time", 1)
    while True:
        datestr = datetime.datetime.now().strftime("%I:%M:%S %p")
        display.lcd_display_string(datestr, 2)

except KeyboardInterrupt:
    print("Cleaning up!")
    display.lcd_clear()

For example, if current time is 15:40:50 then datetime.datetime.now().strftime("%I:%M:%S %p") outputs 03:40:50 PM

Hope it helps you!


问:
How To Create multiple database on web hosting server using Asp.net core EF Core
Hi am trying to develop the web version of my desktop application using C# asp.net core, but am not sure of how to handle the databases, Here is what i want to achieve, my desktop application is a Point of sales system developed using VB whereby the application user are able to manage multiple stores and every store has it own database, upon the creation of the store the database script is executed which now create the database for the New store. Below is my sample code to create the database.

```<code> 'Get DB NAme
        Dim DbNumber As Integer
        ConnectTools()
        cmd.CommandText = "select MAX(StoreCount) as cntt from tblStores"
        rd = cmd.ExecuteReader
        rd.Read()
        If IsDBNull(rd.Item("cntt")) Then
            DbNumber = "1"
        Else
            DbNumber = rd.Item("cntt") + 1
        End If
        rd.Close()
        DatabaseName = "AutemStore" & DbNumber

        cmd.Connection = conn
        'conn.Open()
        conn.ChangeDatabase("Master")
        If conn.State = ConnectionState.Open Then conn.Close()
        conn.Open()
        cmd.CommandText = "Create Database " & DatabaseName
        cmd.ExecuteNonQuery()
        'Save DB Name
        My.Settings.DatabaseName = DatabaseName
        My.Settings.Save()
        'Run DB Script

        conn.ChangeDatabase(My.Settings.DatabaseName)
        cmd.CommandText = ReadFile(Application.StartupPath & "\dstore.sql")
        cmd.CommandType = CommandType.Text
        cmd.ExecuteNonQuery()
</code>```

I believe there is a way this task i just explained can be done using Asp.net core but I don't yet have a clue on how to get it done, please is there any suggestion on how to do this or alternative way to get it done. Thanks in advance.

答:
Since you're trying to use EF(or maybe EFCore), I assume you've set up the data Models and injected the DbContext as _context. (If you have not, you could follow the official docs to get started).

After that, you could rewrite you VB.NET + ADO.NET code using EFCore like this:

The first query of select MAX(StoreCount) as cntt from tblStores can be done by

```<code>var cntt = _context.Stores.Max(t => t.StoreCound);
</code>```

The 2nd command that creates database can be rewritten as:

```<code>var sql= "Create Database @dbname";
var dbname = new SqlParameter("@dbname", "The_DB_Name");
_context.Database.ExecuteSqlCommand(sql, dbname);
</code>```

Body:
Hi am trying to develop the web version of my desktop application using C# asp.net core, but am not sure of how to handle the databases, Here is what i want to achieve, my desktop application is a Point of sales system developed using VB whereby the application user are able to manage multiple stores and every store has it own database, upon the creation of the store the database script is executed which now create the database for the New store. Below is my sample code to create the database.

 'Get DB NAme
        Dim DbNumber As Integer
        ConnectTools()
        cmd.CommandText = "select MAX(StoreCount) as cntt from tblStores"
        rd = cmd.ExecuteReader
        rd.Read()
        If IsDBNull(rd.Item("cntt")) Then
            DbNumber = "1"
        Else
            DbNumber = rd.Item("cntt") + 1
        End If
        rd.Close()
        DatabaseName = "AutemStore" & DbNumber

        cmd.Connection = conn
        'conn.Open()
        conn.ChangeDatabase("Master")
        If conn.State = ConnectionState.Open Then conn.Close()
        conn.Open()
        cmd.CommandText = "Create Database " & DatabaseName
        cmd.ExecuteNonQuery()
        'Save DB Name
        My.Settings.DatabaseName = DatabaseName
        My.Settings.Save()
        'Run DB Script

        conn.ChangeDatabase(My.Settings.DatabaseName)
        cmd.CommandText = ReadFile(Application.StartupPath & "\dstore.sql")
        cmd.CommandType = CommandType.Text
        cmd.ExecuteNonQuery()

I believe there is a way this task i just explained can be done using Asp.net core but I don't yet have a clue on how to get it done, please is there any suggestion on how to do this or alternative way to get it done. Thanks in advance.

Body:
Since you're trying to use EF(or maybe EFCore), I assume you've set up the data Models and injected the DbContext as _context. (If you have not, you could follow the official docs to get started).

After that, you could rewrite you VB.NET + ADO.NET code using EFCore like this:

The first query of select MAX(StoreCount) as cntt from tblStores can be done by

var cntt = _context.Stores.Max(t => t.StoreCound);

The 2nd command that creates database can be rewritten as:

var sql= "Create Database @dbname";
var dbname = new SqlParameter("@dbname", "The_DB_Name");
_context.Database.ExecuteSqlCommand(sql, dbname);


问:
How to Call Method in Fragment From Parent Activity?
**Here is the Fragment I want call getAvailableWebsites(); from parent Activity **    </p>

```<code>public class Earn extends Fragment {

public Earn() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_earn, container, false);
}
public void getAvailableWebsites(){
    Toast.makeText(getActivity(),"Called From Activity",Toast.LENGTH_LONG).show();
}
</code>```

<p>}</p>

答:
you can try below option in your Activity:

```<code>Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (fragment != null && fragment instanceof YourFragment) {
    ((YourFragment) fragment).yourFragmentMethod();
}
</code>```

Hope this helps you..

Body:
**Here is the Fragment I want call getAvailableWebsites(); from parent Activity **

public class Earn extends Fragment {

public Earn() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_earn, container, false);
}
public void getAvailableWebsites(){
    Toast.makeText(getActivity(),"Called From Activity",Toast.LENGTH_LONG).show();
}

}

Body:
you can try below option in your Activity:

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (fragment != null && fragment instanceof YourFragment) {
    ((YourFragment) fragment).yourFragmentMethod();
}

Hope this helps you..


问:
Mercurial: allow merge from a release branch to the default one, but not vice versa
I'm using default branch for ongoing development, and now going to create a new named branch to mark a release. All further development will be on the default branch, all production bugfixes will be done on the new one (with subsequent merge to default), like this:

```<code>#>hg branches
   aristotle   42:dbd...
   default     41:da5...
#>hg branch
   default
#>echo "Feature #1 for the next release" >> feature1.txt
#>hg add
#>hg commit -m "Implement feature #1 for the next release"

...... eek, need to make an urgent fix on Production .....

#>hg update aristotle
#>echo "Fixed urgent bug #123 on Production" >> fix123.txt
#>hg add
#>hg commit -m "Fixed bug #123 on Production"
   created new head
#>hg update default
#>hg merge aristotle
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   (branch merge, dont forget to commit)
#>hg commit -m "Merge in the fix for bug #123"
#>hg push
</code>```

The above seems the way to go, however it seems easy to mess things up and merge the other way around (from default to aristotle which means all the new features will appear in the production branch).

Maybe my fears are groundless because one will notice the mess before pushing the commit to the central repo, but I'd like to see if it's possible to make the approach more foolproof.

So I started looking into hooks:

```<code>[hooks]
pretxnchangegroup.branch = hg heads --template "{branches} " | find "aristotle" && exit 1 || exit 0
</code>```

..but then realized it's not what I need, because this will not allow me to push aristotle changes at all.

So I'm not sure what to do. Ideally, I want developers to see the "wrong way merge" message when they attempt to commit a merge from default to aristotle locally (obviously, there should be a double-check on the central repo), while merging from production branch to the default one should be possible.

Thanks!

答:
This is pretty much an exact duplicate of a question from a few days ago Ensuring a merge between branches happens in one direction

but I didn't like my answer to that one, so how about this one:

Keep separate clones for past releases.  When, in your example above, you decide you need to do an emergency fix on aristotle do this instead:

```<code>cd ..
hg clone -r aristotle myrepo myrepo-aristotle
</code>```

then you have a clone with only aristotle in it and you can't accidentally merge it to default in that clone.

That said, it's still not a great answer.  The only real consolation is that if you merge in a direction you don't like you can always re-clone the two heads and merge in the other direction.

Body:
I'm using default branch for ongoing development, and now going to create a new named branch to mark a release. All further development will be on the default branch, all production bugfixes will be done on the new one (with subsequent merge to default), like this:

#>hg branches
   aristotle   42:dbd...
   default     41:da5...
#>hg branch
   default
#>echo "Feature #1 for the next release" >> feature1.txt
#>hg add
#>hg commit -m "Implement feature #1 for the next release"

...... eek, need to make an urgent fix on Production .....

#>hg update aristotle
#>echo "Fixed urgent bug #123 on Production" >> fix123.txt
#>hg add
#>hg commit -m "Fixed bug #123 on Production"
   created new head
#>hg update default
#>hg merge aristotle
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   (branch merge, dont forget to commit)
#>hg commit -m "Merge in the fix for bug #123"
#>hg push

The above seems the way to go, however it seems easy to mess things up and merge the other way around (from default to aristotle which means all the new features will appear in the production branch).

Maybe my fears are groundless because one will notice the mess before pushing the commit to the central repo, but I'd like to see if it's possible to make the approach more foolproof.

So I started looking into hooks:

[hooks]
pretxnchangegroup.branch = hg heads --template "{branches} " | find "aristotle" && exit 1 || exit 0

..but then realized it's not what I need, because this will not allow me to push aristotle changes at all.

So I'm not sure what to do. Ideally, I want developers to see the "wrong way merge" message when they attempt to commit a merge from default to aristotle locally (obviously, there should be a double-check on the central repo), while merging from production branch to the default one should be possible.

Thanks!

Body:
This is pretty much an exact duplicate of a question from a few days ago Ensuring a merge between branches happens in one direction

but I didn't like my answer to that one, so how about this one:

Keep separate clones for past releases.  When, in your example above, you decide you need to do an emergency fix on aristotle do this instead:

cd ..
hg clone -r aristotle myrepo myrepo-aristotle

then you have a clone with only aristotle in it and you can't accidentally merge it to default in that clone.

That said, it's still not a great answer.  The only real consolation is that if you merge in a direction you don't like you can always re-clone the two heads and merge in the other direction.


问:
How to parse a custom key/value pair string into a JSON object in Azure Data Explorer?
I needed to parse a string of properties to a JSON object. Here is the input format:

"var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"

And the desired output:

{
   "var1": "val1",
   "var2": "val2",
   "var3": "val3",
   "var4": "val4"
}
```

I have the answer, see below...

答:
Thanks Ziad Hammoud for providing this cool workaround!</p>
```<code>print str = "var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"
| extend str = replace("\\] & ", "&", replace("=\\[", "=", str))
| project Properties = parse_urlquery(str)['Query Parameters']
| where Properties.var2== "val2"
</code>```

Body:
I needed to parse a string of properties to a JSON object. Here is the input format:

"var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"

And the desired output:

{
   "var1": "val1",
   "var2": "val2",
   "var3": "val3",
   "var4": "val4"
}

I have the answer, see below...

Body:
Thanks Ziad Hammoud for providing this cool workaround!

print str = "var1=[val1] & var2=[val2] & var3=[val3] & var4=[val4]"
| extend str = replace("\\] & ", "&", replace("=\\[", "=", str))
| project Properties = parse_urlquery(str)['Query Parameters']
| where Properties.var2== "val2"


问:
While Loop Function after a button is pressed and stop looping when another button is pressed C#
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

```<code>private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }
</code>```

While for my button2 code:

```<code>private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}
</code>```

Thank you!

答:
All the operations you put into the EmoStart_Click_1 is running synchronously, except:

```<code>FaceEmotion.MakeAnalysisRequest(imageFilePath)
</code>```

thus the interface (UI) is frozen.

It is not enough to change the signature of the method to async as you did. You must tell the compiler, which other parts should be awaited. You want your whole while function async!

```<code>private async void EmoStart_Click_1(object sender, EventArgs e)
{
    EmoStart.Enabled = false;           //I assume EmoStart is the name of your button
    await Task.Factory.StartNew(Loop);
    EmoStart.Enabled = true;
}

private void Loop()                     //since this method doesn't have async in its signature "var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);" won't compile, so you should change to the synchronous equivalent "var Emo = FaceEmotion.MakeAnalysisRequest(imageFilePath).Result;" --> note that it won't block due to "Task.Factory.StartNew".
{
    string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
    while (...)
    {
        // do your stuff
    }
</code>```

Then you can decide how you want to cancel the while loop.

Option 1.: you could use a global, bool variable:

```<code>private bool emotionsShouldBeProcessed;
</code>```

and you set it true in EmoStart_Click_1 and false like this:

```<code>private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    VoiceStart.Enabled = false;
    emotionsShouldBeProcessed = false;
    // start and await voice stuff
    VoiceStart.Enabled = true;
}
</code>```

Option 2.: you could use a CancellationToken to track if cancel is necessary.

```<code>CancellationTokenSource cSource;

private async void EmoStart_Click_1(object sender, EventArgs e)
{
    EmoStart.Enabled = false;
    cSource = new CancellationTokenSource();
    await Task.Factory.StartNew(() => Loop(cSource.Token));
    EmoStart.Enabled = true;
}
private void Loop(CancellationToken cToken)
{
    string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
    while (true)
    {
        if (cToken.IsCancellationRequested)
            break;
        // otherwise do your stuff
    }
    // some clean up here if necessary
}
private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    VoiceStart.Enabled = false;
    cSource.Cancel();
    VoiceStart.Enabled = true;
}
</code>```

So far so good! But your code will crash

It will crash whenever you want to set EmoBox.Text as this can happen only on the UI thread. To avoid this, you need to ask the UI thread to interrupt until Textbox/Label/etc operations are going on, like this:

```<code>this.Invoke((MethodInvoket)delegate
{
    EmoBox.Text = "...";
});
</code>```

Edit:

I would also check the Emo array whether it is empty since face- and emotion recognitions not always succeeds! Thus, Emo[0] can result in "Index was out of range" exception. Following code makes sure it isn't empty:

```<code>var Emo = ...;
if (Emo.Length > 0)
{
    if (...)
        // use Emo[0]
    else if (...)
        // use Emo[0] differently
}
</code>```

Let me know if there is anything unclear.

Body:
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }

While for my button2 code:

private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}

Thank you!

Body:
All the operations you put into the EmoStart_Click_1 is running synchronously, except:

FaceEmotion.MakeAnalysisRequest(imageFilePath)

thus the interface (UI) is frozen.

It is not enough to change the signature of the method to async as you did. You must tell the compiler, which other parts should be awaited. You want your whole while function async!

private async void EmoStart_Click_1(object sender, EventArgs e)
{
    EmoStart.Enabled = false;           //I assume EmoStart is the name of your button
    await Task.Factory.StartNew(Loop);
    EmoStart.Enabled = true;
}

private void Loop()                     //since this method doesn't have async in its signature "var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);" won't compile, so you should change to the synchronous equivalent "var Emo = FaceEmotion.MakeAnalysisRequest(imageFilePath).Result;" --> note that it won't block due to "Task.Factory.StartNew".
{
    string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
    while (...)
    {
        // do your stuff
    }

Then you can decide how you want to cancel the while loop.

Option 1.: you could use a global, bool variable:

private bool emotionsShouldBeProcessed;

and you set it true in EmoStart_Click_1 and false like this:

private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    VoiceStart.Enabled = false;
    emotionsShouldBeProcessed = false;
    // start and await voice stuff
    VoiceStart.Enabled = true;
}

Option 2.: you could use a CancellationToken to track if cancel is necessary.

CancellationTokenSource cSource;

private async void EmoStart_Click_1(object sender, EventArgs e)
{
    EmoStart.Enabled = false;
    cSource = new CancellationTokenSource();
    await Task.Factory.StartNew(() => Loop(cSource.Token));
    EmoStart.Enabled = true;
}
private void Loop(CancellationToken cToken)
{
    string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
    while (true)
    {
        if (cToken.IsCancellationRequested)
            break;
        // otherwise do your stuff
    }
    // some clean up here if necessary
}
private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    VoiceStart.Enabled = false;
    cSource.Cancel();
    VoiceStart.Enabled = true;
}

So far so good! But your code will crash

It will crash whenever you want to set EmoBox.Text as this can happen only on the UI thread. To avoid this, you need to ask the UI thread to interrupt until Textbox/Label/etc operations are going on, like this:

this.Invoke((MethodInvoket)delegate
{
    EmoBox.Text = "...";
});

Edit:

I would also check the Emo array whether it is empty since face- and emotion recognitions not always succeeds! Thus, Emo[0] can result in "Index was out of range" exception. Following code makes sure it isn't empty:

var Emo = ...;
if (Emo.Length > 0)
{
    if (...)
        // use Emo[0]
    else if (...)
        // use Emo[0] differently
}

Let me know if there is anything unclear.