问:
How to import javascript export file generated from the webpack.config?

Problem description

I need to set the DEV or Production environment so I can test API's either locally or get them ready for production.

ie: Either use http://localhost/api/app/login or /api/app/login

Now I was able to accomplish this by attaching NODE_ENV variables to my npm scripts in the package.json and a couple of lines of code in my webpack.config as so:

```<code>"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",
</code>```

webpack.config

```<code>const environment = process.env.NODE_ENV;
....
new CopyWebpackPlugin([{ from: "static" }])
</code>```

^ that will create an env I can use in my services/api.js file. Now my Problem is that my Jest tests will fail every time because env is undefined.

Attempted solution - need help

So now instead what I'm trying to do is use node to actually generate a Javascript file that I can actually import directly into my services/api.js that way I avoid the undefined env error in testing.

I'm able to create a Javascript file with the following updates to my webpack.config

```<code>const fs = require('fs');
const webpack = require('webpack')
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/consts/endpoints.js");
stream.once('open', function(fd) {
  stream.write('export const environment = () => "'+environment+'"');
  stream.end();
});
</code>```

The file it created (src/consts/endpoints.js):

```<code>export const environment = () => "development"
</code>```

I've also tried this way:

```<code>export const environment = "development"
</code>```

Now my updated services/api.js

```<code>import axios from 'axios'
import environment from '../consts/endpoints'
console.log('api.js environment:', environment);
</code>```

However environment is undefined when I check out localhost.

How can I fix this problem? Is it a race condition? Is there another way to generate the file I need to import?

I tried to generate a .txt file however I can't import that file locally, can only do it in the cloud.

Full webpack.config file

```<code>const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('export const environment = "'+environment+'"');
  stream.end();
});

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: '/static/',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static" }])
  ]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })
</code>```

答:
Figured it out!

I was importing the file incorrectly.

So from webpack.config

```<code>const environment = process.env.NODE_ENV;

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('const env = "'+environment+'"\n');
  stream.write('export default env');
  stream.end();
});
</code>```

^ That generates this file (src/services/environment.js) which contains:

```<code>const env = "development"
export default env
</code>```

Finally in my services/api.js file I can use the import statement the way I wanted, I was missing the export default from above.

```<code>import axios from 'axios'
import endpoints from './endpoints'
import env from './environment'

const api = endpoints(env);
console.log('api', api);

const log = (method, err) => {
    console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
    return err;
};

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post(api.login, post_data)
        .then(res => res)
        .catch((err) => log('api.userLogin', err));
};
</code>```

And in my package.json I can change the ENV var to spit out "development" or "production".

```<code>"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",
</code>```

Body:
Problem description

I need to set the DEV or Production environment so I can test API's either locally or get them ready for production.

ie: Either use http://localhost/api/app/login or /api/app/login

Now I was able to accomplish this by attaching NODE_ENV variables to my npm scripts in the package.json and a couple of lines of code in my webpack.config as so:

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",

webpack.config

const environment = process.env.NODE_ENV;
....
new CopyWebpackPlugin([{ from: "static" }])

^ that will create an env I can use in my services/api.js file. Now my Problem is that my Jest tests will fail every time because env is undefined.

Attempted solution - need help

So now instead what I'm trying to do is use node to actually generate a Javascript file that I can actually import directly into my services/api.js that way I avoid the undefined env error in testing.

I'm able to create a Javascript file with the following updates to my webpack.config

const fs = require('fs');
const webpack = require('webpack')
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/consts/endpoints.js");
stream.once('open', function(fd) {
  stream.write('export const environment = () => "'+environment+'"');
  stream.end();
});

The file it created (src/consts/endpoints.js):

export const environment = () => "development"

I've also tried this way:

export const environment = "development"

Now my updated services/api.js

import axios from 'axios'
import environment from '../consts/endpoints'
console.log('api.js environment:', environment);

However environment is undefined when I check out localhost.

How can I fix this problem? Is it a race condition? Is there another way to generate the file I need to import?

I tried to generate a .txt file however I can't import that file locally, can only do it in the cloud.

Full webpack.config file

const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;

// fs.writeFileSync('src/consts/env.txt', environment);

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('export const environment = "'+environment+'"');
  stream.end();
});

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: '/static/',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static" }])
  ]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })

Body:
Figured it out!

I was importing the file incorrectly.

So from webpack.config

const environment = process.env.NODE_ENV;

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('const env = "'+environment+'"\n');
  stream.write('export default env');
  stream.end();
});

^ That generates this file (src/services/environment.js) which contains:

const env = "development"
export default env

Finally in my services/api.js file I can use the import statement the way I wanted, I was missing the export default from above.

import axios from 'axios'
import endpoints from './endpoints'
import env from './environment'

const api = endpoints(env);
console.log('api', api);

const log = (method, err) => {
    console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
    return err;
};

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post(api.login, post_data)
        .then(res => res)
        .catch((err) => log('api.userLogin', err));
};

And in my package.json I can change the ENV var to spit out "development" or "production".

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",


来源: stackexchange

答:
```<code>df['is_digit'] = [i[-1].isdigit() for i in df.index.values]
df[df['is_digit'] == False]
</code>```

But I like regex better:

```<code>df[df.index.str.contains('[A-z]$')]
</code>```

ContentLicense: CC BY-SA 3.0

Title: filter df based on index condition

Body:
I have a df with lots of rows:

13790226       0.320  0.001976
9895d5dis    182.600  0.040450
105066007     18.890  0.006432
109067019     52.500  0.034011
111845014     16.400  0.023974
11668574e      7.180  0.070714
113307021      4.110  0.017514
113679I37      8.180  0.010837

I would like to filter this df in order to obtain the rows where the index last char is not a digit

Desired df:

9895d5dis    182.600  0.040450
11668574e      7.180  0.070714

How can I do it?

Body:
df['is_digit'] = [i[-1].isdigit() for i in df.index.values]
df[df['is_digit'] == False]

But I like regex better:

df[df.index.str.contains('[A-z]$')]


问:
Export a GridView to Excel
I'm trying to export a GridView into a xls file, I insert the GridView into a Modal and I'm supposing that because of that it can't be exported.

This is my BackEnd of the action from the Button:

```<code>protected void Btn_download_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AppendHeader("content-disposition", "attachment; flename=MainReport.xls");
            Response.ContentType = "application/excel";

            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

            Grv_main.RenderControl(htmlTextWriter);
            Response.Write(stringWriter.ToString());
            Response.End();
        }
</code>```

and this is the HTML:

```<code><form id="form1" runat="server">

        <div class="container">
            <div class="modal fade" id="History-Maint" role="dialog">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header" style="padding: 35px 50px;">
                            <button type="button" class="close" data-dismiss="modal">×</button>
                            <h3><span class="glyphicon glyphicon-list-alt"></span>&nbsp Maintenance Report</h3>
                        </div>
                        <div class="modal-body">
                            <asp:GridView ID="Grv_main"
                                CssClass="table table-striped table-bordered table-hover"
                                runat="server"
                                AutoGenerateColumns="False"
                                Width="940px"
                                HorizontalAlign="Center"
                                DataKeyNames="id"
                                AllowPaging="True" OnRowEditing="GridView1_RowEditing">
                                <Columns>
                                    <asp:TemplateField HeaderText="id" Visible="false">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_id" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="status">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_stats" runat="server" Text='<%# Bind("STATUS") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="tool">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_tool" runat="server" Text='<%# Bind("TOOL") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Area Change">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_areach" runat="server" Text='<%# Bind("AREA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="responsable">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_resp" runat="server" Text='<%# Bind("RESPONSABLE") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="nota">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_note" runat="server" Text='<%# Bind("NOTA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="fecha de modificacion">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_mod" runat="server" Text='<%# Bind("MODIFY") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </div>
                        <div class="modal-footer">
                            <asp:Button ID="Btn_download" runat="server" CssClass="btn btn-success" Text='Guardar' OnClick="Btn_download_Click" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
        </asp:ContentPlaceHolder>
    </form>
</code>```

all of this, is on a MasterPage and into a form with the runat="server"

