问:
Configure Windows 10 WAMP PHP to connect to SQLServer 2008
I have been spending days on this project trying to connect to a database and have reached some what of a stand still. I'm hoping someone has some experience with this.

I have been given Remote Desktop credentials to a Windows Server(R) 2008 box. There is a database running on that machine, and the client would like to pull data out of it from another domain - it is running SQLServer 2008.

As a test I am trying to connect to it via a local WAMP install. I was able to get the following .dll's running in my local PHP after downgrading it to its 32 bit version:
- php_pdo_sqlsrv_55_ts.dll
- php_sqlsrv_55_ts.dll

However, when I try to use PDO or the sqlsrv_connect function to connect, I receive the error message:

```<code>SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver 11 for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver 11 for SQL Server for x86: http://go.microsoft.com/fwlink/?LinkId=163712
</code>```

When I try to download and install the Microsoft ODBC Driver 11 (https://www.microsoft.com/en-us/download/details.aspx?id=36434) - I receive the following error message:

```<code>Installation of this product failed because it is not supported on this operating system. For information on supported configurations, see the product documentation.
</code>```

My question is, is there a way to connect to a SQLServer 2008 database from a WAMP install on a Windows 10 machine? - as far as I can tell it is not supported on Windows 10.

Thank you for your time.

答:
I'm on Windows 10. I have the 64bit wamp server installed running php 7.0.10.

I was able to connect to a Microsoft Azure database.

I had to install The
Microsoft® ODBC Driver 11 for SQL Server® - Windows
this version of it

```<code>ENU\x64\msodbcsql.msi
</code>```

This is the url:
    https://www.microsoft.com/en-us/download/details.aspx?id=36434

I also had to load "php_pdo_sqlsrv_7_ts_x64.dll" file to the folder
    C:/wamp64/bin/php/php7.0.10/ext

and add the

```<code>extension=php_pdo_odbc.dll
extension=php_pdo_sqlsrv_7_ts_x64.dll
</code>```

to the php.ini file

this was for a Cakephp 3.55 project

Body:
I have been spending days on this project trying to connect to a database and have reached some what of a stand still. I'm hoping someone has some experience with this.

I have been given Remote Desktop credentials to a Windows Server(R) 2008 box. There is a database running on that machine, and the client would like to pull data out of it from another domain - it is running SQLServer 2008.

As a test I am trying to connect to it via a local WAMP install. I was able to get the following .dll's running in my local PHP after downgrading it to its 32 bit version:
- php_pdo_sqlsrv_55_ts.dll
- php_sqlsrv_55_ts.dll

However, when I try to use PDO or the sqlsrv_connect function to connect, I receive the error message:

SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver 11 for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver 11 for SQL Server for x86: http://go.microsoft.com/fwlink/?LinkId=163712

When I try to download and install the Microsoft ODBC Driver 11 (https://www.microsoft.com/en-us/download/details.aspx?id=36434) - I receive the following error message:

Installation of this product failed because it is not supported on this operating system. For information on supported configurations, see the product documentation.

My question is, is there a way to connect to a SQLServer 2008 database from a WAMP install on a Windows 10 machine? - as far as I can tell it is not supported on Windows 10.

Thank you for your time.

Body:
I'm on Windows 10. I have the 64bit wamp server installed running php 7.0.10.

I was able to connect to a Microsoft Azure database.

I had to install The
Microsoft® ODBC Driver 11 for SQL Server® - Windows
this version of it

ENU\x64\msodbcsql.msi

This is the url:
    https://www.microsoft.com/en-us/download/details.aspx?id=36434

I also had to load "php_pdo_sqlsrv_7_ts_x64.dll" file to the folder
    C:/wamp64/bin/php/php7.0.10/ext

and add the

extension=php_pdo_odbc.dll
extension=php_pdo_sqlsrv_7_ts_x64.dll

to the php.ini file

this was for a Cakephp 3.55 project


来源: stackexchange

问:
"enable_annotations on the validator cannot be set as Annotations support is disabled" in symfony
I just created a bundle (successfully), and when I am about to create an entity via console this happened(also with clear:cache):

[LogicException]

  "enable_annotations" on the validator cannot be set as Annotations
  support      is disabled.

mi config.yml looks like

```<code>framework:
    validation: { enable_annotations: true }
    serializer: { enable_annotations: true }
</code>```

when i comment the options for validation throws the same Exception but with the serializer

when i comment both then it becomes a ServiceNotFoundException

[Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]
  The service "routing.loader" has a dependency on a non-existent
  service "an     notation_reader".

What is the problem, I am using symfony 3.3.11

答: You also need to enable annotation support in general. This happens automatically as soon as the Doctrine\Common\Annotations\Annotation class is present. For this, you need to make sure to install the doctrine/annotations package.

ContentLicense: CC BY-SA 3.0

Body:
I just created a bundle (successfully), and when I am about to create an entity via console this happened(also with clear:cache):

[LogicException]

  "enable_annotations" on the validator cannot be set as Annotations
  support      is disabled.

mi config.yml looks like

framework:
    validation: { enable_annotations: true }
    serializer: { enable_annotations: true }

when i comment the options for validation throws the same Exception but with the serializer

when i comment both then it becomes a ServiceNotFoundException

[Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]
  The service "routing.loader" has a dependency on a non-existent
  service "an     notation_reader".

What is the problem, I am using symfony 3.3.11


问:
C# LINQ to Entities One-To-Many relationship: Problem displaying last log entry data
I have a web application with two tables to track user shares.  Shares must be approved and so they go through a series of status changes.  Each status change is recorded in the log and timestamped. The current status is always the last entry in the log for that particular share.

Here are the entities (with brevity):

Shares:
ShareID
UserName

ShareLogs:
LogID
ShareID
CreatedDate
Status

I'm trying to get a list of Shares with their current status based on the last log entry.
Here is the SQL query that returns the correct result, but I'd like to do this using LINQ.

```<code>SELECT s.ShareID, s.UserName, sl.Code, sl.CreatedDate
FROM Shares s
INNER JOIN
(
SELECT s.ShareID, s.Code, s.CreatedDate
    FROM ShareLogs sl
    INNER JOIN (SELECT ShareID, MAX(CreatedDate) logDate FROM ShareLogs GROUP BY ShareID) sl2
        ON sl.ShareID = sl2.ShareID AND sl.CreatedDate = sl2.logDate) psl1
ON s.ShareID = sl1.ShareID
ORDER BY s.ShareID
</code>```

I have written one LINQ query that seems to work, but I feel like there should be a better way, as this query looks pretty terrible.

```<code>var query = from list in
(from s in context.Shares
join sl in context.ShareLogs on s.ShareID equals sl.ShareID
where sl.CreatedDate == s.ShareLogs.Max(e => e.CreatedDate)
select new
{
 share = s
 status = sl.Code,
 processDate = sl.CreatedDate
}).Where(e => e.status == 2 || e.status == 3)
select list;
</code>```

答:
```<code>var query = (from s in context.Shares
            let latestOrder = s.ShareLogs
                                         .OrderByDescending(sl => sl.CreatedDate)
                                         .First()
            select new
            {
                share = s,
                status = latestOrder.Code,
                processDate = latestOrder.CreatedDate
            }).Where(sl => sl.status == 2 || sl.status ==3);
</code>```

Let me know if you see this as an improvement.

Edit: I'm not 100% sure on where you need the Where filter so I left it. I'm thinking it may be actually needed in the Let statement. Or we could move it into the Comprehension syntax to be more consistent.

ContentLicense: CC BY-SA 2.5

Body:
I have a web application with two tables to track user shares.  Shares must be approved and so they go through a series of status changes.  Each status change is recorded in the log and timestamped. The current status is always the last entry in the log for that particular share.

Here are the entities (with brevity):

Shares:
ShareID
UserName

ShareLogs:
LogID
ShareID
CreatedDate
Status

I'm trying to get a list of Shares with their current status based on the last log entry.
Here is the SQL query that returns the correct result, but I'd like to do this using LINQ.

SELECT s.ShareID, s.UserName, sl.Code, sl.CreatedDate
FROM Shares s
INNER JOIN
(
SELECT s.ShareID, s.Code, s.CreatedDate
    FROM ShareLogs sl
    INNER JOIN (SELECT ShareID, MAX(CreatedDate) logDate FROM ShareLogs GROUP BY ShareID) sl2
        ON sl.ShareID = sl2.ShareID AND sl.CreatedDate = sl2.logDate) psl1
ON s.ShareID = sl1.ShareID
ORDER BY s.ShareID

I have written one LINQ query that seems to work, but I feel like there should be a better way, as this query looks pretty terrible.

var query = from list in
(from s in context.Shares
join sl in context.ShareLogs on s.ShareID equals sl.ShareID
where sl.CreatedDate == s.ShareLogs.Max(e => e.CreatedDate)
select new
{
 share = s
 status = sl.Code,
 processDate = sl.CreatedDate
}).Where(e => e.status == 2 || e.status == 3)
select list;

Body:
var query = (from s in context.Shares
            let latestOrder = s.ShareLogs
                                         .OrderByDescending(sl => sl.CreatedDate)
                                         .First()
            select new
            {
                share = s,
                status = latestOrder.Code,
                processDate = latestOrder.CreatedDate
            }).Where(sl => sl.status == 2 || sl.status ==3);

Let me know if you see this as an improvement.

Edit: I'm not 100% sure on where you need the Where filter so I left it. I'm thinking it may be actually needed in the Let statement. Or we could move it into the Comprehension syntax to be more consistent.


问:
Extract multiple css files to different directories
I'm trying to compile some sass files and extract each one to multiple paths.

Example:

resources/home/a.scss -> public/home/a.css

resources/home/layout/b.scss -> public/home/layout/b.scss

resources/login/c.scss -> public/login/c.css

At the moment I'm using this config and it bundles every scss file:

```<code>const path = require("path")
const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")

module.exports = {
// Context is an absolute path to the directory where webpack will be
// looking for our entry points.
context: path.resolve(process.cwd(), 'resources/assets'),

entry:
     [
       './sass/app/home/a.scss',
       './sass/app/home/layout/b.scss',
       './sass/app/login/c.scss',
    ],
output: {
    path: __dirname,
    filename: '[name].js'
},
module: {
    rules: [
        {
            test: /\.(scss)$/,
            loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
        }

    ]
},
plugins: [
    new ExtractTextPlugin({ filename: '[name].css', allChunks: true })
    ]
}
</code>```

答:
I think the problem is you are using an Array as the entry, which means that all of the dependencies (in this case the different css files, are added into the same output file).

You should change it to:

```<code>entry: {
 a:  './sass/app/home/a.scss',
 b:  './sass/app/home/layout/b.scss',
 c:  './sass/app/login/c.scss'
}
</code>```

You can read more here https://webpack.js.org/concepts/entry-points/#object-syntax

Body:
I'm trying to compile some sass files and extract each one to multiple paths.

Example:

resources/home/a.scss -> public/home/a.css

resources/home/layout/b.scss -> public/home/layout/b.scss

resources/login/c.scss -> public/login/c.css

At the moment I'm using this config and it bundles every scss file:

const path = require("path")
const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")

module.exports = {
// Context is an absolute path to the directory where webpack will be
// looking for our entry points.
context: path.resolve(process.cwd(), 'resources/assets'),

entry:
     [
       './sass/app/home/a.scss',
       './sass/app/home/layout/b.scss',
       './sass/app/login/c.scss',
    ],
output: {
    path: __dirname,
    filename: '[name].js'
},
module: {
    rules: [
        {
            test: /\.(scss)$/,
            loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
        }

    ]
},
plugins: [
    new ExtractTextPlugin({ filename: '[name].css', allChunks: true })
    ]
}

Body:
I think the problem is you are using an Array as the entry, which means that all of the dependencies (in this case the different css files, are added into the same output file).

You should change it to:

entry: {
 a:  './sass/app/home/a.scss',
 b:  './sass/app/home/layout/b.scss',
 c:  './sass/app/login/c.scss'
}

You can read more here https://webpack.js.org/concepts/entry-points/#object-syntax


问:
Nav bar not lining up with psd
I have a psd that is based on the 960 grid system which I am converting using bootstrap however there is padding to the left and right of the nav bar however I do not feel I am doing it right even though it looks ok

I am using bootstrap version 3.3.7

Image From Below Html

Image from Psd

Html for which produces the first image.

        Project name

Home

Services

Works

About

Contact

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

        Get Started

        Learn More

```
</div>
</div>
</p>

<p>CSS Which produces the first image I seem to have to put margin-right and left of 200px to get it to line up</p>

```.navbar-inverse .navbar-brand {
    margin-left: 220px;
    color: white !important;
    font-size: 64px;
}
.navbar-fixed-top {
    border: none;
    margin-right: 220px;
}
```

<p>Complete css for ref</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*--------------begin header -------------*/

body > div.navbar.navbar-inverse.navbar-fixed-top {
    background: transparent;
}
.navbar-fixed-top {
    border: none;
    margin-right: 220px;
}
.navbar {
    position: relative;
    min-height: 50px;
    margin-bottom: 20px;
    border: none !important;
    box-shadow: none !important;
}
.jumbotron {
    background-image: url(image/background.png);
    background-repeat: no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    padding: none !important;
    padding-bottom: none !important;
    margin-bottom: 0;
    max-height: 490px;
}
body > div.jumbotron > div > h1 {
    color: white;
    font-weight: bold;
}
body > div.jumbotron > div > h4 {
    color: white;
    font-weight: bold;
}
body > div.navbar.navbar-inverse.navbar-fixed-top > div.navbar-inner > ul > li:nth-child(1) > a {
    background-color: black;
    color: white !important;
    font-weight: bold;
}
ul li a {
    color: white;
    font-weight: bold;
}
.navbar-inverse .navbar-nav>li>a {
    color: white !important;
    font-weight: bold !important;
}
.navbar-brand {
    background-image: url (image/brand.png);
    background-repeat: no-repeat;
}
.navbar-inverse .navbar-brand {
    margin-left: 220px;
    color: white !important;
    font-size: 64px;
}
.navbar-fixed-top {
    border: none;
    margin-right: 220px;
}
/*--------------end header -------------*/
/*--------------begin services  -------------*/

.info-plan,
.info-design,
.info-develop,
.info launch {
    background-image: url('/image/services-sprtie.png');
    background-repeat: no-repeat;
}
.info-plan {
    height: 100px;
    background-position: -5px -5px;
}
/*--------------begin reset -------------*/

html,
body {
    height: 100%;
    margin: 0px;
    padding: 0px;
}
#navbar {
    margin-bottom: 0;
}
.alert {
    border-radius: 0;
}
.container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
}
.col-xs-1,
.col-sm-1,
.col-md-1,
.col-sm-1,
.col-xs-2,
.col-sm-2,
.col-md-2,
.col-sm-2,
.col-xs-3,
.col-sm-3,
.col-md-3,
.col-sm-3,
.col-xs-4,
.col-sm-4,
.col-md-4,
.col-sm-4,
.col-xs-5,
.col-sm-5,
.col-md-5,
.col-sm-5,
.col-xs-6,
.col-sm-6,
.col-md-6,
.col-sm-6,
.col-xs-7,
.col-sm-7,
.col-md-7,
.col-sm-7,
.col-xs-8,
.col-sm-8,
.col-md-8,
.col-sm-8,
.col-xs-9,
.col-sm-9,
.col-md-9,
.col-sm-9,
.col-xs-10,
.col-sm-10,
.col-md-10,
.col-sm-10,
.col-xs-11,
.col-sm-11,
.col-md-11,
.col-sm-11,
.col-xs-12,
.col-sm-12,
.col-md-12,
.col-sm-12 {
    position: relative;
    height: 100%;
    min-height: 1px;
    padding-right: 0;
    padding-left: 0;
}
.row {
    margin-right: 0;
    margin-left: 0;
}
.footer {
    margin-top: 0;
    padding-top: 0;
    padding-bottom: 0;
    border-top: none;
}
.panel {
    border: none;
}
/*--------------end reset -------------*/</code>```

Edit 2

I tried using

```<code>.custom-container {
  border:1px solid red;
  max-width:960px;
}
</code>```

But its made the whole site 960px i just want the nav and the content area to confirm to that but leave the jumbotron to be of full width.

Edit 3

This is my attempt but as you will see from screen shot 3 it is not working

```<code><div class="container">
     <div class="container custom-container">
<div class="navbar navbar-inverse navbar-fixed-top">

     <div class="navbar-header">
     <a class="navbar-brand" href="#">Project name</a>
    </div>
            <div class="navbar-inner">

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Home</a></li>
                    <li><a href="#services">Services</a></li>
                    <li><a href="#works">Works</a></li>
                    <li><a href="#about">About</a></li>
                    <li><a href="#contact">Contact</a></li>
                </ul>

       </div>
        </div>

        </div>
</code>```

Screen shot 3

答:
Simply wrap your navbar in a .container div. Then target it and set a max-width of your choice. E.G. 960px

.custom-container {
border:1px solid red;
max-width:760px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Start of container for navbar -->
<div class="container custom-container">
<!-- Start of container for navbar -->

<nav class="navbar navbar-default">
        <div class="container-fluid">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            Project name
          </div>
          <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
              <li class="active">Home</li>
              <li>About</li>
              <li>Contact</li>
              <li class="dropdown">
                Dropdown <span class="caret"></span>
                <ul class="dropdown-menu">
                  <li>Action</li>
                  <li>Another action</li>
                  <li>Something else here</li>
                  <li role="separator" class="divider"></li>
                  <li class="dropdown-header">Nav header</li>
                  <li>Separated link</li>
                  <li>One more separated link</li>
                </ul>
              </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
              <li class="active">Default <span class="sr-only">(current)</span></li>
              <li>Static top</li>
              <li>Fixed top</li>
            </ul>
          </div><!--/.nav-collapse -->
        </div><!--/.container-fluid -->
      </nav>

<!-- End of container for navbar -->
</div>
<!-- End of container for navbar --></code>```

Title: Nav bar not lining up with psd

Body:
I have a psd that is based on the 960 grid system which I am converting using bootstrap however there is padding to the left and right of the nav bar however I do not feel I am doing it right even though it looks ok

I am using bootstrap version 3.3.7

Image From Below Html

Image from Psd

Html for which produces the first image.

        Project name

Home

Services

Works

About

Contact

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

        Get Started

        Learn More

CSS Which produces the first image I seem to have to put margin-right and left of 200px to get it to line up

.navbar-inverse .navbar-brand {
    margin-left: 220px;
    color: white !important;
    font-size: 64px;
}
.navbar-fixed-top {
    border: none;
    margin-right: 220px;
}

Complete css for ref

/*--------------begin header -------------*/

body > div.navbar.navbar-inverse.navbar-fixed-top {
    background: transparent;
}
.navbar-fixed-top {
    border: none;
    margin-right: 220px;
}
.navbar {
    position: relative;
    min-height: 50px;
    margin-bottom: 20px;
    border: none !important;
    box-shadow: none !important;
}
.jumbotron {
    background-image: url(image/background.png);
    background-repeat: no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    padding: none !important;
    padding-bottom: none !important;
    margin-bottom: 0;
    max-height: 490px;
}
body > div.jumbotron > div > h1 {
    color: white;
    font-weight: bold;
}
body > div.jumbotron > div > h4 {
    color: white;
    font-weight: bold;
}
body > div.navbar.navbar-inverse.navbar-fixed-top > div.navbar-inner > ul > li:nth-child(1) > a {
    background-color: black;
    color: white !important;
    font-weight: bold;
}
ul li a {
    color: white;
    font-weight: bold;
}
.navbar-inverse .navbar-nav>li>a {
    color: white !important;
    font-weight: bold !important;
}
.navbar-brand {
    background-image: url (image/brand.png);
    background-repeat: no-repeat;
}
.navbar-inverse .navbar-brand {
    margin-left: 220px;
    color: white !important;
    font-size: 64px;
}
.navbar-fixed-top {
    border: none;
    margin-right: 220px;
}
/*--------------end header -------------*/
/*--------------begin services  -------------*/

.info-plan,
.info-design,
.info-develop,
.info launch {
    background-image: url('/image/services-sprtie.png');
    background-repeat: no-repeat;
}
.info-plan {
    height: 100px;
    background-position: -5px -5px;
}
/*--------------begin reset -------------*/

html,
body {
    height: 100%;
    margin: 0px;
    padding: 0px;
}
#navbar {
    margin-bottom: 0;
}
.alert {
    border-radius: 0;
}
.container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
}
.col-xs-1,
.col-sm-1,
.col-md-1,
.col-sm-1,
.col-xs-2,
.col-sm-2,
.col-md-2,
.col-sm-2,
.col-xs-3,
.col-sm-3,
.col-md-3,
.col-sm-3,
.col-xs-4,
.col-sm-4,
.col-md-4,
.col-sm-4,
.col-xs-5,
.col-sm-5,
.col-md-5,
.col-sm-5,
.col-xs-6,
.col-sm-6,
.col-md-6,
.col-sm-6,
.col-xs-7,
.col-sm-7,
.col-md-7,
.col-sm-7,
.col-xs-8,
.col-sm-8,
.col-md-8,
.col-sm-8,
.col-xs-9,
.col-sm-9,
.col-md-9,
.col-sm-9,
.col-xs-10,
.col-sm-10,
.col-md-10,
.col-sm-10,
.col-xs-11,
.col-sm-11,
.col-md-11,
.col-sm-11,
.col-xs-12,
.col-sm-12,
.col-md-12,
.col-sm-12 {
    position: relative;
    height: 100%;
    min-height: 1px;
    padding-right: 0;
    padding-left: 0;
}
.row {
    margin-right: 0;
    margin-left: 0;
}
.footer {
    margin-top: 0;
    padding-top: 0;
    padding-bottom: 0;
    border-top: none;
}
.panel {
    border: none;
}
/*--------------end reset -------------*/

Edit 2

I tried using

.custom-container {
  border:1px solid red;
  max-width:960px;
}

But its made the whole site 960px i just want the nav and the content area to confirm to that but leave the jumbotron to be of full width.

Edit 3

This is my attempt but as you will see from screen shot 3 it is not working

     Project name

Home

Services

Works

About

Contact

Screen shot 3

Body:
Simply wrap your navbar in a .container div. Then target it and set a max-width of your choice. E.G. 960px

.custom-container {
border:1px solid red;
max-width:760px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Start of container for navbar -->
<div class="container custom-container">
<!-- Start of container for navbar -->

<nav class="navbar navbar-default">
        <div class="container-fluid">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Project name</a>
          </div>
          <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="#">About</a></li>
              <li><a href="#">Contact</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li role="separator" class="divider"></li>
                  <li class="dropdown-header">Nav header</li>
                  <li><a href="#">Separated link</a></li>
                  <li><a href="#">One more separated link</a></li>
                </ul>
              </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
              <li class="active"><a href="./">Default <span class="sr-only">(current)</span></a></li>
              <li><a href="../navbar-static-top/">Static top</a></li>
              <li><a href="../navbar-fixed-top/">Fixed top</a></li>
            </ul>
          </div><!--/.nav-collapse -->
        </div><!--/.container-fluid -->
      </nav>

<!-- End of container for navbar -->
</div>
<!-- End of container for navbar -->


问:
What is the best way to export all Nestuite data using API
I wanted to know is there any way to create a dynamic restlet that includes all the data and fields. This restlet should be able to get data from a newly created field also without modifying the restlet code.

```<code>getAllfields()
</code>```

this can be used to get all the fields in a record, but how to use this to get all the data from a record if after restlet is made someone adds a new cuscol field in transaction line item. Also what about custom records.

答: You could load the record and use JSON.stringify to send it over. This would work on custom records as well.</p>

Body:
I wanted to know is there any way to create a dynamic restlet that includes all the data and fields. This restlet should be able to get data from a newly created field also without modifying the restlet code.

getAllfields()

this can be used to get all the fields in a record, but how to use this to get all the data from a record if after restlet is made someone adds a new cuscol field in transaction line item. Also what about custom records.


问:
Simulate an inline onkeydown event
I have an input element which I do not control
for example:

```<code><input tabindex="2" onkeypress="if(NotReady_Key())return;fnKeyPressNum(this,'N',0);"onkeydown="if(NotReady_Key())return;fnKeyDownNum(this,9,0);" id="someElement"/>
</code>```

In internet explorer 8 and 9, I am trying to find a way to make the element perform as if the "enter" button has been pressed upon the input,

I failed to find a JS way to simulate the press

but I was thinking, is it possible to grab the inline method:

```<code>onkeydown="if(NotReady_Key())return;fnKeyDownNum(this,9,0);"
</code>```

from the element, obtain the element by elementById,
and execute it as if the event actually happened?
here is what I tried so far(I am using jquery):

```<code> //get dom element
var element = $("#someElement")[0];
//simulate the event
//insert element as "this"
(function(){
fnKeyDownNum(this,9,0);
}).call(element);
</code>```

but it doesn't seem to work as excpected, did I forget something?
I think that I also need to make sure other system variables are simulated other than this, to fully simulate the "ENTER" event.

what can i do?

option 2 is of course to simulate a real key press of "ENTER" right on the input, but i failed to find a way to do so in IE8/9 so far, any way would be accepted even using VBS if thats an option.

please note, I specifically need IE8 and IE9 support.

答:
If you just need to call fnKeyDownNum with an element, give this a try:

```<code>fnKeyDownNum(document.getElementById('someElement'),9,0);
</code>```

But if you need to really simulate a keypress (because, a keypress can add input to a field, and if you press enter on a form element it also has the effect of submitting the form) you will have to manage that separately.

Title: Simulate an inline onkeydown event

Body:
I have an input element which I do not control
for example:

<input tabindex="2" onkeypress="if(NotReady_Key())return;fnKeyPressNum(this,'N',0);"onkeydown="if(NotReady_Key())return;fnKeyDownNum(this,9,0);" id="someElement"/>

In internet explorer 8 and 9, I am trying to find a way to make the element perform as if the "enter" button has been pressed upon the input,

I failed to find a JS way to simulate the press

but I was thinking, is it possible to grab the inline method:

onkeydown="if(NotReady_Key())return;fnKeyDownNum(this,9,0);"

from the element, obtain the element by elementById,
and execute it as if the event actually happened?
here is what I tried so far(I am using jquery):

 //get dom element
var element = $("#someElement")[0];
//simulate the event
//insert element as "this"
(function(){
fnKeyDownNum(this,9,0);
}).call(element);

but it doesn't seem to work as excpected, did I forget something?
I think that I also need to make sure other system variables are simulated other than this, to fully simulate the "ENTER" event.

what can i do?

option 2 is of course to simulate a real key press of "ENTER" right on the input, but i failed to find a way to do so in IE8/9 so far, any way would be accepted even using VBS if thats an option.

please note, I specifically need IE8 and IE9 support.

Body:
If you just need to call fnKeyDownNum with an element, give this a try:

fnKeyDownNum(document.getElementById('someElement'),9,0);

But if you need to really simulate a keypress (because, a keypress can add input to a field, and if you press enter on a form element it also has the effect of submitting the form) you will have to manage that separately.


问:
What unit test to write for a class using generics in Java?
Taking the very specific example of the JpaDao class defined in this article:

```<code>public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}
</code>```

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

答:
From the JUnit FAQ:

4) Under what conditions should I test get() and set() methods?

Unit tests are intended to alleviate fear that something might break. If you think a get() or set() method could reasonably break, or has in fact contributed to a defect, then by all means write a test.

In short, test until you're confident. What you choose to test is subjective, based on your experiences and confidence level. Remember to be practical and maximize your testing investment.

It also states:

"Test until fear turns to boredom."

I don't think your question is specific to generics since the question would still be the same even if you weren't using generics.  In this case I would choose to test one object (Either real or canned for test purposes).  As you discover problems then write tests to address those specific deficiencies.

Body:
Taking the very specific example of the JpaDao class defined in this article:

public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?


问:
How to improve this code to print a triangle of numbers?
I am a beginner and have just started to code. I wrote this getting below mentioned output and also got a result. But I have a feeling my code is not efficient, could anyone kindly show me how to write this better?

```<code>    1
   22
  333
 4444
55555
</code>```

```<code>package basic;

import java.util.Scanner;

public class Pattern {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the number of rows?");
        int n = scan.nextInt();

        int num1 = 1;

        for (int i = 1; i <= n; i++) {
            for (int k = n - 1; k >= i; k--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print(num1);
            }
            System.out.println();
            num1 = num1 + 1;

        }

    }
}
</code>```

答:
Suggestions for Improvement

Your num1 variable is unnecessary

Unnecessary for loops.

```<code>package basic;

import java.util.Scanner;

public class Pattern {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter the number of rows of the pyramid?");
    int n = scan.nextInt();

    for (int i = 1; i <= n; i++) {
        for (int j=1; j<=n;j++){
            if (j <= n-i){
                System.out.print(" ");
            }else{
                System.out.print(i);
            }
        }
        System.out.println()
    }

}
</code>```

Ouput : When input is 5

****1

***22

**333

*4444

55555

Body:
I am a beginner and have just started to code. I wrote this getting below mentioned output and also got a result. But I have a feeling my code is not efficient, could anyone kindly show me how to write this better?

    1
   22
  333
 4444
55555

package basic;

import java.util.Scanner;

public class Pattern {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the number of rows?");
        int n = scan.nextInt();

        int num1 = 1;

        for (int i = 1; i <= n; i++) {
            for (int k = n - 1; k >= i; k--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print(num1);
            }
            System.out.println();
            num1 = num1 + 1;

        }

    }
}

Body:
Suggestions for Improvement

Your num1 variable is unnecessary

Unnecessary for loops.

package basic;

import java.util.Scanner;

public class Pattern {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter the number of rows of the pyramid?");
    int n = scan.nextInt();

    for (int i = 1; i <= n; i++) {
        for (int j=1; j<=n;j++){
            if (j <= n-i){
                System.out.print(" ");
            }else{
                System.out.print(i);
            }
        }
        System.out.println()
    }

}

Ouput : When input is 5

****1

***22

**333

*4444

55555


问:
CRM 2016 - How to create a parent-child relationship with multiple parent types?
I have an entity - EntityZ, which has a ParentId where ParentId could be EntityA.Id, EntityB.Id or EntityC.Id. Is it possible to create this in MS Dynamics CRM 2016? If yes, how? I've looked but couldn't find a similar question or any help on the web.

答:
An entity can be the child party in only one full parental relationship. When you are looking for a way to cascade record ownership, deletion a.o. between mutiple parent - child entities you can create configurable cascading relationships.

As Arun Vinoth pointed out you can design your entity as an activity type. However, this may conflict with the semantics of activity records in CRM. Also, doing this would make it possible to associate the child entity to any entity that is enabled for activities.


问:
Golang - windows console exits while running go.exe
I installed Go in Windows 10 with the MSI installer. However, when I run go in cmd (or PowerShell) with an argument, such as env, build, install, list, ...
The console window closes (or crashes?) after the go command is run. This prevents me from seeing any errors or anything while compiling go code.

Is there some sort of log in windows which contains console host data, such as crashing, errors, and warnings? This would be very helpful to find out if console or console host is crashing for some reason.

As an example:

```<code>go env
</code>```

won't output anything and the console window will immediately close.

Edit: Just to clarify, I am not running this command in the run dialog, I am running it from an administrator command prompt (I tried using PowerShell, also no luck). If I run:

```<code>go help
</code>```

It will work properly. However, as soon as I run go with any other argument, such as:

```<code>go install <target>
</code>```

or

```<code>go build <target>
</code>```

The process will work but the console will exit before giving me any information.

Edit:

I've discovered a temporary fix... If I run go commands in a Cygwin terminal they work as usual. This is very strange.

答:
I figured it out, I have Cygwin installed and I put it in my path environment variable. Turns out the git installation from Cygwin was interfering with the regular up to date, git installation. This was causing go with args to only work if I had the Cygwin terminal running. On golang-nuts someone also mentioned that some git versions have some bug where come.exe is called causing go commands to fail on windows.

To fix I just removed Cygwin from path and updated git to latest version.

Body:
I installed Go in Windows 10 with the MSI installer. However, when I run go in cmd (or PowerShell) with an argument, such as env, build, install, list, ...
The console window closes (or crashes?) after the go command is run. This prevents me from seeing any errors or anything while compiling go code.

Is there some sort of log in windows which contains console host data, such as crashing, errors, and warnings? This would be very helpful to find out if console or console host is crashing for some reason.

As an example:

go env

won't output anything and the console window will immediately close.

Edit: Just to clarify, I am not running this command in the run dialog, I am running it from an administrator command prompt (I tried using PowerShell, also no luck). If I run:

go help

It will work properly. However, as soon as I run go with any other argument, such as:

go install <target>

or

go build <target>

The process will work but the console will exit before giving me any information.

Edit:

I've discovered a temporary fix... If I run go commands in a Cygwin terminal they work as usual. This is very strange.


问:
Python regex to match dates
What regular expression in Python do I use to match dates like this: "11/12/98"?</p>

ContentLicense: CC BY-SA 4.0

Title: Python regex to match dates

Body:
I find the below RE working fine for Date in the following format;

14-11-2017

14.11.2017

14|11|2017

It can accept year from 2000-2099

Please do not forget to add $ at the end,if not it accept 14-11-201 or 20177

date="13-11-2017"

x=re.search("^([1-9] |1[0-9]| 2[0-9]|3[0-1])(.|-)([1-9] |1[0-2])(.|-|)20[0-9][0-9]$",date)

x.group()

output = '13-11-2017'


问:
Php search in database to show data, not working
i'm trying to display some data from my database, and i dosen't work when i try to display some of the data, specified by a search bar. Here is the code. I hope someone can fix my problem.

Ive tried for a few hours, but nothing seems to work.

I removed most of the html code, to even be able to post.

<?php
 include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>

    <form>
    <input type="text" name="search" placeholder="Search for graphicscard"/>
    <input type="submit" value="Search" />

<?php

?>

    </form>

Graphicscard
Coin
Hashrate
Bios-modded
Core-clock
Memory-clock
Power draw
Additional info

      <?
  if(isset($_POST['search'])) {
        $searchq = $_POST['search'];
        $searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);

        $query = mysqli_query("SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
        $count = mysqli_num_rows($queryQ);

            while ($row = mysqli_fetch_array($query)) {
                echo "
";
                echo "".$row['name']."	";
                echo "".$row['coin'] . "	";
                echo "".$row['hashrate'] . "	";
                echo "".$row['bios_mod'] . "	";
                echo "".$row['core_clock'] . "	";
                echo "".$row['memory_clock'] . "	";
                echo "".$row['power_draw'] . "	";
                echo "".$row['additional_info'] . "	";
                echo "
";
            }
        }

        ?>```

答:
Change your code on this:

```<code>  if(isset($_POST['search'])) {
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);

    $query = mysql_query("SELECT * FROM cards WHERE name LIKE '$searchq%' OR coin LIKE '$searchq%'") or die ("No results");
    $count = mysql_num_rows($query);

        while ($row = mysql_fetch_array($query)) {
            echo "<tr>";
            echo "<td>".$row['name']."</td>";
            echo "<td>".$row['coin'] . "</td>";
            echo "<td>".$row['hashrate'] . "</td>";
            echo "<td>".$row['bios_mod'] . "</td>";
            echo "<td>".$row['core_clock'] . "</td>";
            echo "<td>".$row['memory_clock'] . "</td>";
            echo "<td>".$row['power_draw'] . "</td>";
            echo "<td>".$row['additional_info'] . "</td>";
            echo "</tr>";
        }
    }
</code>```

If you use mysqli please see this referenc on how to use it

in your tag form add method of sending data POST: <form method="POST">

Body:
Change your code on this:

  if(isset($_POST['search'])) {
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);

    $query = mysql_query("SELECT * FROM cards WHERE name LIKE '$searchq%' OR coin LIKE '$searchq%'") or die ("No results");
    $count = mysql_num_rows($query);

        while ($row = mysql_fetch_array($query)) {
            echo "<tr>";
            echo "<td>".$row['name']."</td>";
            echo "<td>".$row['coin'] . "</td>";
            echo "<td>".$row['hashrate'] . "</td>";
            echo "<td>".$row['bios_mod'] . "</td>";
            echo "<td>".$row['core_clock'] . "</td>";
            echo "<td>".$row['memory_clock'] . "</td>";
            echo "<td>".$row['power_draw'] . "</td>";
            echo "<td>".$row['additional_info'] . "</td>";
            echo "</tr>";
        }
    }