答:
```<code>private void ExportGridToExcel()  {
        Response.Clear();

        //You had a typo on the line below in your code for (filename)

        Response.AddHeader("content-disposition", "attachment;filename=MainReport.xls");
        Response.ContentType = "File/Data.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
        GridEmpData.RenderControl(HtmlTextWriter);
        Response.Write(StringWriter.ToString());
        Response.End();
    }
</code>```

Made reference to this website http://www.c-sharpcorner.com/UploadFile/b926a6/gridview-data-export-into-excel-file-format/

Maybe take a look? There is databases there although the answer on how to convert a gridview to an Excel file is there and the code is above.

Title: Export a GridView to Excel

Body:
I'm trying to export a GridView into a xls file, I insert the GridView into a Modal and I'm supposing that because of that it can't be exported.

This is my BackEnd of the action from the Button:

protected void Btn_download_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AppendHeader("content-disposition", "attachment; flename=MainReport.xls");
            Response.ContentType = "application/excel";

            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

            Grv_main.RenderControl(htmlTextWriter);
            Response.Write(stringWriter.ToString());
            Response.End();
        }

and this is the HTML:

<form id="form1" runat="server">

                            <button type="button" class="close" data-dismiss="modal">×</button>

&nbsp Maintenance Report

                            <asp:GridView ID="Grv_main"
                                CssClass="table table-striped table-bordered table-hover"
                                runat="server"
                                AutoGenerateColumns="False"
                                Width="940px"
                                HorizontalAlign="Center"
                                DataKeyNames="id"
                                AllowPaging="True" OnRowEditing="GridView1_RowEditing">
                                <Columns>
                                    <asp:TemplateField HeaderText="id" Visible="false">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_id" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="status">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_stats" runat="server" Text='<%# Bind("STATUS") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="tool">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_tool" runat="server" Text='<%# Bind("TOOL") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Area Change">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_areach" runat="server" Text='<%# Bind("AREA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="responsable">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_resp" runat="server" Text='<%# Bind("RESPONSABLE") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="nota">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_note" runat="server" Text='<%# Bind("NOTA") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="fecha de modificacion">
                                        <ItemTemplate>
                                            <asp:Label ID="Lbl_mod" runat="server" Text='<%# Bind("MODIFY") %>'></asp:Label>
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Center" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>

                            <asp:Button ID="Btn_download" runat="server" CssClass="btn btn-success" Text='Guardar' OnClick="Btn_download_Click" />

        <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
        </asp:ContentPlaceHolder>
    </form>

all of this, is on a MasterPage and into a form with the runat="server"

Body:
private void ExportGridToExcel()  {
        Response.Clear();

        //You had a typo on the line below in your code for (filename)

        Response.AddHeader("content-disposition", "attachment;filename=MainReport.xls");
        Response.ContentType = "File/Data.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
        GridEmpData.RenderControl(HtmlTextWriter);
        Response.Write(StringWriter.ToString());
        Response.End();
    }

Made reference to this website http://www.c-sharpcorner.com/UploadFile/b926a6/gridview-data-export-into-excel-file-format/

Maybe take a look? There is databases there although the answer on how to convert a gridview to an Excel file is there and the code is above.


问:
Get selected data and fill textboxes
I am trying to make easy-to-use form for the users who are using our internal application. Basicly I have a select element. What I want is when I choose anything I want to fill specified text boxes.

Codes are below. That works fine but fill only 1 box.Pls do not forget normally I am getting data from the mySQL db.

html file:

```<code><script src="choose.js"></script>
<select onchange="ChooseGuest(this.value)">
<option value="1">guest 1</option>
<option value="2">guest 2</option>
<option value="3">guest 3</option>
</select>
<input type="text" id="guestdetails"/>
<input type="text" id="guestdetails2"/>
</code>```

php data file:

```<code>$AskForIt = $_GET["q"];
If ($AskForIt == "1") {
echo "guest 1 data";
} Elseif ($AskForIt == "2") {
echo "guest 2 data";
} Elseif ($AskForIt == "3") {
echo "guest 3 data";
}
</code>```

js file:

```<code>var xmlHttp

function ChooseGuest(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("upgrade your browser");
  return;
  }
var url="guests.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("guestdetails").value=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
</code>```

答:
From what I understand, you are trying to fill the input boxes with data pulled from your DB and have the appropriate data shown depending on which drop down is selected. PHP is server side only. Once the page loads the PHP will only run once and not again until the page is reloaded. So, you'll need to access those vars using JS. This is probably why only the first selection is being filled.

If this is so, you will need to go into your PHP  file and create JS vars that are equal to the data accessed from the DB. Simply set your JS vars equal to a PHP echo of the vars from your php:

PHP Data File

```<code><?php

    var somePHPvar = "DB Value";

?>

<script>

    var someVar = <?php echo somePHPvar; ?>;

</script>
</code>```

If this is all done on the same PHP file, don't forget to include it on the page and call these JS vars. From there you'll be able to fill those values using JS.

Title: Get selected data and fill textboxes

Body:
I am trying to make easy-to-use form for the users who are using our internal application. Basicly I have a select element. What I want is when I choose anything I want to fill specified text boxes.

Codes are below. That works fine but fill only 1 box.Pls do not forget normally I am getting data from the mySQL db.

html file:

<select onchange="ChooseGuest(this.value)">
<option value="1">guest 1</option>
<option value="2">guest 2</option>
<option value="3">guest 3</option>
</select>
<input type="text" id="guestdetails"/>
<input type="text" id="guestdetails2"/>

php data file:

$AskForIt = $_GET["q"];
If ($AskForIt == "1") {
echo "guest 1 data";
} Elseif ($AskForIt == "2") {
echo "guest 2 data";
} Elseif ($AskForIt == "3") {
echo "guest 3 data";
}

js file:

var xmlHttp

function ChooseGuest(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("upgrade your browser");
  return;
  }
var url="guests.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("guestdetails").value=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

Body:
From what I understand, you are trying to fill the input boxes with data pulled from your DB and have the appropriate data shown depending on which drop down is selected. PHP is server side only. Once the page loads the PHP will only run once and not again until the page is reloaded. So, you'll need to access those vars using JS. This is probably why only the first selection is being filled.

If this is so, you will need to go into your PHP  file and create JS vars that are equal to the data accessed from the DB. Simply set your JS vars equal to a PHP echo of the vars from your php:

PHP Data File

<?php

    var somePHPvar = "DB Value";

?>

<script>

    var someVar = <?php echo somePHPvar; ?>;

</script>

If this is all done on the same PHP file, don't forget to include it on the page and call these JS vars. From there you'll be able to fill those values using JS.


问:
open same frame when button click in java
i updated the code because many people doesn't understand so write a simple representation for that.
here is the problem whenever i clicked the button it open a new frame but i dont want this it does't open a new frame it remain open the same frame.

code for main frame :

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JavaProject2_27 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_27 window = new JavaProject2_27();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_27() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnClicked = new JButton("Clicked");
        btnClicked.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JavaProject2_28 obj=new JavaProject2_28();
                obj.getJavaProject2_28();
            }
        });
        btnClicked.setBounds(150, 99, 89, 23);
        frame.getContentPane().add(btnClicked);
    }
}
</code>```

code for the second frame :

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;

public class JavaProject2_28 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_28 window = new JavaProject2_28();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_28() {
        initialize();
    }

    public void getJavaProject2_28()
    {
        frame.setVisible(true);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}
</code>```

snapshot

答:
I was checking your earlier program, still cannot find the implementation of getDataJavaProject2_23(); method in those three classes that you provided.

First of all answer to your question few things to mention:

Use proper naming convention, as a example: JavaProject2_28 this class name didnot make any sense to us or even for you if you look at this after a week or two.

You can divide your program for more classes, as a example: database data handling, GUI and etc.

And another important thing is multiple JFrames for one application is not good because of even if you look at your task bar when running your program you can see there is multiple icons, it is difficult to deal with your application. There is more disadvatages about this. read this to get clear idea. Instead of multiple JFrames you can use one JFrame and multiple JPanel with appropriate layouts.

Answer for your updated question:

whenever i clicked the button it open a new frame but i dont want this
  it does't open a new frame it remain open the same frame.

I checked your program it is work fine(after press the button open up the other frame).