If you use mysqli please see this referenc on how to use it

in your tag form add method of sending data POST: <form method="POST">


问:
How to evaluate a dataset for class overlapping
I'm using Weka to develop a classifier for a medical problem. This dataset has a class imbalance situation and I want to know if there is also a problem of class overlapping. Each record has 30 attributes, how can I discover if there is class overlapping using Weka features?</p>

答:
I think you mean by 'class overlapping', Exist similar instances that belong to different classes. Simply, you can remove them. In awk, you could do the following:

awk '!NF || !seen[$0]++' inputFile > outputFile


问:
Show and Hide Div onMouseOver
Hey guys, need just a little bit of help here, it's very close to what I'm after but not quite.

I want the text links I hover over to animate hidden text in a target div. So when I hover over link A, that text fades in; when I hover over link B, the previous text fades away and new text fades in.

Here is my javascript:

```<code><script type="text/javascript">
function ShowHide(){
    $("#textMessages").animate({"height": "toggle"}, { duration: 1000 });
    }
</script>
</code>```

Here are my links:

```<code><a onMouseOver="ShowHide(); return false;" href="#">Message A</a>

<a onMouseOver="ShowHide(); return false;" href="#">Message B</a>

<a onMouseOver="ShowHide(); return false;" href="#">Message C</a>
</code>```

And here is my target div with text snippets to fade in and fade out:

```<code><div id="textMessages">

<div id="defaultMessage">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

<div id="MessageA">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

<div id="MessageB">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

<div id="MessageC">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

</div>
</code>```

I assume I will need to set the #MessageA/B/C display:none

答:
i've "improved" the answer by rcravens

http://jsfiddle.net/md3Xe/3/

Title: Show and Hide Div onMouseOver

Body:
Hey guys, need just a little bit of help here, it's very close to what I'm after but not quite.

I want the text links I hover over to animate hidden text in a target div. So when I hover over link A, that text fades in; when I hover over link B, the previous text fades away and new text fades in.

Here is my javascript:

Here are my links:

Message A

Message B

Message C

And here is my target div with text snippets to fade in and fade out:

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit

I assume I will need to set the #MessageA/B/C display:none


问:
angularjs $scope.$watchCollection on nested JSON document
I'm having troubles with the $watchCollection() function. The problem might be the fact that I'm trying to reference a nested part of a JSON document. I really can't figure the problem out.

HTML

```<code><div ng-app="MovieApp">
  <div ng-controller="FilterController as FilterCtrl" ng-init="FilterCtrl.init()">
    <ul ng-repeat="filter in filters">
      <b>{{filter.name}}</b>
      <li ng-repeat="element in filter.elements">
        <input type="checkbox" ng-model="element.ticked" />{{element.name}}
      </li>
    </ul>
  </div>
</div>
</code>```