You can do some changes that are unnecessary:

Remove this function

```<code>public void getJavaProject2_28()
{
    frame.setVisible(true);
}
</code>```

And add frame.setVisible(true); to the initialize() method.

Solution:

Add frame.setVisible(true) to button action.
Like below:

```<code>        }
    });
    btnClicked.setBounds(150, 99, 89, 23);
    frame.getContentPane().add(btnClicked);
    frame.setVisible(true);
}
</code>```

And in the main frame(which is button button added) change like below:

```<code>JButton btnClicked = new JButton("Clicked");
btnClicked.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        JavaProject2_28 obj=new JavaProject2_28();
    }
});
</code>```

Also you do not need the main() method in both if you are only open second JFrame in main frame button.

Body:
i updated the code because many people doesn't understand so write a simple representation for that.
here is the problem whenever i clicked the button it open a new frame but i dont want this it does't open a new frame it remain open the same frame.

code for main frame :

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JavaProject2_27 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_27 window = new JavaProject2_27();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_27() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnClicked = new JButton("Clicked");
        btnClicked.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JavaProject2_28 obj=new JavaProject2_28();
                obj.getJavaProject2_28();
            }
        });
        btnClicked.setBounds(150, 99, 89, 23);
        frame.getContentPane().add(btnClicked);
    }
}

code for the second frame :

import java.awt.EventQueue;

import javax.swing.JFrame;

public class JavaProject2_28 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_28 window = new JavaProject2_28();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_28() {
        initialize();
    }

    public void getJavaProject2_28()
    {
        frame.setVisible(true);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

snapshot

Body:
I was checking your earlier program, still cannot find the implementation of getDataJavaProject2_23(); method in those three classes that you provided.

First of all answer to your question few things to mention:

Use proper naming convention, as a example: JavaProject2_28 this class name didnot make any sense to us or even for you if you look at this after a week or two.

You can divide your program for more classes, as a example: database data handling, GUI and etc.

And another important thing is multiple JFrames for one application is not good because of even if you look at your task bar when running your program you can see there is multiple icons, it is difficult to deal with your application. There is more disadvatages about this. read this to get clear idea. Instead of multiple JFrames you can use one JFrame and multiple JPanel with appropriate layouts.

Answer for your updated question:

whenever i clicked the button it open a new frame but i dont want this
  it does't open a new frame it remain open the same frame.

I checked your program it is work fine(after press the button open up the other frame).

You can do some changes that are unnecessary:

Remove this function

public void getJavaProject2_28()
{
    frame.setVisible(true);
}

And add frame.setVisible(true); to the initialize() method.

Solution:

Add frame.setVisible(true) to button action.
Like below:

        }
    });
    btnClicked.setBounds(150, 99, 89, 23);
    frame.getContentPane().add(btnClicked);
    frame.setVisible(true);
}

And in the main frame(which is button button added) change like below:

JButton btnClicked = new JButton("Clicked");
btnClicked.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        JavaProject2_28 obj=new JavaProject2_28();
    }
});

Also you do not need the main() method in both if you are only open second JFrame in main frame button.


问:
Process Accessability
I am trying to write some information into the file, which is located in
ftp, and this file can be updated by number of people, but if at all i
download a file from the ftp to my local machine, update it and then
upload it back to ftp, and at the same time if some one else downloads
the same file for the modification, then the data will be overwritten.

so is there a way in Python script where i can lock the file, so that
no one updates it until i release the lock

答:
It is unclear if you need to know for debugging purposes or to support a feature in the code but this is the method call to get the pid of the current executing process.

```<code>import os

print "Process id:",os.getpid()
</code>```

This will simply dump the id to output and you can put other information of interest there so you can follow which is what.

Is this what you are looking for? If not, please clarify and I'll try again.

ContentLicense: CC BY-SA 2.5

Title: Process Accessability

Body:
It is unclear if you need to know for debugging purposes or to support a feature in the code but this is the method call to get the pid of the current executing process.

import os

print "Process id:",os.getpid()

This will simply dump the id to output and you can put other information of interest there so you can follow which is what.

Is this what you are looking for? If not, please clarify and I'll try again.


问:
Ruby list all files within a UNC path via WinRM
I am attempting to execute a ruby script via WinRM

```<code>ruby "R:\Scripts\testDir.rb"
</code>```

that contains the following code:

```<code>Dir.foreach("\\\\FileServer\\TestDir\\") { |x|
    puts "Found #{x}"
}
</code>```

I have no problems executing the script locally on the server, but it fails with the following Permission Denied error via WinRM:

```<code>ruby : R:/Scripts/testDir.rb:1:in `open': Permission denied @ dir_initialize - \\FileServer\TestDir\ (Errno::EACCES)
    + CategoryInfo          : NotSpecified: (R:/Scripts...(Errno::EACCES):String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

    from R:/Scripts/testDir.rb:1:in `foreach'
    from R:/Scripts/testDir.rb:1:in `<main>'
</code>```

When running the script locally, I get the following output.

```<code>Found .
Found ..
Found test.txt
Found test.tar.xz
</code>```

My guess is that my script is failing because of the . and .. returned values being passed through WinRM, but I am not sure why.

答: The issue I was having was caused by double-hopping. The command I was running to execute the ruby script was from my local machine via WinRm. </p>

Body:
I am attempting to execute a ruby script via WinRM

ruby "R:\Scripts\testDir.rb"

that contains the following code:

Dir.foreach("\\\\FileServer\\TestDir\\") { |x|
    puts "Found #{x}"
}

I have no problems executing the script locally on the server, but it fails with the following Permission Denied error via WinRM:

ruby : R:/Scripts/testDir.rb:1:in `open': Permission denied @ dir_initialize - \\FileServer\TestDir\ (Errno::EACCES)
    + CategoryInfo          : NotSpecified: (R:/Scripts...(Errno::EACCES):String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

    from R:/Scripts/testDir.rb:1:in `foreach'
    from R:/Scripts/testDir.rb:1:in `'

When running the script locally, I get the following output.

Found .
Found ..
Found test.txt
Found test.tar.xz

My guess is that my script is failing because of the . and .. returned values being passed through WinRM, but I am not sure why.


问:
Can't get jQuery CDN to work for WordPress plugin
I'm building my first WordPress plugin and I've run into some trouble. I first created a custom page template with a contact form I created. It used Bootstrap JS, Bootstrap CSS, jQuery, and then jQuery UI for a datepicker. It also used an external stylesheet. Everything worked really well. I'm now turning this page template into a plugin so that I can use it across several websites easily, and to easier pull the theme's default design. I originally added Bootstrap JS, Bootstrap CSS, jQuery, and jQuery UI in the head of the .php file like this:

```<code><head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/chem-dry-contact/style.css" media="screen">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
</code>```

I now understand this isn't the best way to link to external stylesheets and scripts for WordPress, and especially not for a plugin. But it did work before.

I was able to get all my html to show up as a plugin with a shortcode and everything, but it doesn't look like all of the external files are working. Here's how I set it up with WordPress's enqueue function:

```<code>function add_plugin_scripts() {
  wp_enqueue_script( 'jquery-3.2.1', '/wp-content/plugins/ChemDry-PriceQuote/jquery-3.2.1.js', array(), null, true);
  wp_enqueue_script('bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array(), null, true);
}
add_action( 'wp_enqueue_scripts', 'add_plugin_scripts' );

function add_plugin_styles () {
    wp_enqueue_style('style', '/wp-content/plugins/ChemDry-PriceQuote/style.css');
    wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
}
add_action( 'wp_enqueue_scripts', 'add_plugin_styles' );
</code>```

My external CSS is working, and I think my Bootstrap CSS is working, but I don't think jquery and Bootstrap JS are working. The functionality it provided when I had it set up as a page template is no longer working, and when I tested it out by commenting out the jQuery line in my page template version, I got the exact same result as I'm getting now. I did already try to deregister jquery first and then try to reregister it...but that didn't work either.

Now I've read that WordPress comes with jQuery...but if I don't add it, I don't get the functionality I need. I've looked all over Stack Overflow for an answer but I can't quite seem to get this to work.

Again, this is my first plugin I've developed so I'd appreciate any help. Thank you.

答:
Wordpress come with jquery and you should use JQuery keyword instead of $ at beginning of your statements.

You can check Following links aswell :

jquery is not defined in wordpress

not defined using JQuery

also You can Take look at following link for make $ work again:

Using ‘$’ instead of ‘jQuery’ in WordPress

Body:
I'm building my first WordPress plugin and I've run into some trouble. I first created a custom page template with a contact form I created. It used Bootstrap JS, Bootstrap CSS, jQuery, and then jQuery UI for a datepicker. It also used an external stylesheet. Everything worked really well. I'm now turning this page template into a plugin so that I can use it across several websites easily, and to easier pull the theme's default design. I originally added Bootstrap JS, Bootstrap CSS, jQuery, and jQuery UI in the head of the .php file like this:

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

    <link rel="stylesheet" type="text/css" href="/chem-dry-contact/style.css" media="screen">

    <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

I now understand this isn't the best way to link to external stylesheets and scripts for WordPress, and especially not for a plugin. But it did work before.

I was able to get all my html to show up as a plugin with a shortcode and everything, but it doesn't look like all of the external files are working. Here's how I set it up with WordPress's enqueue function:

function add_plugin_scripts() {
  wp_enqueue_script( 'jquery-3.2.1', '/wp-content/plugins/ChemDry-PriceQuote/jquery-3.2.1.js', array(), null, true);
  wp_enqueue_script('bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array(), null, true);
}
add_action( 'wp_enqueue_scripts', 'add_plugin_scripts' );

function add_plugin_styles () {
    wp_enqueue_style('style', '/wp-content/plugins/ChemDry-PriceQuote/style.css');
    wp_enqueue_style('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
}
add_action( 'wp_enqueue_scripts', 'add_plugin_styles' );

My external CSS is working, and I think my Bootstrap CSS is working, but I don't think jquery and Bootstrap JS are working. The functionality it provided when I had it set up as a page template is no longer working, and when I tested it out by commenting out the jQuery line in my page template version, I got the exact same result as I'm getting now. I did already try to deregister jquery first and then try to reregister it...but that didn't work either.

Now I've read that WordPress comes with jQuery...but if I don't add it, I don't get the functionality I need. I've looked all over Stack Overflow for an answer but I can't quite seem to get this to work.

Again, this is my first plugin I've developed so I'd appreciate any help. Thank you.


问:
JSON encoding unsigned 64 bit integers in PHP
I know PHP does not support unsigned 64 bit integers.

However I simply need to read unsigned 64 bit integer values from a MySQL table via PDO query, and pass them through to clients (without performing any calculation or comparison); the PHP page is publishing a very simple REST interface to clients and should output the query result as JSON data only.

Right now the PDO query returns untouched integers as long as they are 63bit wide (no sign), but when the original value in the table has the 64th bit set, the PDO driver converts it to a string (I have set PDO::ATTR_STRINGIFY_FETCHES attribute to false, since I want types to be preserved as much as possible).

When I call the json_encode() function, the related fields get the same treatment: they become strings when they exceed 63 bit width.

I do not want to leave them as strings in json output, since it would require "breaking" changes in client code to have them handling json-string to ulong conversion upon decoding.

Is there a way to customize json_encode behavior somehow to output them as "UInt64" ?

I've taken a look at JsonSerializable but it seems it cannot solve my issue.

答:
I found a workaround to the problem, not exactly "elegant", but practical (and it works).

I've included in my project a custom pure-PHP json encoding library found on GitHub here.

I've declared this interface:

```<code>interface JSONSerializer
{
    public function toJSON();
}
</code>```

I've implemented the interface in this simple class:

```<code>class UInt64Raw implements JSONSerializer {

    private $value;

    public function __construct($number) {
        $this->value = $number;
    }

    public function getValue() { return $this->value; }

    public function toJSON() {
        if (is_null($this->value)) return "null";
        if ($this->value) return (string)$this->value;
        return "0";
    }

}
</code>```

I've changed a little bit the default behavior of the JSON encoder library in order to invoke the interface method whenever the object to be encoded is implementing that interface.

I can then retrieve unsigned 64 bit integers as strings from PDO, wrap them inside a UInt64Raw object instance and eventually pass them unquoted (as numbers) through custom JSON encoding.

Body:
I found a workaround to the problem, not exactly "elegant", but practical (and it works).

I've included in my project a custom pure-PHP json encoding library found on GitHub here.

I've declared this interface:

interface JSONSerializer
{
    public function toJSON();
}

I've implemented the interface in this simple class:

class UInt64Raw implements JSONSerializer {

    private $value;

    public function __construct($number) {
        $this->value = $number;
    }

    public function getValue() { return $this->value; }

    public function toJSON() {
        if (is_null($this->value)) return "null";
        if ($this->value) return (string)$this->value;
        return "0";
    }

}

I've changed a little bit the default behavior of the JSON encoder library in order to invoke the interface method whenever the object to be encoded is implementing that interface.

I can then retrieve unsigned 64 bit integers as strings from PDO, wrap them inside a UInt64Raw object instance and eventually pass them unquoted (as numbers) through custom JSON encoding.


问:
Difference between custom serialisation and Externalisation?
Recently from any source, I came to know that custom serialisation is a process where we can define writeObject(ObjectOutputStream os) and readObject(ObjectInputStream is) in our Serializable class, and these methods will be executed at the time of serialisation and de-serialisation respectively to perform our functionality.

Later on, I came to know that Externalisation is an interface which defines 2 methods:
1- writeExternal()
2- readExternal()

Our class can implement Externalizable and override these methods when we don't want to serialise whole object. These methods will be executed at the time of serialisation and de-serialisation.

I have a doubt that why can't we use custom serialisation by implementing Serializable and defining writeObject(ObjectOutputStream os) and readObject(ObjectInputStream is) methods even to serialise some attributes of an object. Why this externalisation came into the picture.

Thanks,

答:
Externalizable was introduced way before Serializable interface during JDK 1.1 days. During that time, the programmer had to write the exact logic how the object shall be serialized, ie, everything that shall occur inside the writeExternal() and readExternal() had to be written explicitly. Serializable was introduced later to get rid of this headache.

But in some cases, using Externalizable has its own advantages as it allows you to define how the class shall be serialized in your own way rather than depending on what is defined underneath the hood by Java language APIs. I think your class may fall under this category.

To answer your question added in the last part, you can achieve selective serialization of members inside a class by marking them as transient.


问:
Google Drive API oauth 2 error
I managed to get the code runing to a point where i can upload and download files in my android app from google drive using the api. However i uploaded my app to Google Play and when a user installs it the first time the oauth 2 screen pops up and requires to select account(which is great) but when the user selects Google account the oauth screen just keep appearing and looping.
Did anyone encounter this before? </p>

答: As stated in this thread, maybe you did not create credentials for your app. As described in this documentation, you must retrieve your SHA-1 keys for both the debug and production environments and add them in your credentials in the Google Developers Console.</p>

Title: Google Drive API oauth 2 error


问:
Google signIn error after generation signed apk
When I compile the app from android studio the signin works. I generate the signed apk but it doesn't work and says login error.

The error that give after is: You have wrong OAuth2 related configurations, please check. Detailed error: UNREGISTERED_ON_API_CONSOLE.

I am using Google Signin Auth.

Which showed when I was not able to configure before and after it shows again. Can someone help me?

答:
You may check this thread. It stated that when you sign an APK and then ask Google for a OAuth2 token, you have to register your signed app through the dev console. It's a security measure based on the app package name and the sha1 fingerprint.

To do that, you have to:

sign your APK, manually or through Gradle or whatever: the Android documentation is pretty clear on this step;

get your sha1 fingerprint; as mention in this SO answer, it's kind of easy on Android Studio: in the Gradle panel, select the signingReport task under your root project and run it - the SHA1 fingerprint will show in the text output;

register your APK through the Google dev console: create a new Credentials / OAuth client id / Android, defined by the SHA1 fingerprint you got and your APK package name.

Additional reference which might help: Google sign in failed after frequent signing in and out


问:
Jquery: Reset (enable) Select options that were previously disabled onchange
I have a "sector" field that disables/enables select options depending on what the end user choose from the "name" field.

This happens using an onchange function. The onChange aspect works fine, but I am having troubles "reseting" the "sector" field if a user chooses a selection for a second time from the "name" field.

```<code>$('#filter_pname').change(function() {
    $('#filter_secteur option').attr("enabled", "true"); // reset attempt

    var variable = $('#filter_pname option:selected').data('secteur');
    $('#filter_secteur option:not(:contains('+ variable +'))').attr("disabled","disabled");
});
</code>```

If a second selection is chosen, the disabled fields remain disabled.

https://jsfiddle.net/invisionweb/kysfzbdy/

答:
Instead of doing .attr("enabled", "true");, do this instead: .removeAttr('disabled'); or .attr("disabled", false);

```<code>$('#filter_pname').change(function() {
    $('#filter_secteur option').removeAttr('disabled'); // reset attempt

    var variable = $('#filter_pname option:selected').data('secteur');
    $('#filter_secteur option:not(:contains('+ variable +'))').attr("disabled","disabled");
});
</code>```

Body:
I have a "sector" field that disables/enables select options depending on what the end user choose from the "name" field.

This happens using an onchange function. The onChange aspect works fine, but I am having troubles "reseting" the "sector" field if a user chooses a selection for a second time from the "name" field.

$('#filter_pname').change(function() {
    $('#filter_secteur option').attr("enabled", "true"); // reset attempt

    var variable = $('#filter_pname option:selected').data('secteur');
    $('#filter_secteur option:not(:contains('+ variable +'))').attr("disabled","disabled");
});

If a second selection is chosen, the disabled fields remain disabled.

https://jsfiddle.net/invisionweb/kysfzbdy/

Body:
Instead of doing .attr("enabled", "true");, do this instead: .removeAttr('disabled'); or .attr("disabled", false);

$('#filter_pname').change(function() {
    $('#filter_secteur option').removeAttr('disabled'); // reset attempt

    var variable = $('#filter_pname option:selected').data('secteur');
    $('#filter_secteur option:not(:contains('+ variable +'))').attr("disabled","disabled");
});


问:
Extract upper or lower triangular part of a numpy matrix
I have a matrix A and I want 2 matrices U and L such that U contains the upper triangular elements of A (all elements above and not including diagonal) and similarly for L(all elements below and not including diagonal). Is there a numpy method to do this?

e.g

```<code>A = array([[ 4.,  9., -3.],
           [ 2.,  4., -2.],
           [-2., -3.,  7.]])

U = array([[ 0.,  9., -3.],
           [ 0.,  0., -2.],
           [ 0.,  0.,  0.]])

L = array([[ 0.,  0.,  0.],
           [ 2.,  0.,  0.],
           [-2., -3.,  0.]])
</code>```

答:
To extract the upper triangle values to a flat vector,
you can do something like the following:

```<code>import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)

#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

a[np.triu_indices(3)]
#or
list(a[np.triu_indices(3)])

#array([1, 2, 3, 5, 6, 9])
</code>```

Similarly, for the lower triangle, use np.tril.

IMPORTANT

If you want to extract the values that are above the diagonal (or below) then use the k argument. This is usually used when the matrix is symmetric.

```<code>import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

a[np.triu_indices(3, k = 1)]

# this returns the following
array([2, 3, 6])
</code>```

EDIT (on 11.11.2019):

To put back the extracted vector into a 2D symmetric array, one can follow my answer here: https://stackoverflow.com/a/58806626/5025009

ContentLicense: CC BY-SA 4.0

Body:
I have a matrix A and I want 2 matrices U and L such that U contains the upper triangular elements of A (all elements above and not including diagonal) and similarly for L(all elements below and not including diagonal). Is there a numpy method to do this?

e.g

A = array([[ 4.,  9., -3.],
           [ 2.,  4., -2.],
           [-2., -3.,  7.]])

U = array([[ 0.,  9., -3.],
           [ 0.,  0., -2.],
           [ 0.,  0.,  0.]])

L = array([[ 0.,  0.,  0.],
           [ 2.,  0.,  0.],
           [-2., -3.,  0.]])

Body:
To extract the upper triangle values to a flat vector,
you can do something like the following:

import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)

#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

a[np.triu_indices(3)]
#or
list(a[np.triu_indices(3)])

#array([1, 2, 3, 5, 6, 9])

Similarly, for the lower triangle, use np.tril.

IMPORTANT

If you want to extract the values that are above the diagonal (or below) then use the k argument. This is usually used when the matrix is symmetric.

import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

a[np.triu_indices(3, k = 1)]

# this returns the following
array([2, 3, 6])

EDIT (on 11.11.2019):

To put back the extracted vector into a 2D symmetric array, one can follow my answer here: https://stackoverflow.com/a/58806626/5025009


问:
Camunda/Activiti process loops endessly in JavaDelegate's
I have problem with camunda process that looks like this.
This process loops endlessly in an non deterministic way in steps SetId and CreateObjectsForId (both are JavaDelegates).

I am using camunda 7.5.

I have some BaseJavaDelegate implemented like:

```<code>@Override
public void execute( DelegateExecution aExecution ) throws Exception
{
    logBefore( aExecution );
    try
    {
        executeInTry( aExecution );
    }
    catch( Throwable aEx )
    {
        aEx.printStackTrace();
        throw new BpmnError( "GENERIC_ERROR_CODE", aEx.getMessage() );
    }
   logAfter( aExecution );
}
</code>```

Log from example execution:

```<code>01.06.2017 15:32:53,902;pool-6-thread-2:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
01.06.2017 15:32:54,664;pool-6-thread-2:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Ended task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: d161958b-46ce-11e7-8483-005056b37c6b
    ActivityId: CreateObjectsForId
    TransactionId: null
...
01.06.2017 15:37:53,886;pool-6-thread-3:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
01.06.2017 15:37:53,893;pool-6-thread-3:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Ended task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: d161958b-46ce-11e7-8483-005056b37c6b
    ActivityId: CreateObjectsForId
    TransactionId: null
</code>```

From log you can see that SetId was started second time while CreateObjectsForId never finished.
No exception is thrown during this execution.
Also previous steps are all executed in the same thread but when the loop begins process starts using another thread/two threads.

I have tried to bypass this problem by designing process like this.
This time implementation of SetId step knows that it was entered for the second time and with exclusive gate process should go further.

Unfortunately the process still loops! No exception from my code. No OptimisticLockException. No any other exception from camunda.
I have no clue what else can cause process to loop like this.

答:
I have found solution to my problem.
I have been running embedded camunda engine.

Once, I decided to try running the same code on application server (wildfly in my case). Now I got clear messages in log that my transactions we just taking too long. Here you can find solution of this problem (transactions timeout and jobs-executor lockTimeInMillis)

Body:
I have problem with camunda process that looks like this.
This process loops endlessly in an non deterministic way in steps SetId and CreateObjectsForId (both are JavaDelegates).

I am using camunda 7.5.

I have some BaseJavaDelegate implemented like:

@Override
public void execute( DelegateExecution aExecution ) throws Exception
{
    logBefore( aExecution );
    try
    {
        executeInTry( aExecution );
    }
    catch( Throwable aEx )
    {
        aEx.printStackTrace();
        throw new BpmnError( "GENERIC_ERROR_CODE", aEx.getMessage() );
    }
   logAfter( aExecution );
}

Log from example execution:

01.06.2017 15:32:53,902;pool-6-thread-2:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
01.06.2017 15:32:54,664;pool-6-thread-2:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Ended task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: d161958b-46ce-11e7-8483-005056b37c6b
    ActivityId: CreateObjectsForId
    TransactionId: null
...
01.06.2017 15:37:53,886;pool-6-thread-3:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
01.06.2017 15:37:53,893;pool-6-thread-3:...wf.base.BaseJavaDelegate;callExecuteInTry;DEBUG;
Ended task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ActivityId: SetId
    TransactionId: null
...
Starting task:
    ProcessDefinitionId: ...Process1:1:1
    ProcessInstanceId: ae2ecf43-46ce-11e7-8483-005056b37c6b
    ExecutionId: d161958b-46ce-11e7-8483-005056b37c6b
    ActivityId: CreateObjectsForId
    TransactionId: null

From log you can see that SetId was started second time while CreateObjectsForId never finished.
No exception is thrown during this execution.
Also previous steps are all executed in the same thread but when the loop begins process starts using another thread/two threads.

I have tried to bypass this problem by designing process like this.
This time implementation of SetId step knows that it was entered for the second time and with exclusive gate process should go further.

Unfortunately the process still loops! No exception from my code. No OptimisticLockException. No any other exception from camunda.
I have no clue what else can cause process to loop like this.


问:
invalid comparison between distintc pointer types: 'type*' and 'type&(*)()'
I cannot understand why the compiler is complaining about a bad comparison attempt.

The offending comparison is this:

```<code>method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble) {
        ...
    }
...
}
</code>```

And here are the type declarations of the compared items:

```<code>const fltSemantics &getSemantics() const;
static const fltSemantics &IEEEdouble();
</code>```

The error indicated by the compiler looks like this:

comparison between distinct pointer types 'const llvm::fltSemantics*' and 'const llvm::fltSemantics& (*)()' lacks a cast [-fpermissive]

Can anybody help me understand this? I am a beginner but to me it looks both terms in the comparison are of type const fltsemantics &&.

PS: I am compiling with gcc and C++11 compliance.

答:
You are comparing an object pointer to a function pointer, fix:</p>

```<code>method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble()) {
        ...
    }
...
}
</code>```

Body:
I cannot understand why the compiler is complaining about a bad comparison attempt.

The offending comparison is this:

method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble) {
        ...
    }
...
}

And here are the type declarations of the compared items:

const fltSemantics &getSemantics() const;
static const fltSemantics &IEEEdouble();

The error indicated by the compiler looks like this:

comparison between distinct pointer types 'const llvm::fltSemantics*' and 'const llvm::fltSemantics& (*)()' lacks a cast [-fpermissive]

Can anybody help me understand this? I am a beginner but to me it looks both terms in the comparison are of type const fltsemantics &&.

PS: I am compiling with gcc and C++11 compliance.

Body:
You are comparing an object pointer to a function pointer, fix:

method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble()) {
        ...
    }