JS

```<code>var app = angular.module('MovieApp', []);

app.controller('FilterController', function($scope){
  this.init = function(){
    $scope.filters = jsonfilters;
  };

  $scope.$watchCollection('filters', function(newValue,oldValue){
    alert("A filter has been changed");
  });

});

var jsonfilters = [
{
  "name": "Genres",
  "elements": [
    {"name": "Adventure", "ticked": true},
    {"name": "Action", "ticked": true},
    {"name": "Fantasy", "ticked": true},
    {"name": "Science Fiction", "ticked": true},
    {"name": "Family", "ticked": true},
    {"name": "Thriller", "ticked": true},
    {"name": "Animation", "ticked": true},
    {"name": "Comedy", "ticked": true},
    {"name": "Drama", "ticked": true}
  ]
},
{
  "name": "Companies",
  "elements": [
    {"name": "Warner Bros.", "ticked": true},
    {"name": "Walt Disney Pictures", "ticked": true},
    {"name": "Paramount Pictures", "ticked": true},
    {"name": "Columbia Pictures", "ticked": true},
    {"name": "DreamWorks Animation", "ticked": true},
    {"name": "Universal Pictures", "ticked": true},
    {"name": "Twentieth Century Fox Film Corporation", "ticked": true},
    {"name": "Legendary Pictures", "ticked": true},
    {"name": "Marvel Studios", "ticked": true},
    {"name": "Village Roadshow Pictures", "ticked": true},
    {"name": "Jerry Bruckheimer Films", "ticked": true}
  ]
}
];
</code>```