...
}


问:
Selective reshaping of 3d array to 2d array
I'm working with a 3d array of vectors, and having trouble reshaping properly.
My dimensions correspond to quantities as follows:

0 = vector (3)

1 = point (4)

2 = polyline (2)

So this can be interpreted as 2 polylines that each contain 4 points, and each point has a vector. I want to reshape to a 2d matrix that is (3, 8).

The original array is:

```<code>poly_array = array([[[-0.707, 0.0],
                      [-0.371, 0.0],
                      [0.371, 0.0],
                      [0.707, 0.0]],
                     [[0.0, -0.707],
                      [0.0, 0.0],
                      [0.0, 0.707],
                      [0.0, 0.0]],
                     [[0.707, 0.707],
                      [0.928, 1.0],
                      [0.928, 0.707],
                      [0.707, 0.0]]])
</code>```

so if I'm looking at ordered points along the first polyline, I would run:

```<code>for i in range(4):
    print poly_array[:,i,0]
</code>```

or for ordered points along the second polyline:

```<code>for i in range(4):
    print poly_array[:,i,1]
</code>```

If I reshape this way:

```<code>new_dim = shape(poly_array)[1] * shape(poly_array)[2]
new_array = poly_array.reshape(3, new_dim)
</code>```

But this orders the vectors as taking one from each polyline (i.e., pt0-polyline0, pt0-polyline1, pt1-polyline0, pt1-polyline1, etc.)