What I want to achieve is being able to call a function everytime one of the checkboxes are ticked/unticked.
I made a jsfiddle to demo the problem.

答:
If you don't need $watchCollection, I suggest avoiding it. There is a large cost to using it, aside from the fact that you didn't get it to work.

Instead try using an event to let you know what changed.

I am using the ng-change directive to know when the user clicks on a checkbox.

HTML

```<code><div ng-app="MovieApp">
  <div ng-controller="FilterController as FilterCtrl" ng-init="FilterCtrl.init()">
    <ul ng-repeat="filter in filters">
      <b>{{filter.name}}</b>
      <li ng-repeat="element in filter.elements">
        <input type="checkbox" ng-model="element.ticked" ng-change="filterChanged($event, element)" />{{element.name}}
      </li>
    </ul>
  </div>
</div>
</code>```

JS

```<code>var app = angular.module('MovieApp', []);

app.controller('FilterController', function($scope){
  this.init = function(){
    $scope.filters = jsonfilters;
  };

    $scope.filterChanged = function($event, element) {
    console.log('Filter changed:', element);
  }
});

var jsonfilters = [
  {
    "name": "Genres",
    "elements": [
      {"name": "Adventure", "ticked": true},
      {"name": "Action", "ticked": true},
      {"name": "Fantasy", "ticked": true},
      {"name": "Science Fiction", "ticked": true},
      {"name": "Family", "ticked": true},
      {"name": "Thriller", "ticked": true},
      {"name": "Animation", "ticked": true},
      {"name": "Comedy", "ticked": true},
      {"name": "Drama", "ticked": true}
    ]
  },
  {
    "name": "Companies",
    "elements": [
      {"name": "Warner Bros.", "ticked": true},
      {"name": "Walt Disney Pictures", "ticked": true},
      {"name": "Paramount Pictures", "ticked": true},
      {"name": "Columbia Pictures", "ticked": true},
      {"name": "DreamWorks Animation", "ticked": true},
      {"name": "Universal Pictures", "ticked": true},
      {"name": "Twentieth Century Fox Film Corporation", "ticked": true},
      {"name": "Legendary Pictures", "ticked": true},
      {"name": "Marvel Studios", "ticked": true},
      {"name": "Village Roadshow Pictures", "ticked": true},
      {"name": "Jerry Bruckheimer Films", "ticked": true}
    ]
  }
];
</code>```

See my jsfiddle here: https://jsfiddle.net/intervalia/5k7ehswt/2/

Body:
I'm having troubles with the $watchCollection() function. The problem might be the fact that I'm trying to reference a nested part of a JSON document. I really can't figure the problem out.

HTML

      {{filter.name}}

        <input type="checkbox" ng-model="element.ticked" />{{element.name}}

JS

var app = angular.module('MovieApp', []);

app.controller('FilterController', function($scope){
  this.init = function(){
    $scope.filters = jsonfilters;
  };

  $scope.$watchCollection('filters', function(newValue,oldValue){
    alert("A filter has been changed");
  });

});

var jsonfilters = [
{
  "name": "Genres",
  "elements": [
    {"name": "Adventure", "ticked": true},
    {"name": "Action", "ticked": true},
    {"name": "Fantasy", "ticked": true},
    {"name": "Science Fiction", "ticked": true},
    {"name": "Family", "ticked": true},
    {"name": "Thriller", "ticked": true},
    {"name": "Animation", "ticked": true},
    {"name": "Comedy", "ticked": true},
    {"name": "Drama", "ticked": true}
  ]
},
{
  "name": "Companies",
  "elements": [
    {"name": "Warner Bros.", "ticked": true},
    {"name": "Walt Disney Pictures", "ticked": true},
    {"name": "Paramount Pictures", "ticked": true},
    {"name": "Columbia Pictures", "ticked": true},
    {"name": "DreamWorks Animation", "ticked": true},
    {"name": "Universal Pictures", "ticked": true},
    {"name": "Twentieth Century Fox Film Corporation", "ticked": true},
    {"name": "Legendary Pictures", "ticked": true},
    {"name": "Marvel Studios", "ticked": true},
    {"name": "Village Roadshow Pictures", "ticked": true},
    {"name": "Jerry Bruckheimer Films", "ticked": true}
  ]
}
];

What I want to achieve is being able to call a function everytime one of the checkboxes are ticked/unticked.
I made a jsfiddle to demo the problem.

Body:
If you don't need $watchCollection, I suggest avoiding it. There is a large cost to using it, aside from the fact that you didn't get it to work.

Instead try using an event to let you know what changed.

I am using the ng-change directive to know when the user clicks on a checkbox.

HTML

<div ng-app="MovieApp">
  <div ng-controller="FilterController as FilterCtrl" ng-init="FilterCtrl.init()">
    <ul ng-repeat="filter in filters">
      <b>{{filter.name}}</b>
      <li ng-repeat="element in filter.elements">
        <input type="checkbox" ng-model="element.ticked" ng-change="filterChanged($event, element)" />{{element.name}}
      </li>
    </ul>
  </div>
</div>

JS

var app = angular.module('MovieApp', []);

app.controller('FilterController', function($scope){
  this.init = function(){
    $scope.filters = jsonfilters;
  };

    $scope.filterChanged = function($event, element) {
    console.log('Filter changed:', element);
  }
});

var jsonfilters = [
  {
    "name": "Genres",
    "elements": [
      {"name": "Adventure", "ticked": true},
      {"name": "Action", "ticked": true},
      {"name": "Fantasy", "ticked": true},
      {"name": "Science Fiction", "ticked": true},
      {"name": "Family", "ticked": true},
      {"name": "Thriller", "ticked": true},
      {"name": "Animation", "ticked": true},
      {"name": "Comedy", "ticked": true},
      {"name": "Drama", "ticked": true}
    ]
  },
  {
    "name": "Companies",
    "elements": [
      {"name": "Warner Bros.", "ticked": true},
      {"name": "Walt Disney Pictures", "ticked": true},
      {"name": "Paramount Pictures", "ticked": true},
      {"name": "Columbia Pictures", "ticked": true},
      {"name": "DreamWorks Animation", "ticked": true},
      {"name": "Universal Pictures", "ticked": true},
      {"name": "Twentieth Century Fox Film Corporation", "ticked": true},
      {"name": "Legendary Pictures", "ticked": true},
      {"name": "Marvel Studios", "ticked": true},
      {"name": "Village Roadshow Pictures", "ticked": true},
      {"name": "Jerry Bruckheimer Films", "ticked": true}
    ]
  }
];

See my jsfiddle here: https://jsfiddle.net/intervalia/5k7ehswt/2/


问:
TraversalEngine abstract class utilisation
Firstly, I am sorry but I don't speak English very well. Secondly, I have a problem with nodes which are put in a gridpane. In fact, if the focus is taken by the first one which is located on the top left side, when I push the tab key, the focus is not taken by the other which is located on the right.

People ask me to use the traversalEngine abstract class in order to solve this problem. Nevertheless, when I try to implement an engine object, it doesn't work if I put the parameters which are shown everywhere on the web:

```<code>TraversalEngine engine = new TraversalEngine(gridPane, false) {
</code>```

It ask me to remove the parameters. If I do it, I don't have access to the trav method. In fact, it is the getRoot method which appears and can be implemented:

```<code>TraversalEngine engine = new TraversalEngine() {

        @Override
        protected Parent getRoot() {
            // TODO Auto-generated method stub
            return null;
        }
    }
</code>```

Is there something which can be make in order to solve this problem?

Thanks you for your help

答:
The traversal order for focusing nodes in a parent is the order in which they occur in the child list. Assuming every child contains at most one focusable node you could simply add the children line by line or reorder the children.

This could be done programmatically of course, but adding the children in the correct order in the first place would be more efficient...

```<code>public static int getColumnIndex(Node n) {
    Integer i = GridPane.getColumnIndex(n);
    return i == null ? 0 : i;
}

public static int getRowIndex(Node n) {
    Integer i = GridPane.getRowIndex(n);
    return i == null ? 0 : i;
}
</code>```

```<code>grid.getChildren().sort(Comparator.comparingInt(ContainingClass::getRowIndex).thenComparingInt(ContainingClass::getColumnIndex));
</code>```

Body:
Firstly, I am sorry but I don't speak English very well. Secondly, I have a problem with nodes which are put in a gridpane. In fact, if the focus is taken by the first one which is located on the top left side, when I push the tab key, the focus is not taken by the other which is located on the right.