```<code>In: print new_array[:, 0]
Out: [-0.707  0.     0.707]

In: print new_array[:, 1]
Out: [ 0.    -0.707  0.707]
</code>```

But I want

```<code>In: print new_array[:, 1]
Out: [-0.371  0.     0.928]
</code>```

How can I reshape so that it loops through all the vectors corresponding to points (along axis 1) for a given polyline before the next polyline?

Body:
I'm working with a 3d array of vectors, and having trouble reshaping properly.
My dimensions correspond to quantities as follows:

0 = vector (3)

1 = point (4)

2 = polyline (2)

So this can be interpreted as 2 polylines that each contain 4 points, and each point has a vector. I want to reshape to a 2d matrix that is (3, 8).

The original array is:

poly_array = array([[[-0.707, 0.0],
                      [-0.371, 0.0],
                      [0.371, 0.0],
                      [0.707, 0.0]],
                     [[0.0, -0.707],
                      [0.0, 0.0],
                      [0.0, 0.707],
                      [0.0, 0.0]],
                     [[0.707, 0.707],
                      [0.928, 1.0],
                      [0.928, 0.707],
                      [0.707, 0.0]]])

so if I'm looking at ordered points along the first polyline, I would run:

for i in range(4):
    print poly_array[:,i,0]

or for ordered points along the second polyline:

for i in range(4):
    print poly_array[:,i,1]

If I reshape this way:

new_dim = shape(poly_array)[1] * shape(poly_array)[2]
new_array = poly_array.reshape(3, new_dim)

But this orders the vectors as taking one from each polyline (i.e., pt0-polyline0, pt0-polyline1, pt1-polyline0, pt1-polyline1, etc.)

In: print new_array[:, 0]
Out: [-0.707  0.     0.707]

In: print new_array[:, 1]
Out: [ 0.    -0.707  0.707]

But I want

In: print new_array[:, 1]
Out: [-0.371  0.     0.928]

How can I reshape so that it loops through all the vectors corresponding to points (along axis 1) for a given polyline before the next polyline?

Body:
You would need some permuting of axes with np.swapaxes and a reshape -

poly_array.swapaxes(1,2).reshape(poly_array.shape[0],-1)

Sample run -

In [127]: poly_array
Out[127]:
array([[[-0.707,  0.   ],
        [-0.371,  0.   ],
        [ 0.371,  0.   ],
        [ 0.707,  0.   ]],

       [[ 0.   , -0.707],
        [ 0.   ,  0.   ],
        [ 0.   ,  0.707],
        [ 0.   ,  0.   ]],

       [[ 0.707,  0.707],
        [ 0.928,  1.   ],
        [ 0.928,  0.707],
        [ 0.707,  0.   ]]])

In [142]: out
Out[142]:
array([[-0.707, -0.371,  0.371,  0.707,  0.   ,  0.   ,  0.   ,  0.   ],
       [ 0.   ,  0.   ,  0.   ,  0.   , -0.707,  0.   ,  0.707,  0.   ],
       [ 0.707,  0.928,  0.928,  0.707,  0.707,  1.   ,  0.707,  0.   ]])

In [143]: out[:,1]
Out[143]: array([-0.371,  0.   ,  0.928])


问:
Tensorflow import metagraph placeholder not fed
I'm working on a project in Tensorflow. I have built and trained a CNN and now I'm trying to load it in another file to make predictions. For some reason I keep getting the error "You must feed a value for placeholder tensor 'y_pred' with dtype float and shape [10]"

The file which the graph was constructed from has a variable y_pred for the prediction:

```<code>y_pred = tf.nn.softmax(layer_fc2)
</code>```

The file where I'm trying to load the model is as follows:

```<code># Create Session
sess = tf.Session()
# Load model
saver = tf.train.import_meta_graph('Model.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
sess.run(tf.global_variables_initializer())
graph = tf.get_default_graph()
x_batch = mnist.test.next_batch(1)

x_batch = x_batch[0].reshape(1, 784)
x = graph.get_tensor_by_name("x:0")
y_pred = graph.get_tensor_by_name("y_pred:0")

classification = sess.run(y_pred, feed_dict={x:x_batch})
print(classification)
</code>```

The exact error I'm getting is:

```<code>InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'y_pred' with dtype float and shape [10]
 [[Node: y_pred = Placeholder[dtype=DT_FLOAT, shape=[10], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

I'm wondering if maybe I'm not setting the value correctly before I export it?
Does anyone know why this isn't working?

Edit. Including model code:

```<code># Network Design
# First Layer
layer_conv1, weights_conv1 = new_conv_layer(input=x_image, num_input_channels=num_channels, filter_size=filter_size1, num_filters=num_filters1, use_pooling=True)
# Second Layer
layer_conv2, weights_conv2 = new_conv_layer(input=layer_conv1, num_input_channels=num_filters1, filter_size=filter_size2, num_filters=num_filters2, use_pooling=True)
# Third Layer
layer_conv3, weights_conv3 = new_conv_layer(input=layer_conv2, num_input_channels=num_filters2, filter_size=filter_size3, num_filters=num_filters3, use_pooling=True)
# Flatten Layer
layer_flat, num_features = flatten_layer(layer_conv3)
# First Fully Connected Layer
layer_fc1 = new_fc_layer(input=layer_flat, num_inputs=num_features, num_outputs=fc_size, use_relu=True)
# Second Fully Connected Layer
layer_fc2 = new_fc_layer(input=layer_fc1, num_inputs=fc_size, num_outputs=num_classes, use_relu=False)

# softmaxResult = tf.placeholder(tf.float32, shape=[10], name='softmaxResult')
# Get class probabilities
y_pred = tf.nn.softmax(layer_fc2)
y_pred = tf.identity(y_pred, name="y_pred")
# session.run(y_pred, feed_dict={softmaxResult: y_pred})
# Predicted Class
y_pred_cls = tf.argmax(y_pred, dimension=1)
# softmaxResult.assign(y_pred_cls)

# Feed y_pred
# session.run(softmaxResult, feedDict={softmaxResult: softmaxResult})

# Define Cost Function
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y_true)
cost = tf.reduce_mean(cross_entropy)

# Optimize Network
optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)
correct_prediction = tf.equal(y_pred_cls, y_true_cls)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Run Session
session.run(tf.global_variables_initializer())

def print_progress(epoch, feed_dict_train, feed_dict_validate, val_loss):
    #Calculate accuracy on training set
    acc = session.run(accuracy, feed_dict=feed_dict_train)
    val_acc = session.run(accuracy, feed_dict=feed_dict_validate)
    msg = "Epoch {0} --- Training Accuracy: {1:>6.1%}, Validation Accuracy: {2:>6.1%}, Validation Loss: {3:.3f}"
    print(msg.format(epoch + 1, acc, val_acc, val_loss))

total_iterations = 0

#Optimization Function
def optimize(num_iterations):
    # Updates global rather than local value
    global total_iterations

    best_val_loss = float("inf")

    for i in range(total_iterations, total_iterations + num_iterations):
        # Get training data batch
        x_batch, y_batch = mnist.train.next_batch(batch_size)
        # Get a validation batch
        x_validate, y_validate = mnist.train.next_batch(batch_size)

        # Shrink to single dimension
        x_batch = x_batch.reshape(batch_size, img_size_flat)
        x_validate = x_validate.reshape(batch_size, img_size_flat)

        # Training feed
        feed_dict_train = {x: x_batch, y_true: y_batch}
        feed_dict_validate = {x: x_validate, y_true: y_validate}

        # Run the optimizer
        session.run(optimizer, feed_dict=feed_dict_train)

        # Print status at end of each epoch (defined as full pass through training dataset).
        if i % int(5000/batch_size) == 0:
            val_loss = session.run(cost, feed_dict=feed_dict_validate)
            epoch = int(i / int(5000/batch_size))

            print_progress(epoch, feed_dict_train, feed_dict_validate, val_loss)

        total_iterations += num_iterations

optimize(num_iterations=3000)

# Save the final model
saver = tf.train.Saver()
saved_path = saver.save(session, os.path.join(os.getcwd(),'MNIST Model'))
print("Model saved in: ", saved_path)

# Run on test image
image = mnist.test.next_batch(1)
feedin = image[0].reshape(1, 784)
inputStuff = {x:feedin}

classification = session.run(y_pred, feed_dict=inputStuff)
print(classification)
</code>```

答:
Thank you @VS_FF

You need to find in 'x:0' as they input key.

Body:
I'm working on a project in Tensorflow. I have built and trained a CNN and now I'm trying to load it in another file to make predictions. For some reason I keep getting the error "You must feed a value for placeholder tensor 'y_pred' with dtype float and shape [10]"

The file which the graph was constructed from has a variable y_pred for the prediction:

y_pred = tf.nn.softmax(layer_fc2)

The file where I'm trying to load the model is as follows:

# Create Session
sess = tf.Session()
# Load model
saver = tf.train.import_meta_graph('Model.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
sess.run(tf.global_variables_initializer())
graph = tf.get_default_graph()
x_batch = mnist.test.next_batch(1)

x_batch = x_batch[0].reshape(1, 784)
x = graph.get_tensor_by_name("x:0")
y_pred = graph.get_tensor_by_name("y_pred:0")

classification = sess.run(y_pred, feed_dict={x:x_batch})
print(classification)

The exact error I'm getting is:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'y_pred' with dtype float and shape [10]
 [[Node: y_pred = Placeholder[dtype=DT_FLOAT, shape=[10], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

I'm wondering if maybe I'm not setting the value correctly before I export it?
Does anyone know why this isn't working?

Edit. Including model code:

# Network Design
# First Layer
layer_conv1, weights_conv1 = new_conv_layer(input=x_image, num_input_channels=num_channels, filter_size=filter_size1, num_filters=num_filters1, use_pooling=True)
# Second Layer
layer_conv2, weights_conv2 = new_conv_layer(input=layer_conv1, num_input_channels=num_filters1, filter_size=filter_size2, num_filters=num_filters2, use_pooling=True)
# Third Layer
layer_conv3, weights_conv3 = new_conv_layer(input=layer_conv2, num_input_channels=num_filters2, filter_size=filter_size3, num_filters=num_filters3, use_pooling=True)
# Flatten Layer
layer_flat, num_features = flatten_layer(layer_conv3)
# First Fully Connected Layer
layer_fc1 = new_fc_layer(input=layer_flat, num_inputs=num_features, num_outputs=fc_size, use_relu=True)
# Second Fully Connected Layer
layer_fc2 = new_fc_layer(input=layer_fc1, num_inputs=fc_size, num_outputs=num_classes, use_relu=False)

# softmaxResult = tf.placeholder(tf.float32, shape=[10], name='softmaxResult')
# Get class probabilities
y_pred = tf.nn.softmax(layer_fc2)
y_pred = tf.identity(y_pred, name="y_pred")
# session.run(y_pred, feed_dict={softmaxResult: y_pred})
# Predicted Class
y_pred_cls = tf.argmax(y_pred, dimension=1)
# softmaxResult.assign(y_pred_cls)

# Feed y_pred
# session.run(softmaxResult, feedDict={softmaxResult: softmaxResult})

# Define Cost Function
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y_true)
cost = tf.reduce_mean(cross_entropy)

# Optimize Network
optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)
correct_prediction = tf.equal(y_pred_cls, y_true_cls)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Run Session
session.run(tf.global_variables_initializer())

def print_progress(epoch, feed_dict_train, feed_dict_validate, val_loss):
    #Calculate accuracy on training set
    acc = session.run(accuracy, feed_dict=feed_dict_train)
    val_acc = session.run(accuracy, feed_dict=feed_dict_validate)
    msg = "Epoch {0} --- Training Accuracy: {1:>6.1%}, Validation Accuracy: {2:>6.1%}, Validation Loss: {3:.3f}"
    print(msg.format(epoch + 1, acc, val_acc, val_loss))

total_iterations = 0

#Optimization Function
def optimize(num_iterations):
    # Updates global rather than local value
    global total_iterations

    best_val_loss = float("inf")

    for i in range(total_iterations, total_iterations + num_iterations):
        # Get training data batch
        x_batch, y_batch = mnist.train.next_batch(batch_size)
        # Get a validation batch
        x_validate, y_validate = mnist.train.next_batch(batch_size)

        # Shrink to single dimension
        x_batch = x_batch.reshape(batch_size, img_size_flat)
        x_validate = x_validate.reshape(batch_size, img_size_flat)

        # Training feed
        feed_dict_train = {x: x_batch, y_true: y_batch}
        feed_dict_validate = {x: x_validate, y_true: y_validate}

        # Run the optimizer
        session.run(optimizer, feed_dict=feed_dict_train)

        # Print status at end of each epoch (defined as full pass through training dataset).
        if i % int(5000/batch_size) == 0:
            val_loss = session.run(cost, feed_dict=feed_dict_validate)
            epoch = int(i / int(5000/batch_size))

            print_progress(epoch, feed_dict_train, feed_dict_validate, val_loss)

        total_iterations += num_iterations

optimize(num_iterations=3000)

# Save the final model
saver = tf.train.Saver()
saved_path = saver.save(session, os.path.join(os.getcwd(),'MNIST Model'))
print("Model saved in: ", saved_path)

# Run on test image
image = mnist.test.next_batch(1)
feedin = image[0].reshape(1, 784)
inputStuff = {x:feedin}

classification = session.run(y_pred, feed_dict=inputStuff)
print(classification)


问:
Downloading Xcode 9 (or 9.1 Beta release)
I downloaded iOS 11 on my device and want to continue testing my projects on my device but it wont work because it says that ios 11.0 may not support the version of Xcode I have (which is 8.3.3). I am assuming this is because I need to use the Xcode 9 (or 9.1 beta release) but I can't seem to find where I can download this at.</p>

答:
The XCode 9 Beta does not show up in the Download Center for people without the paid developer program membership.

Instead, it can be downloaded directly via this link:
http://adcdownload.apple.com/WWDC_2017/Xcode_9_beta/Xcode_9_beta.xip

UPDATED LINK TO BETA 3:
https://download.developer.apple.com/Developer_Tools/Xcode_9_beta_3/Xcode_9_beta_3.xip
(From computingfreak's comment below.)

UPDATED LINK TO BETA 4:

https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_9_beta_4/Xcode_9_beta_4.xip


问:
TinyMCE editor in Ajax form using jQuery plugin
I have ajax form (http://jquery.malsup.com/form/) and I use jQuery plugin to install my TinyMCE editor. But I cannot get textarea content in ajax request. This is because its in TinyMCE editor iframe. I tried several tutorials from google, but all failed to work for me. Editor shows up, but when I send ajax request, it fails to get edited textarea content.

Here is how I install TinyMCE editor, but this fails

```<code>$("textarea.tinymce").tinymce({
    script_url : tinymceUrl,
    mode : "none",
    theme : "simple",
    setup : function(ed) {
        ed.onChange.add(function() {
            tinyMCE.triggerSave(true,true);
        });
    }
});
</code>```

答:
As Dave G already states the API link is old (and i was wondering about the call of triggerSave).

Please try

```<code>tinyMCE.triggerSave();
</code>```

Body:
I have ajax form (http://jquery.malsup.com/form/) and I use jQuery plugin to install my TinyMCE editor. But I cannot get textarea content in ajax request. This is because its in TinyMCE editor iframe. I tried several tutorials from google, but all failed to work for me. Editor shows up, but when I send ajax request, it fails to get edited textarea content.

Here is how I install TinyMCE editor, but this fails

$("textarea.tinymce").tinymce({
    script_url : tinymceUrl,
    mode : "none",
    theme : "simple",
    setup : function(ed) {
        ed.onChange.add(function() {
            tinyMCE.triggerSave(true,true);
        });
    }
});

Body:
As Dave G already states the API link is old (and i was wondering about the call of triggerSave).

Please try

tinyMCE.triggerSave();


问:
Does docker use host's random and timesync
When I run a docker container, does it use host's /dev/random /dev/urandom and does it use host's time?

I'm planning to use haveged and ntp, so is it enough to install them on the host machine, or do I need to somehow install/link them to the container?

答:
Docker shares the kernel with the docker host, so devices like /dev/random and time that are provided by the kernel will be handled outside of your container. In fact, if you try to change the time inside of a container, you'll find that docker has removed this capability by default (CAP_SYS_TIME).

```<code>root@66fd0ad0324e:/# date 06061209
date: cannot set date: Operation not permitted
</code>```

There is one caveat, if docker is running on a VM like it does with environments like MacOS and Windows, the VM is running the kernel, so you need to ensure its time is correct in that VM. I believe you could do this with a privileged container running the ntp daemon.

Body:
Docker shares the kernel with the docker host, so devices like /dev/random and time that are provided by the kernel will be handled outside of your container. In fact, if you try to change the time inside of a container, you'll find that docker has removed this capability by default (CAP_SYS_TIME).

root@66fd0ad0324e:/# date 06061209
date: cannot set date: Operation not permitted

There is one caveat, if docker is running on a VM like it does with environments like MacOS and Windows, the VM is running the kernel, so you need to ensure its time is correct in that VM. I believe you could do this with a privileged container running the ntp daemon.


问:
How can I access variable inside another function jquery
I have this object and want to access the variable scrolled var scrolled = 10; from the init function within the scrollDown function.

I am having trouble accessing the variable. How can I achieve this?

```<code>// Summary Screen Functions
var summary = {
    init: function() {

        var scrolled = 0;

        $('.page-summary-action a').on('click', summary.continueToSummary);
        $('.scroll-down').on('click', summary.scrollDown);
        $('.scroll-up').on('click', summary.scrollUp);
    },

    scrollDown: function(e) {
        e.preventDefault();
        scrolled = scrolled + 300;

        console.log('clicked');

        $(".data-cards").animate({
            scrollTop:  scrolled
        });
    },

    scrollUp: function(e) {
        e.preventDefault();
        console.log('clicked');

        $(".data-cards").animate({
            scrollTop: 15
        });
    }
};

summary.init();
</code>```

答:
Following your question, you should use this.scrolled instead of var. An example would be

```<code> var summary = {
    init: function() {
        this.scrolled = 20;
    },

    scrollDown: function(e) {
        console.log(this.scrolled);
    },

    scrollUp: function(e) {
        console.log(this.scrolled);
    }
 };
 summary.init();
 summary.scrollDown();
</code>```

to satisfy your curiosity, you should look up this link How does the “this” keyword work? and Explanation from MDN

Body:
I have this object and want to access the variable scrolled var scrolled = 10; from the init function within the scrollDown function.

I am having trouble accessing the variable. How can I achieve this?

// Summary Screen Functions
var summary = {
    init: function() {

        var scrolled = 0;

        $('.page-summary-action a').on('click', summary.continueToSummary);
        $('.scroll-down').on('click', summary.scrollDown);
        $('.scroll-up').on('click', summary.scrollUp);
    },

    scrollDown: function(e) {
        e.preventDefault();
        scrolled = scrolled + 300;

        console.log('clicked');

        $(".data-cards").animate({
            scrollTop:  scrolled
        });
    },

    scrollUp: function(e) {
        e.preventDefault();
        console.log('clicked');

        $(".data-cards").animate({
            scrollTop: 15
        });
    }
};

summary.init();

Body:
Following your question, you should use this.scrolled instead of var. An example would be

 var summary = {
    init: function() {
        this.scrolled = 20;
    },

    scrollDown: function(e) {
        console.log(this.scrolled);
    },

    scrollUp: function(e) {
        console.log(this.scrolled);
    }
 };
 summary.init();
 summary.scrollDown();

to satisfy your curiosity, you should look up this link How does the “this” keyword work? and Explanation from MDN


问:
ren *.xml *.xsig works in cmd but not in .bat
I have a very simple batch file, I want it to change the extension of all the .xml into .xsig files in the folder of the batch file.
The only line that is in the batch file is:

```<code>ren *.xml *.xsig
</code>```

The command works fine in cmd, but not by double clicking the batch file, it always reports the next message:

```<code>The system could not find the file specified
</code>```

What am I doing wrong? I've tested this in windows 7.

答: "by double clicking" you start your batchfile with a working folder of %windir\system32. I'm quite sure, there are no .xml files. Spend your batchfile a cd %~dp0 to change the working folder to the same where your batchfile resides, or cd /d or pushd to the proper folder.

Body:
I have a very simple batch file, I want it to change the extension of all the .xml into .xsig files in the folder of the batch file.
The only line that is in the batch file is:

ren *.xml *.xsig

The command works fine in cmd, but not by double clicking the batch file, it always reports the next message:

The system could not find the file specified

What am I doing wrong? I've tested this in windows 7.