People ask me to use the traversalEngine abstract class in order to solve this problem. Nevertheless, when I try to implement an engine object, it doesn't work if I put the parameters which are shown everywhere on the web:

TraversalEngine engine = new TraversalEngine(gridPane, false) {

It ask me to remove the parameters. If I do it, I don't have access to the trav method. In fact, it is the getRoot method which appears and can be implemented:

TraversalEngine engine = new TraversalEngine() {

        @Override
        protected Parent getRoot() {
            // TODO Auto-generated method stub
            return null;
        }
    }

Is there something which can be make in order to solve this problem?

Thanks you for your help

Body:
The traversal order for focusing nodes in a parent is the order in which they occur in the child list. Assuming every child contains at most one focusable node you could simply add the children line by line or reorder the children.

This could be done programmatically of course, but adding the children in the correct order in the first place would be more efficient...

public static int getColumnIndex(Node n) {
    Integer i = GridPane.getColumnIndex(n);
    return i == null ? 0 : i;
}

public static int getRowIndex(Node n) {
    Integer i = GridPane.getRowIndex(n);
    return i == null ? 0 : i;
}

grid.getChildren().sort(Comparator.comparingInt(ContainingClass::getRowIndex).thenComparingInt(ContainingClass::getColumnIndex));


问:
Several case when's with output on same row
I'm having issues with a pretty complicated postgreSQL query that I can briefly sum up as follows:

I have a set of costumers who buy apples, oranges, or both. I also know each date of each purchase. What I'd like is the date of the first purchase for each customer and each fruit.

To do this, I use the following query:

```<code>SELECT distinct
CASE WHEN fruitType = 'apple' then min(purchaseDate)
ELSE null END AS appleFirstPurchaseDate
, CASE WHEN fruitType = 'orange' then min(purchaseDate)
ELSE null END AS orangeFirstPurchaseDate
FROM fruitPurchases
GROUP BY fruitType
</code>```

I also have this version (I don't know which one is better for this problem):

```<code>SELECT distinct
CASE WHEN fruitType = 'apple' then min(purchaseDate) over(partition by fruitType)
ELSE null END AS appleFirstPurchaseDate
, CASE WHEN fruitType = 'orange' then min(purchaseDate) over(partition by fruitType)
ELSE null END AS orangeFirstPurchaseDate
FROM fruitPurchases
</code>```

Both give the same result and, when the customer buys only oranges or only apples, it works fine. However, when they've already bought both, I get this for one same customer:

```<code>appleFirstPurchaseDate  orangeFirstPurchaseDate
----------------------  -----------------------
       2017-05-03                [NULL]
         [NULL]                2016-11-25
</code>```

While the result I'm dreaming of is:

```<code>appleFirstPurchaseDate  orangeFirstPurchaseDate
----------------------  -----------------------
       2017-05-03              2016-11-25
</code>```

I also checked this solution (the first of the 3 options) that suggests the use of the MAX function but, because of my MIN function, I get this error message: "aggregate functions calls cannot be nested".

I am vaguely aware that a subquery could solve this problem but, given the whole messy code that I'm working on, I'd rather get a solution that doesn't add new FROM clauses and that would keep using CASE WHEN's. If impossible, I'd be happy with any solution :)

答:
```<code>select
    min(purchaseDate) filter (where fruitType = 'apple') as apple,
    min(purchaseDate) filter (where fruitType = 'orange') as orange,
    customer
from fruitPurchases
group by customer
</code>```

Body:
I'm having issues with a pretty complicated postgreSQL query that I can briefly sum up as follows:

I have a set of costumers who buy apples, oranges, or both. I also know each date of each purchase. What I'd like is the date of the first purchase for each customer and each fruit.

To do this, I use the following query:

SELECT distinct
CASE WHEN fruitType = 'apple' then min(purchaseDate)
ELSE null END AS appleFirstPurchaseDate
, CASE WHEN fruitType = 'orange' then min(purchaseDate)
ELSE null END AS orangeFirstPurchaseDate
FROM fruitPurchases
GROUP BY fruitType

I also have this version (I don't know which one is better for this problem):

SELECT distinct
CASE WHEN fruitType = 'apple' then min(purchaseDate) over(partition by fruitType)
ELSE null END AS appleFirstPurchaseDate
, CASE WHEN fruitType = 'orange' then min(purchaseDate) over(partition by fruitType)
ELSE null END AS orangeFirstPurchaseDate
FROM fruitPurchases

Both give the same result and, when the customer buys only oranges or only apples, it works fine. However, when they've already bought both, I get this for one same customer:

appleFirstPurchaseDate  orangeFirstPurchaseDate
----------------------  -----------------------
       2017-05-03                [NULL]
         [NULL]                2016-11-25

While the result I'm dreaming of is:

appleFirstPurchaseDate  orangeFirstPurchaseDate
----------------------  -----------------------
       2017-05-03              2016-11-25

I also checked this solution (the first of the 3 options) that suggests the use of the MAX function but, because of my MIN function, I get this error message: "aggregate functions calls cannot be nested".

I am vaguely aware that a subquery could solve this problem but, given the whole messy code that I'm working on, I'd rather get a solution that doesn't add new FROM clauses and that would keep using CASE WHEN's. If impossible, I'd be happy with any solution :)


问:
How do I create a console application which manipulates text in system.out?
For example, instead of printing

```<code>/
-
\
/
</code>```

on a new line make it so it stays on one line and is an animation of a spinner?

答:
Yes, print a \b (backspace) to remove the last character. In a nutshell:

```<code>System.out.print('/');
System.out.print('\b');
System.out.print('-');
System.out.print('\b');
System.out.print('\\');
System.out.print('\b');
</code>```

Note that this doesn't work in Eclipse console due to a bug. In the command console, however, it should work fine.

Body:
For example, instead of printing

/
-
\
/

on a new line make it so it stays on one line and is an animation of a spinner?

Body:
Yes, print a \b (backspace) to remove the last character. In a nutshell:

System.out.print('/');
System.out.print('\b');
System.out.print('-');
System.out.print('\b');
System.out.print('\\');
System.out.print('\b');

Note that this doesn't work in Eclipse console due to a bug. In the command console, however, it should work fine.


问:
Stack Overflow with recursion in Java
I'm trying to write an AI that never loses at Tic Tac Toe, and I want to use the minimax algorithm to do so. However, when I try to run the program, a stack overflow appears and I can't seem to find what is the error. Could you take a look and tell me what I'm doing wrong? It doesn't go as deep in the recursion I believe, since it should only go through all the possible game outcomes, which go up to 8 moves (since the player is first to play, not the AI). It is probably me doing something wrong, but I can't find anything.

EDIT: Here's the full code, the mechanics function is the main part:
EDIT2: Fixed the constructor

```<code>package Packet;
import java.util.*;
import java.util.Scanner;

public class Logic {

public static class TicTacToe{

    private int[] currentBoard = new int[9];
    private int[] availableSpots = new int [9];

    private int emptySpace = 0;
    private int playerAI = 1;
    private int playerHuman = 2;

    void TicTacToe(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }

    private int movesNumber(){
        int counter = 0;
        for (int i = 0; i < 9; i++){
            if (this.currentBoard[i] == this.emptySpace){
                counter++;
            }
        }
        return counter;
    }

    private boolean win(int[] board,int player){
        if (
        (board[0] == player && board[1] == player && board[2] == player) ||
        (board[3] == player && board[4] == player && board[5] == player) ||
        (board[6] == player && board[7] == player && board[8] == player) ||
        (board[0] == player && board[3] == player && board[6] == player) ||
        (board[1] == player && board[4] == player && board[7] == player) ||
        (board[2] == player && board[5] == player && board[8] == player) ||
        (board[0] == player && board[4] == player && board[8] == player) ||
        (board[2] == player && board[4] == player && board[6] == player) ){
            return true;
        }
        else{
            return false;
        }
    }

    private int mechanics(int[] newBoard, int player){
        if (win(newBoard,this.playerHuman)){
            return -10;
        }
        else if (win(newBoard, this.playerAI)){
            return +10;
        }
        else if (this.movesNumber() == 0){
            return 0;
        }

        ArrayList<Integer> moves = new ArrayList<Integer>();
        ArrayList<Integer> scores = new ArrayList<Integer>();

        for (int i = 0; i < this.movesNumber(); i++){
            int[] possibleBoard = new int[9];
            possibleBoard = newBoard;

            int availableSpotNumber = i;

            int j = i;

            while (this.availableSpots[j] == 9){
                availableSpotNumber++;
                j++;
            }

            possibleBoard[availableSpotNumber] = player;

            if (player == this.playerAI){
                scores.add(this.mechanics(possibleBoard, this.playerHuman));
            }
            else{
                scores.add(this.mechanics(possibleBoard, this.playerAI));
            }
            moves.add(availableSpotNumber);

            possibleBoard[availableSpotNumber] = this.emptySpace;
        }

        int bestMove = 0;

        if (player == this.playerAI){
            int bestScore = -10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) > bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        else {
            int bestScore = 10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) < bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        return moves.get(bestMove);
    }

    public void printTable(){
        System.out.println(this.currentBoard[0] + " | " + this.currentBoard[1] + " | " + this.currentBoard[2]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[3] + " | " + this.currentBoard[4] + " | " + this.currentBoard[5]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[6] + " | " + this.currentBoard[7] + " | " + this.currentBoard[8]);
        System.out.println();
    }

    private void fillTable(int position,int player){
        this.currentBoard[position] = player;
        this.availableSpots[position] = 9;
    }

    public void startGame(){
        while(true){
            this.printTable();
            Scanner ulaz = new Scanner(System.in);
            fillTable(ulaz.nextInt(), this.playerHuman);
            this.printTable();
            fillTable(this.mechanics(this.currentBoard, this.playerAI), this.playerAI);
            ulaz.close();
        }
    }

    public void resetGame(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }
}

public static void main(String[] args){
    TicTacToe game = new TicTacToe();
    game.startGame();
}
}
</code>```

Also, here's the exact errors I get:

```<code>Exception in thread "main" java.lang.StackOverflowError
    at Packet.Logic$TicTacToe.mechanics(Logic.java:54)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
</code>```

After this part, these parts appear a bunch of times (at least 50)

```<code>at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
</code>```

Line 54:

```<code>if (win(newBoard,this.playerHuman)){
</code>```

Line 84:

```<code>scores.add(this.mechanics(possibleBoard, this.playerHuman));
</code>```

Line 87:

```<code>scores.add(this.mechanics(possibleBoard, this.playerAI));
</code>```

答:
There's a couple of problems, but here's how you can debug this:

add a StringBuilder debug = new StringBuilder(); field to your class, then change the main loop like this:

```<code>int debugLen = debug.length();
debug.append("\nSetting ").append(availableSpotNumber).append(" to ").append(player);
possibleBoard[availableSpotNumber] = player;

try {
    if (player == this.playerAI) {
        scores.add(this.mechanics(possibleBoard, this.playerHuman));
    } else {
        scores.add(this.mechanics(possibleBoard, this.playerAI));
    }
    moves.add(availableSpotNumber);
} catch (StackOverflowError error) {
     throw new StackOverflowError(debug.toString());
}

debug.setLength(debugLen);
possibleBoard[availableSpotNumber] = this.emptySpace;
</code>```

Then you will see what is happening, which will give you a clue what to fix next. For example, the current version is doing this, for initial human move 1:

```<code>Setting 0 to 1
Setting 0 to 2
Setting 0 to 1
Setting 0 to 2
etc..
</code>```

But, if you're too lazy, you can find a fixed version here.

Title: Stack Overflow with recursion in Java

Body:
I'm trying to write an AI that never loses at Tic Tac Toe, and I want to use the minimax algorithm to do so. However, when I try to run the program, a stack overflow appears and I can't seem to find what is the error. Could you take a look and tell me what I'm doing wrong? It doesn't go as deep in the recursion I believe, since it should only go through all the possible game outcomes, which go up to 8 moves (since the player is first to play, not the AI). It is probably me doing something wrong, but I can't find anything.

EDIT: Here's the full code, the mechanics function is the main part:
EDIT2: Fixed the constructor

package Packet;
import java.util.*;
import java.util.Scanner;

public class Logic {

public static class TicTacToe{

    private int[] currentBoard = new int[9];
    private int[] availableSpots = new int [9];

    private int emptySpace = 0;
    private int playerAI = 1;
    private int playerHuman = 2;

    void TicTacToe(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }

    private int movesNumber(){
        int counter = 0;
        for (int i = 0; i < 9; i++){
            if (this.currentBoard[i] == this.emptySpace){
                counter++;
            }
        }
        return counter;
    }

    private boolean win(int[] board,int player){
        if (
        (board[0] == player && board[1] == player && board[2] == player) ||
        (board[3] == player && board[4] == player && board[5] == player) ||
        (board[6] == player && board[7] == player && board[8] == player) ||
        (board[0] == player && board[3] == player && board[6] == player) ||
        (board[1] == player && board[4] == player && board[7] == player) ||
        (board[2] == player && board[5] == player && board[8] == player) ||
        (board[0] == player && board[4] == player && board[8] == player) ||
        (board[2] == player && board[4] == player && board[6] == player) ){
            return true;
        }
        else{
            return false;
        }
    }

    private int mechanics(int[] newBoard, int player){
        if (win(newBoard,this.playerHuman)){
            return -10;
        }
        else if (win(newBoard, this.playerAI)){
            return +10;
        }
        else if (this.movesNumber() == 0){
            return 0;
        }

        ArrayList<Integer> moves = new ArrayList<Integer>();
        ArrayList<Integer> scores = new ArrayList<Integer>();

        for (int i = 0; i < this.movesNumber(); i++){
            int[] possibleBoard = new int[9];
            possibleBoard = newBoard;

            int availableSpotNumber = i;

            int j = i;

            while (this.availableSpots[j] == 9){
                availableSpotNumber++;
                j++;
            }

            possibleBoard[availableSpotNumber] = player;

            if (player == this.playerAI){
                scores.add(this.mechanics(possibleBoard, this.playerHuman));
            }
            else{
                scores.add(this.mechanics(possibleBoard, this.playerAI));
            }
            moves.add(availableSpotNumber);

            possibleBoard[availableSpotNumber] = this.emptySpace;
        }

        int bestMove = 0;

        if (player == this.playerAI){
            int bestScore = -10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) > bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        else {
            int bestScore = 10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) < bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        return moves.get(bestMove);
    }

    public void printTable(){
        System.out.println(this.currentBoard[0] + " | " + this.currentBoard[1] + " | " + this.currentBoard[2]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[3] + " | " + this.currentBoard[4] + " | " + this.currentBoard[5]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[6] + " | " + this.currentBoard[7] + " | " + this.currentBoard[8]);
        System.out.println();
    }

    private void fillTable(int position,int player){
        this.currentBoard[position] = player;
        this.availableSpots[position] = 9;
    }

    public void startGame(){
        while(true){
            this.printTable();
            Scanner ulaz = new Scanner(System.in);
            fillTable(ulaz.nextInt(), this.playerHuman);
            this.printTable();
            fillTable(this.mechanics(this.currentBoard, this.playerAI), this.playerAI);
            ulaz.close();
        }
    }

    public void resetGame(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }
}

public static void main(String[] args){
    TicTacToe game = new TicTacToe();
    game.startGame();
}
}

Also, here's the exact errors I get:

Exception in thread "main" java.lang.StackOverflowError
    at Packet.Logic$TicTacToe.mechanics(Logic.java:54)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)

After this part, these parts appear a bunch of times (at least 50)

at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
at Packet.Logic$TicTacToe.mechanics(Logic.java:87)

Line 54:

if (win(newBoard,this.playerHuman)){

Line 84:

scores.add(this.mechanics(possibleBoard, this.playerHuman));

Line 87:

scores.add(this.mechanics(possibleBoard, this.playerAI));

Body:
There's a couple of problems, but here's how you can debug this:

add a StringBuilder debug = new StringBuilder(); field to your class, then change the main loop like this:

int debugLen = debug.length();
debug.append("\nSetting ").append(availableSpotNumber).append(" to ").append(player);
possibleBoard[availableSpotNumber] = player;

try {
    if (player == this.playerAI) {
        scores.add(this.mechanics(possibleBoard, this.playerHuman));
    } else {
        scores.add(this.mechanics(possibleBoard, this.playerAI));
    }
    moves.add(availableSpotNumber);
} catch (StackOverflowError error) {
     throw new StackOverflowError(debug.toString());
}

debug.setLength(debugLen);
possibleBoard[availableSpotNumber] = this.emptySpace;

Then you will see what is happening, which will give you a clue what to fix next. For example, the current version is doing this, for initial human move 1:

Setting 0 to 1
Setting 0 to 2
Setting 0 to 1
Setting 0 to 2
etc..

But, if you're too lazy, you can find a fixed version here.


问:
How to upload a mapping file to Firebase Crashlytics?
In the old Crash reporting - there is easy way to upload. i didn't find it in the Crashlytics section</p>

答: Mike from Firebase here. Crashlytics in Firebase does not offer a way to upload mapping files outside of the build flow. I'm personally curious, did you use the manual upload frequently?</p>


问:
how to debug puppeteer in headless mode
Does anyone knows how can i debug puppeteer while it runs headless?
I have this E2E Jasmine test which runs fine under non headless mode , but as soon as i run headless , it fails. i'm trying to understand why it fails under headless mode (i'm suspecting it is related to a react render stuff)  , but in order to get some common sense , i must use a debugger.
P.S the documentation implies i should run non headless in order to see whats going on , but thats not helping in my case :/
Thanks in advance!</p>

答:
You can debug it easily with DEBUG.

Example command to run,

```<code>DEBUG=* node app.js
</code>```

Title: how to debug puppeteer in headless mode

Body:
You can debug it easily with DEBUG.

Example command to run,

DEBUG=* node app.js


问:
About 2's complement for natural numbers to binary
I know how to convert a number into binary with 2's complement but I am still confused on the notion of it.

Do we use 2's complement only when we are converting negative numbers into binary?

Any help would be great! thanks

答:
Two's complement notation for negative numbers really depends on a fixed-length encoding to be well-defined. Why? It requires that leading zeroes be semantically relevant. Variable-length encodings (like in mathematics generally) ignore leading zeroes: 0101 and 101 are the same number. However, in two's complement, one of these numbers is positive (0101 = 5 in a 4-bit two's complement notation) and the other negative (101 = -3 in a 3-bit two's complement notation). So you really must specify the container size for two's complement to be meaningful.

Now that this is out of the way, the answer to your question becomes clearer. Any given string of bits of length k is a number in a k-bit two's complement notation. The number is positive if and only if the most significant bit is zero. Any given "positive" number you have is only positive with respect to any given two's complement notation if it doesn't require the kth bit be set, where k is the number of bits in your notation. For example, in a 4-bit two's complement notation, the "positive" number 8 ( = 1000) cannot be represented and, if you tried to do it anyway, the number would be interpreted as -8 ( = 1000). The representable range would be [-8, 7] = [1000, 0111].


问:
Invoking python under CygWin on Windows hangs
Installing a new Windows system, I've installed CygWin and 64
bit Python (2.7.3) in their default locations (c:\cygwin and
c:\Python27\python), and added both the CygWin bin and the
Python directory to my path (in the user variable PATH).  From
the normal command window, Python starts up perfectly, but when
I invoke it from bash in the CygWin environment, it hangs,
never giving my the input prompt.

I've done this on other machines, previously, but always with
older versions of Python (32 bits) and CygWin, and with Python
in a decidely non-standard location.  Has anyone else had this
problem, or could someone tell me what it might be due to?

答: another universal workaround is invoking it via winpty https://github.com/rprichard/winpty and this is not really a python specific issue.


问:
How to get twitter bootstrap modal working in node js express js?
This is my index.jade file

```
.navbar.navbar-fixed-top
    .navbar-inner
        .container
            .brand #{title}

    .container
        .row
            .hero-unit
                h1 #{title}
                p Cricket fantasy game where you can be selector.
                a.btn(data-toggle="modal", href="#myModal") Launch

div.modal.hide(id="myModal")
    .modal-header
        button(type="button", class="close", data-dismiss="modal") x
        h3 Modal Header
    .modal-body
        p One fine body...
    .modal-footer
```

This is my layout.jade file

```
!!!
html
    head
        title= title
        link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap.css')
        link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap.min.css')
        link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap-responsive.min.css')
        link(rel='stylesheet', href='/stylesheets/style.css')
    body!= body
script(src="/libs/bootstrap/js/bootstrap.js")```

I have other bootstrap elements working but cannot follow the following instructions - "You can activate modals on your page easily without having to write a single line of javascript. Just set data-toggle="modal" on a controller element with a data-target="#foo" or href="#foo" which corresponds to a modal element id, and when clicked, it will launch your modal."

How can i do that ?

答:
add jQuery before the bootstrap:</p>

```<code>script(src="https://code.jquery.com/jquery-3.2.1.min.js")
</code>```

Body:
This is my index.jade file

.navbar.navbar-fixed-top
    .navbar-inner
        .container
            .brand #{title}

    .container
        .row
            .hero-unit
                h1 #{title}
                p Cricket fantasy game where you can be selector.
                a.btn(data-toggle="modal", href="#myModal") Launch

div.modal.hide(id="myModal")
    .modal-header
        button(type="button", class="close", data-dismiss="modal") x
        h3 Modal Header
    .modal-body
        p One fine body...
    .modal-footer

This is my layout.jade file

!!!
html
    head
        title= title
        link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap.css')
        link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap.min.css')
        link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap-responsive.min.css')
        link(rel='stylesheet', href='/stylesheets/style.css')
    body!= body
script(src="/libs/bootstrap/js/bootstrap.js")

I have other bootstrap elements working but cannot follow the following instructions - "You can activate modals on your page easily without having to write a single line of javascript. Just set data-toggle="modal" on a controller element with a data-target="#foo" or href="#foo" which corresponds to a modal element id, and when clicked, it will launch your modal."

How can i do that ?

Body:
add jQuery before the bootstrap:

script(src="https://code.jquery.com/jquery-3.2.1.min.js")


问:
IE7 CSS Compatibility
Let me start off by saying I'm not a web developer and I don't know much at all about comparability.

I've been asked if I can fix a problem with a website in IE7. It loads completely fine in all modern browsers, but they want to make sure it works perfectly in IE7 as well. It technically works fine, but it appears to load the initial content on one pass and then the style on a second pass. I guess I can't be positive if this is what it's doing.

Does anyone who has experience with browser compatibility have any idea if this can be remedied? The website is extremely basic, just HTML, CSS, and a little bit of JS.

If this is the case, is there an easy way to set everything to invisible until the page is done loading? I know you can do this with javascript and individual elements.

答:
Looks like my comment may have gone unnoticed so I'll throw this down here. This sounds like a Flash of Unstyled Content - a sometimes common occurrence in IE. Check out this site for more information:

bluerobot.com/web/css/fouc.asp

Title: IE7 CSS Compatibility


问:
Adding Overlays to Videos export as a video in android
So i have a video for eg. a race car video and i created a overlay view (transparent relative layout) which includes some progress bar related to speed and performance now i need to export full video as seen in this view so can anyone please help me i have gone through ffmpeg,opencv but no success.

Similar Ios Overlay

答:
For decoding video to bitmap and encoding bitmap back to mp4 video you can use jcodec.

```<code>SequenceEncoder sequenceEncoder = new SequenceEncoder(new File(pathToSaveVideo));
</code>```

Perform these steps in a loop

Extract bitmaps of each frame of video

Combine with overlay bitmap

```<code> Canvas canvas = new Canvas(backgroundBitmap);
 Paint rectpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
 int width = overlayBitmap.getWidth();
 int height = overlayBitmap.getHeight();
 Rect des = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
 Rect src = new Rect(0, 0, width, height);
 canvas.drawBitmap(overlayBitmap, src, des, rectpaint);
</code>```

Encode it back into a video

```<code>sequenceEncoder.encodeImage(backgroundBitmap);
</code>```

Finally finish the encoder after loop

sequenceEncoder.finish()

Body:
For decoding video to bitmap and encoding bitmap back to mp4 video you can use jcodec.

SequenceEncoder sequenceEncoder = new SequenceEncoder(new File(pathToSaveVideo));

Perform these steps in a loop

Extract bitmaps of each frame of video

Combine with overlay bitmap

 Canvas canvas = new Canvas(backgroundBitmap);
 Paint rectpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
 int width = overlayBitmap.getWidth();
 int height = overlayBitmap.getHeight();
 Rect des = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
 Rect src = new Rect(0, 0, width, height);
 canvas.drawBitmap(overlayBitmap, src, des, rectpaint);

Encode it back into a video

sequenceEncoder.encodeImage(backgroundBitmap);

Finally finish the encoder after loop

sequenceEncoder.finish()


问:
Margin below <TextView/> in <ConstraintLayout/> not working
There is a simple layout with TextView and RecyclerView inside a ConstraintLayout.

```<code>    <android.support.constraint.ConstraintLayout
        android:id="@+id/clSelectedPatient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvSelectPatient"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lifcare"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_marginBottom="100dp"
            app:layout_constraintBottom_toTopOf="@+id/rvPatients"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvPatients"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            app:layout_constraintTop_toBottomOf="@+id/tvSelectPatient"/>

    </android.support.constraint.ConstraintLayout>
</code>```

android:layout_marginBottom="100dp" below TextView is not working.

答:
There are a few mistakes in your layout:

You use match_parent for width and using match_parent is prohibited for ConstraintLayout subviews.

Build a Responsive UI with ConstraintLayout - Adjust the view size

Note: You cannot use match_parent for any view in a ConstraintLayout.
  Instead use "match constraints" (0dp)

In order to display vertical margins properly, you have to define vertical constraints for TextView and RecyclerView.

Your fixed layout code would look like:

```<code><android.support.constraint.ConstraintLayout
    android:id="@+id/clSelectedPatient"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvSelectPatient"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="100dp"
        android:text="Lifcare"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/rvPatients" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvPatients"
        android:layout_width="0dp"
        android:layout_height="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvSelectPatient"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

And this is how it looks on device:

Body:
There is a simple layout with TextView and RecyclerView inside a ConstraintLayout.

    <android.support.constraint.ConstraintLayout
        android:id="@+id/clSelectedPatient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvSelectPatient"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lifcare"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_marginBottom="100dp"
            app:layout_constraintBottom_toTopOf="@+id/rvPatients"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvPatients"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            app:layout_constraintTop_toBottomOf="@+id/tvSelectPatient"/>

    </android.support.constraint.ConstraintLayout>

android:layout_marginBottom="100dp" below TextView is not working.

Body:
There are a few mistakes in your layout:

You use match_parent for width and using match_parent is prohibited for ConstraintLayout subviews.

Build a Responsive UI with ConstraintLayout - Adjust the view size

Note: You cannot use match_parent for any view in a ConstraintLayout.
  Instead use "match constraints" (0dp)

In order to display vertical margins properly, you have to define vertical constraints for TextView and RecyclerView.

Your fixed layout code would look like:

<android.support.constraint.ConstraintLayout
    android:id="@+id/clSelectedPatient"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvSelectPatient"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="100dp"
        android:text="Lifcare"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/rvPatients" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvPatients"
        android:layout_width="0dp"
        android:layout_height="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvSelectPatient"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

</android.support.constraint.ConstraintLayout>

And this is how it looks on device:


问:
Empty circle - only point strok in line chart for ChartJS
How can I acheive this kind of point in a chartJS line chart?

答:
Here is an example to get the point style you are after:

documentation for point options for line chart can be found here

A codePen of the below code here

HTML:

```<code><html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"></canvas>
    </div>
  </body>
</html>
</code>```

JS:

```<code>new Chart(document.getElementById("myChart"), {
  type: "line",
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [
      {
        label: "My First Dataset",
        data: [20, 25, 22, 19, 31, 40],
        fill: true,
        borderColor: "rgb(75, 192, 192)",
        backgroundColor: "rgba(0,0,0,0.1)",
        borderWidth: 2,
        lineTension: 0,
        /* point options */
        pointBorderColor: "blue", // blue point border
        pointBackgroundColor: "white", // wite point fill
        pointBorderWidth: 1, // point border width
      }
    ]
  },
  options: {
    legend: {
      labels: {
        usePointStyle: true, // show legend as point instead of box
        fontSize: 10 // legend point size is based on fontsize
      }
    }
  }
});
</code>```

Body:
Here is an example to get the point style you are after:

documentation for point options for line chart can be found here

A codePen of the below code here

HTML:

<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"></canvas>
    </div>
  </body>
</html>

JS:

new Chart(document.getElementById("myChart"), {
  type: "line",
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [
      {
        label: "My First Dataset",
        data: [20, 25, 22, 19, 31, 40],
        fill: true,
        borderColor: "rgb(75, 192, 192)",
        backgroundColor: "rgba(0,0,0,0.1)",
        borderWidth: 2,
        lineTension: 0,
        /* point options */
        pointBorderColor: "blue", // blue point border
        pointBackgroundColor: "white", // wite point fill
        pointBorderWidth: 1, // point border width
      }
    ]
  },
  options: {
    legend: {
      labels: {
        usePointStyle: true, // show legend as point instead of box
        fontSize: 10 // legend point size is based on fontsize
      }
    }
  }
});