问:
Algorithm for Knapsack with repetition
I am trying to devise a pseudo-code for Knapsack algorithms, where a single item can be selected multiple times. The classical algorithm is

```<code>OPT(i, w) = max(OPT(i-1, w) or vi + OPT(i-1, w-wi))
</code>```

In order to meet the requirements, I am modifying it to

```<code>k=1;
max = maximum(OPT(i-1, w))
while(OPT(i-1, w - k*wi) > 0) {
  maximum = max(maximum, k*vi + OPT(i-1, w - k*wi))
  k++
}
OPT(i, w) = maximum
</code>```

Does this seem to be an appropriate solution? Or any better solution exists?
Please let me know if any additional information is required.
Rest all remains the same, vi denotes the value of ith element and wi denotes the weight of ith element.

答:
Based on Algorithms DVP, the solution to Knapsack with repetition is like below:

```<code>K(0)=0
for w=1 to W:
    K(w) = max{K(w - w_i) + v_i, w_i < w}
return K(W)
</code>```

Here, W is the capacity; w_i is the weight of item i; v_i is the value of item i; K(w) is the max value achievable with knapsack of capacity w.

Your solution seems like 0-1 Knapsack though.

Title: Algorithm for Knapsack with repetition

Body:
I am trying to devise a pseudo-code for Knapsack algorithms, where a single item can be selected multiple times. The classical algorithm is

OPT(i, w) = max(OPT(i-1, w) or vi + OPT(i-1, w-wi))

In order to meet the requirements, I am modifying it to

k=1;
max = maximum(OPT(i-1, w))
while(OPT(i-1, w - k*wi) > 0) {
  maximum = max(maximum, k*vi + OPT(i-1, w - k*wi))
  k++
}
OPT(i, w) = maximum

Does this seem to be an appropriate solution? Or any better solution exists?
Please let me know if any additional information is required.
Rest all remains the same, vi denotes the value of ith element and wi denotes the weight of ith element.

Body:
Based on Algorithms DVP, the solution to Knapsack with repetition is like below:

K(0)=0
for w=1 to W:
    K(w) = max{K(w - w_i) + v_i, w_i < w}
return K(W)

Here, W is the capacity; w_i is the weight of item i; v_i is the value of item i; K(w) is the max value achievable with knapsack of capacity w.

Your solution seems like 0-1 Knapsack though.


来源: stackexchange

问:
Prime factorization of a number
I'm trying to write a program to find all the prime factors of a given number, and tried the following:

```<code>def factors(nr):
    i = 2
    factors = []
    while i<nr:
        if (nr%i)==0:
            factors.append(i)
            nr = nr/i
        else:
            i = i+1
    return factors
</code>```

My idea is the following. Start with i = 2, while i < the number, check if the module of the number and i = 0. If this is the case, add i to a list, and run the algorithm again, but now with the new number. However, my algorithm doesn't work. Any idea why?

I know that several right answers are posted on the site, but I would like to know why my program is incorrect.

Update
So if I let the programm run for example:

factors(38), yields [2].

factors(25), yields [5].

So it stops after it has added one number to the list.

答:
The simplest change you can make to fix your problem is to change your while loop condition:

```<code>def factors(nr):
    i = 2
    factors = []
    while i <= nr:
        if (nr % i) == 0:
            factors.append(i)
            nr = nr / i
        else:
            i = i + 1
    return factors

print factors(8)
print factors(9)
print factors(10)
</code>```

Output

```<code>[2, 2, 2]
[3, 3]
[2, 5]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Prime factorization of a number

Body:
I'm trying to write a program to find all the prime factors of a given number, and tried the following:

def factors(nr):
    i = 2
    factors = []
    while i<nr:
        if (nr%i)==0:
            factors.append(i)
            nr = nr/i
        else:
            i = i+1
    return factors

My idea is the following. Start with i = 2, while i < the number, check if the module of the number and i = 0. If this is the case, add i to a list, and run the algorithm again, but now with the new number. However, my algorithm doesn't work. Any idea why?

I know that several right answers are posted on the site, but I would like to know why my program is incorrect.

Update
So if I let the programm run for example:

factors(38), yields [2].

factors(25), yields [5].

So it stops after it has added one number to the list.

Body:
The simplest change you can make to fix your problem is to change your while loop condition:

def factors(nr):
    i = 2
    factors = []
    while i <= nr:
        if (nr % i) == 0:
            factors.append(i)
            nr = nr / i
        else:
            i = i + 1
    return factors

print factors(8)
print factors(9)
print factors(10)

Output

[2, 2, 2]
[3, 3]
[2, 5]


问:
How to get nodeType using jquery
I want to get nodeType and then compare it to where it is text node or element node.</p>

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
    var mm= $('.jj')
    alert(mm.nodeValue)
    })
</script>
</head>
<body>
<div class="jj">value</div>
</body>
</code>```

答:
As noted above, $('.jj').get(0).nodeType works.

Same as $('.jj').first().nodeType

or $('.jj').prop('nodeType')

.prop() : Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

Title: How to get nodeType using jquery

Body:
I want to get nodeType and then compare it to where it is text node or element node.

value


问:
Cannot find module "script!foundation-sites/dist/foundation.min.js on Heroic
These are the contents of webpack.config.js file

```<code>var webpack = require('webpack');
var path = require('path');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
module.exports =  {
  entry: [
  'script!jquery/dist/jquery.min.js',
  'script!foundation-sites/dist/foundation.min.js',
  './app/app.jsx'
  ],
  externals:{
    jquery: 'jQuery'
  },
  plugins:[
  new webpack.ProvidePlugin({
    '$': 'jquery',
    'jQuery': 'jquery'
  }),
  new webpack.optimize.UglifyJsPlugin({
    compressor: {
      warnings: false
    }
  })
  ],

  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  resolve:{
    root: __dirname,
    modulesDirectories: [
    'node_modules',
    './app/components',
    './app/api'
    ],
    alias: {
        app: 'app',
        applicationStyles:'app/styles/app.scss',
        actions:'app/actions/actions.jsx',
        reducers:'app/reducers/reducers.jsx',
        configureStore:'app/store/configureStore.jsx'

      },
    extensions: ['','.js',['.jsx']]
  },
  module:{
    loaders: [
    {
      loader: 'babel-loader',
      query: {
        presets: ['react','es2015','stage-0']
      },
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/
    }
      ]
  },
  sassLoader:{
    includePaths:[
    path.resolve(__dirname,'./node_modules/foundation-sites/scss')
    ]
  },
  devtool: process.env.NODE_ENV === 'production' ? undefined : 'inline-source-map'
};
</code>```

and these are the contents of package.json file

```<code>{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "Simple react app",
  "main": "index.js",
  "scripts": {
    "test": "NODE_ENV=test karma start",
    "build":"webpack",
    "start": "npm run build && node server.js"
  },
  "author": "varun",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.15.3",
    "express": "^4.14.0",
    "firebase": "^3.0.2",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-router": "^2.0.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.16.0",
    "css-loader": "^0.23.1",
    "deep-freeze-strict": "^1.1.1",
    "expect": "^1.14.0",
    "foundation-sites": "^6.2.0",
    "jquery": "^2.2.1",
    "moment": "^2.12.0",
    "node-sass": "^3.13.0",
    "node-uuid": "^1.4.7",
    "react-addons-test-utils": "^0.14.7",
    "react-redux": "^4.4.1",
    "redux": "^3.3.1",
    "redux-mock-store": "^1.0.3",
    "redux-thunk": "^2.1.0",
    "sass-loader": "^4.0.2",
    "script-loader": "^0.6.1",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.13"
  },
  "devDependencies": {

    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.2",
    "karma-mocha": "^0.2.2",
    "karma-mocha-reporter": "^2.0.0",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^1.7.0",
    "mocha": "^2.4.5"

  }
}
</code>```

When I deploy this app to heroku and open the app using the command 'heroku open', I get the following error

Error: Cannot find module "script!foundation-sites/dist/foundation.min.js"

Would be great if anyone could point out what is wrong here. Cant seem to get around this one.
PS. The app works perfectly when I run it locally

答:
In webpack.config.js file,  you need to change the path as following .

```<code>module.exports =  {
     entry: ['script!jquery/dist/jquery.min.js',
     'script!foundation-sites/dist/js/foundation.min.js',
     './app/app.jsx'
        ]
 }
</code>```

same path you can assign for app.jsx for CSS

```<code>require('style!css!foundation-sites/dist/css/foundation.min.css');
</code>```

Body:
These are the contents of webpack.config.js file

var webpack = require('webpack');
var path = require('path');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
module.exports =  {
  entry: [
  'script!jquery/dist/jquery.min.js',
  'script!foundation-sites/dist/foundation.min.js',
  './app/app.jsx'
  ],
  externals:{
    jquery: 'jQuery'
  },
  plugins:[
  new webpack.ProvidePlugin({
    '$': 'jquery',
    'jQuery': 'jquery'
  }),
  new webpack.optimize.UglifyJsPlugin({
    compressor: {
      warnings: false
    }
  })
  ],

  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  resolve:{
    root: __dirname,
    modulesDirectories: [
    'node_modules',
    './app/components',
    './app/api'
    ],
    alias: {
        app: 'app',
        applicationStyles:'app/styles/app.scss',
        actions:'app/actions/actions.jsx',
        reducers:'app/reducers/reducers.jsx',
        configureStore:'app/store/configureStore.jsx'

      },
    extensions: ['','.js',['.jsx']]
  },
  module:{
    loaders: [
    {
      loader: 'babel-loader',
      query: {
        presets: ['react','es2015','stage-0']
      },
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/
    }
      ]
  },
  sassLoader:{
    includePaths:[
    path.resolve(__dirname,'./node_modules/foundation-sites/scss')
    ]
  },
  devtool: process.env.NODE_ENV === 'production' ? undefined : 'inline-source-map'
};

and these are the contents of package.json file

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "Simple react app",
  "main": "index.js",
  "scripts": {
    "test": "NODE_ENV=test karma start",
    "build":"webpack",
    "start": "npm run build && node server.js"
  },
  "author": "varun",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.15.3",
    "express": "^4.14.0",
    "firebase": "^3.0.2",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-router": "^2.0.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.16.0",
    "css-loader": "^0.23.1",
    "deep-freeze-strict": "^1.1.1",
    "expect": "^1.14.0",
    "foundation-sites": "^6.2.0",
    "jquery": "^2.2.1",
    "moment": "^2.12.0",
    "node-sass": "^3.13.0",
    "node-uuid": "^1.4.7",
    "react-addons-test-utils": "^0.14.7",
    "react-redux": "^4.4.1",
    "redux": "^3.3.1",
    "redux-mock-store": "^1.0.3",
    "redux-thunk": "^2.1.0",
    "sass-loader": "^4.0.2",
    "script-loader": "^0.6.1",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.13"
  },
  "devDependencies": {

    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.2",
    "karma-mocha": "^0.2.2",
    "karma-mocha-reporter": "^2.0.0",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^1.7.0",
    "mocha": "^2.4.5"

  }
}

When I deploy this app to heroku and open the app using the command 'heroku open', I get the following error

Error: Cannot find module "script!foundation-sites/dist/foundation.min.js"

Would be great if anyone could point out what is wrong here. Cant seem to get around this one.
PS. The app works perfectly when I run it locally

Body:
In webpack.config.js file,  you need to change the path as following .

module.exports =  {
     entry: ['script!jquery/dist/jquery.min.js',
     'script!foundation-sites/dist/js/foundation.min.js',
     './app/app.jsx'
        ]
 }

same path you can assign for app.jsx for CSS

require('style!css!foundation-sites/dist/css/foundation.min.css');


问:
AIML and python3
Hey I just started looking into programming Chatbots with python3 is there an interpreter for AIML files for python3. I tried looking in pip but I can only find it supported for python 2?</p>

答: You can use https://github.com/weddige/pyaiml3 to enable AIML interpreter in python 3. I have tested it in python3.5.2 and it worked.</p>

Title: AIML and python3


问:
Use movement vector to detect impact in 2D field
Given a coordinate and a movement vector. How can I get the list of all blocks will be infected?

I think it's a little bit like "object in view" or "object collision"?

For example, the original point O is (2, 2), the movement vector "→" is (0, 1) and the blocks B should be [(1, 3), (1, 4), (2, 4), (3, 3), (3, 4)]

```<code> 0123 y→
0.......
1...BB..
2..O→B..
3...BB..
x.......
↓.......
</code>```

If the movement vector is (-1, 1), the B should be [(0, 2), (0, 3), (0, 4), (1, 4), (2, 4)]

```<code> 0123 y→
0..BBB..
1...↗B..
2..O.B..
3.......
x.......
↓.......
</code>```

I'm currently considering

```<code>point P (x, y) vector V (v, u)
x' = x + v
y' = y + u
set S = ([x'-1, x'+1], [y'-1, y'+1])
calculate a line L "y=ax+b" perpendicular to V crossing (x', y').
split S into two groups by L
chose the one V is facing
</code>```

but I cannot find a way to achieve last two steps.

Any suggestion will be helpful.

答:
I think what you are looking for is something called time-until-impact or time-until-collision or something like that.

But in most game engines this is not the way to go. What a standard technique for collision handling is, is space partitioning. That means, if you have n rigid bodies in your simulation then a naive algorithm requires n^2 checks (each with another) to see if a collision happened. However, performance-wise this is a killer. Instead you should partition your space via (`uniform partitioning, Oct-Trees, Z-ordering, etc.), then you only check with neighboring rigid bodies that are neighbors with the cell in question.

Note, that the velocity vector (what you call movement) vector is not really needed here because in practice it brings no benefits.

Body:
Given a coordinate and a movement vector. How can I get the list of all blocks will be infected?

I think it's a little bit like "object in view" or "object collision"?

For example, the original point O is (2, 2), the movement vector "→" is (0, 1) and the blocks B should be [(1, 3), (1, 4), (2, 4), (3, 3), (3, 4)]

 0123 y→
0.......
1...BB..
2..O→B..
3...BB..
x.......
↓.......

If the movement vector is (-1, 1), the B should be [(0, 2), (0, 3), (0, 4), (1, 4), (2, 4)]

 0123 y→
0..BBB..
1...↗B..
2..O.B..
3.......
x.......
↓.......

I'm currently considering

point P (x, y) vector V (v, u)
x' = x + v
y' = y + u
set S = ([x'-1, x'+1], [y'-1, y'+1])
calculate a line L "y=ax+b" perpendicular to V crossing (x', y').
split S into two groups by L
chose the one V is facing

but I cannot find a way to achieve last two steps.

Any suggestion will be helpful.


问:
php insert to mysql issue
I have an issue inserting data to table in php,the problem I am facing maybe it is not difficult to solve but Im new in php development and could not solve it, here is my code

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

<input type = "text" class = "form-control"
               name = "Quantity" id="QTY">
QTY

<input type = "text" class = "form-control"
                             name = "Type" id="type">
type

<input type = "text" class = "form-control"
               name = "price" id="prs">
price

<input type="file" name="fileToUpload" id="fileToUpload">
image

      <input type="submit" value="Submit1" name="Submit1">
Register

         <?php

   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   if (isset($_post('Submit1')))
   {
   $name=filter_input(INPUT_POST,'name');
   $QTY=filter_input(INPUT_POST,'Quantity');
   $type=filter_input(INPUT_POST,'Type');
   $sql = "INSERT INTO products (ProductName, Quantity,Price)
    VALUES ('$name','$QTY','$type')";

//('$_POST['name']','$_POST['Quantity']','$_POST['Type']')";
   mysql_select_db('pharmacynew');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not enter data: ' . mysql_error());
   }

   echo "Entered data successfully\n";

   mysql_close($conn);
}       // put your code here
        ?>

```

the problem Iam facing when I run the page ,it shows me this error
"Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) "
Can any body tell me why is this problem appearing and how to overcome it,
many thanks

答:
The problem is in this line:

```<code>if (isset($_post('Submit1')))
</code>```

By using regular brackets ( and ) you're trying to use $_post as a function instead of a variable. That's not allowed within isset().

You need to use angled brackets [ and ] to read values from the $_post array (which should be $_POST in uppercase, by the way).

Simply change that line to

```<code>if (isset($_POST["Submit1"]))
</code>```

Title: php insert to mysql issue

Body:
I have an issue inserting data to table in php,the problem I am facing maybe it is not difficult to solve but Im new in php development and could not solve it, here is my code

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

<input type = "text" class = "form-control"
               name = "Quantity" id="QTY">
QTY

<input type = "text" class = "form-control"
                             name = "Type" id="type">
type

<input type = "text" class = "form-control"
               name = "price" id="prs">
price

<input type="file" name="fileToUpload" id="fileToUpload">
image

      <input type="submit" value="Submit1" name="Submit1">
Register

         <?php

   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   if (isset($_post('Submit1')))
   {
   $name=filter_input(INPUT_POST,'name');
   $QTY=filter_input(INPUT_POST,'Quantity');
   $type=filter_input(INPUT_POST,'Type');
   $sql = "INSERT INTO products (ProductName, Quantity,Price)
    VALUES ('$name','$QTY','$type')";

//('$_POST['name']','$_POST['Quantity']','$_POST['Type']')";
   mysql_select_db('pharmacynew');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not enter data: ' . mysql_error());
   }

   echo "Entered data successfully\n";

   mysql_close($conn);
}       // put your code here
        ?>

the problem Iam facing when I run the page ,it shows me this error
"Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) "
Can any body tell me why is this problem appearing and how to overcome it,
many thanks

Body:
The problem is in this line:

if (isset($_post('Submit1')))

By using regular brackets ( and ) you're trying to use $_post as a function instead of a variable. That's not allowed within isset().

You need to use angled brackets [ and ] to read values from the $_post array (which should be $_POST in uppercase, by the way).

Simply change that line to

if (isset($_POST["Submit1"]))


问:
Xcode Storyboards - iPhone 7 Plus has no status bar?
Why does the iPhone 7 Plus storyboard have no Status Bar visible in Xcode where as the other sizes do (iPhone 7, 5s). When running the app in the iPhone 7 Plus it has a status bar but on the storyboard it doesn't?

iPhone 7 Plus and has no status bar:

iPhone 7 storyboard that has status bar:

答: So, uninstalling Xcode and reinstalling it has fixed this issue </p>


问:
Create Vec<String> from literal
I want to do

```<code>fn main() {
    let options: Vec<String> = vec!["a", "b", "c"].map(|s| s.to_owned()).collect();
}
</code>```

because this seems like the easiest way to get a vector of owned Strings, but I get hit with this error:

error: no method named `map` found for type `std::vec::Vec<&str>` in the current scope
...
note: the method `map` exists but the following trait bounds were not satisfied:
`std::vec::Vec<&str> : std::iter::Iterator`, `[&str] : std::iter::Iterator`
```

I don't see where the need for the [&str] : std::iter::Iterator bound comes from. if you ignore the part with split_whitespace I'm basically doing what answers on this question recommend.

How should I be generating this vector?

答:
if you ignore the part with split_whitespace

Yes, except you cannot ignore this part. The docs for split_whitespace state (emphasis mine):

The iterator returned

split_whitespace returns an iterator over the pieces of the string that were separated by whitespace, and map is a method on Iterator.

A Vec is not an iterator. You can see that Vec does not implement it's own map method:

no method named map found for type std::vec::Vec<&str>

And the compiler tries to suggest what you might have meant, but weren't quite achieving:

note: the method map exists but the following trait bounds were not satisfied:

You can get an iterator from a Vec by calling Vec::iter or into_iter:

```<code>fn main() {
    let options: Vec<String> = vec!["a", "b", "c"].into_iter().map(|s| s.to_owned()).collect();
}
</code>```

However, there's no need to allocate two vectors here, an array and a vector is more efficient:

```<code>let options: Vec<_> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
</code>```

An iterator over a slice returns references (&T) to the elements in the slice. Since each element is already a &str, the type of s is a &&str. Calling to_owned on a reference to a reference simply clones the reference. You could also have said .map(|&s| s.to_owned()), which dereferences the value once, producing a &str. Calling to_owned on a &str allocates a String.

Title: Create Vec<String> from literal

Body:
I want to do

fn main() {
    let options: Vec<String> = vec!["a", "b", "c"].map(|s| s.to_owned()).collect();
}

because this seems like the easiest way to get a vector of owned Strings, but I get hit with this error:

error: no method named `map` found for type `std::vec::Vec<&str>` in the current scope
...
note: the method `map` exists but the following trait bounds were not satisfied:
`std::vec::Vec<&str> : std::iter::Iterator`, `[&str] : std::iter::Iterator`

I don't see where the need for the [&str] : std::iter::Iterator bound comes from. if you ignore the part with split_whitespace I'm basically doing what answers on this question recommend.

How should I be generating this vector?

Body:
if you ignore the part with split_whitespace

Yes, except you cannot ignore this part. The docs for split_whitespace state (emphasis mine):

The iterator returned

split_whitespace returns an iterator over the pieces of the string that were separated by whitespace, and map is a method on Iterator.

A Vec is not an iterator. You can see that Vec does not implement it's own map method:

no method named map found for type std::vec::Vec<&str>

And the compiler tries to suggest what you might have meant, but weren't quite achieving:

note: the method map exists but the following trait bounds were not satisfied:

You can get an iterator from a Vec by calling Vec::iter or into_iter:

fn main() {
    let options: Vec<String> = vec!["a", "b", "c"].into_iter().map(|s| s.to_owned()).collect();
}

However, there's no need to allocate two vectors here, an array and a vector is more efficient:

let options: Vec<_> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();

An iterator over a slice returns references (&T) to the elements in the slice. Since each element is already a &str, the type of s is a &&str. Calling to_owned on a reference to a reference simply clones the reference. You could also have said .map(|&s| s.to_owned()), which dereferences the value once, producing a &str. Calling to_owned on a &str allocates a String.


问:
How to Run Shell Script at start in VM Virtualbox Ubuntu 16.04
I am trying to run a shell script which runs at system login. To try, I used an example script, which has two lines
   #!/bin/bash
   echo “Hello World”

I Followed all the instructions mentioned on this website http://www.cyberciti.biz/tips/linux-how-to-run-a-command-when-boots-up.html

Even I did some steps such as editing /etc/rc.local, but still when I login, I do not see Hello world output running on terminal.

Can anyone please explain what is wrong here or may be I am missing something?

答:
You can also schedule a cron job to run once after the reboot command.  The line will need "@reboot  root /path/script.sh"  You can specify whatever user you want to run the script.  To make the result easier to find, you might make that second line something like
echo "Hello World" > /root/hello.txt</p>


问:
Plugin Error: required plugin "Android Support" is disabled
I have a plugin error in my logcat

```<code>   10:08:28 PM Plugin Error
        Problems found loading plugins:
        Plugin "Google Analytics Uploader" was not loaded: required plugin "Android Support" is disabled.
        Plugin "SDK Updater" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Android NDK Support" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google App Indexing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Tools For Android Studio" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Testing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Services" was not loaded: required plugin "Android Support" is disabled.
        Disable not loaded plugins
        Enable Android Support
        Open plugin manager
 10:08:32 PM Error Loading Project: Cannot load 3 facets Details...
</code>```

This happened after I left my laptop to sleep and when I opened android studio, this error popped out. Now I cannot run my project.

答:
Open the file c:\users\username.AndroidStudio2.3\config\disabled_plugins.txt

delete the line "org.jetbrains.android"

restart Android Studio

Body:
I have a plugin error in my logcat

   10:08:28 PM Plugin Error
        Problems found loading plugins:
        Plugin "Google Analytics Uploader" was not loaded: required plugin "Android Support" is disabled.
        Plugin "SDK Updater" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Android NDK Support" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google App Indexing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Tools For Android Studio" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Testing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Services" was not loaded: required plugin "Android Support" is disabled.
        Disable not loaded plugins
        Enable Android Support
        Open plugin manager
 10:08:32 PM Error Loading Project: Cannot load 3 facets Details...

This happened after I left my laptop to sleep and when I opened android studio, this error popped out. Now I cannot run my project.


问:
How to horizontally flip images already on the canvas?
Before you throw me out - I am aware of this answer, but it does not seem to work for me. It is also different in that the source of the image data in my case is a WebGL canvas - not an img node.

I am trying to put ImageData onto a canvas like so:

```<code>var c = document.createElement('canvas');
c.setAttribute('width', size.width);
c.setAttribute('height', size.height);

$('body').append(c)

// p contains a Uint8ClampedArray with imagedata coming from a WebGL canvas

var i = new ImageData(p, size.width, size.height);
var ctx = c.getContext('2d');
ctx.putImageData(i, 0, 0);
</code>```

and then to flip it like so:

```<code>var d = document.createElement('canvas');
d.width = c.width; d.height = c.height;
d.getContext('2d').drawImage(c, 0, 0);

ctx.clearRect(0, 0, c.width, c.height);
ctx.scale(-1, 1);
ctx.translate(c.width, 0);

ctx.drawImage(d, 0, 0);
</code>```

but this fails miserably.

The data comes from a WebGL canvas like this:

```<code>var gl = renderer.domElement.getContext("webgl")
var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
</code>```

so I've considered low-level operations on the pixel array as a solution, but before I get into that I thought I'd ask.

I have a hunch that drawImage is insensitive to transforms, but that would be funny. Please please don't make me use toDataURL()

答:
The webGL canvas can be used just like an image. You don't need to use the slow gl.readPixels and ctx.setImageData methods to move the image data

```<code>// where canvasGL is the webGL canvas and ctx is the 2D  canvas context
ctx.setTransform(1,0,0,-1,0,canvasGL.height);
ctx.drawImage(canvasGL,0,0);
</code>```

Body:
Before you throw me out - I am aware of this answer, but it does not seem to work for me. It is also different in that the source of the image data in my case is a WebGL canvas - not an img node.

I am trying to put ImageData onto a canvas like so:

var c = document.createElement('canvas');
c.setAttribute('width', size.width);
c.setAttribute('height', size.height);

$('body').append(c)

// p contains a Uint8ClampedArray with imagedata coming from a WebGL canvas

var i = new ImageData(p, size.width, size.height);
var ctx = c.getContext('2d');
ctx.putImageData(i, 0, 0);

and then to flip it like so:

var d = document.createElement('canvas');
d.width = c.width; d.height = c.height;
d.getContext('2d').drawImage(c, 0, 0);

ctx.clearRect(0, 0, c.width, c.height);
ctx.scale(-1, 1);
ctx.translate(c.width, 0);

ctx.drawImage(d, 0, 0);

but this fails miserably.

The data comes from a WebGL canvas like this:

var gl = renderer.domElement.getContext("webgl")
var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

so I've considered low-level operations on the pixel array as a solution, but before I get into that I thought I'd ask.

I have a hunch that drawImage is insensitive to transforms, but that would be funny. Please please don't make me use toDataURL()

Body:
The webGL canvas can be used just like an image. You don't need to use the slow gl.readPixels and ctx.setImageData methods to move the image data

// where canvasGL is the webGL canvas and ctx is the 2D  canvas context
ctx.setTransform(1,0,0,-1,0,canvasGL.height);
ctx.drawImage(canvasGL,0,0);


问:
Am I on right path to simplifying php code block?
Fairly new to php and following e commerce tutorials. When exploring a way to resolve a problem I had with a php code block, I came upon a post another person had with the same code block.
https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/
 The post suggested a way to simplify the code.

Original code block:

```<code>   <?php
if (isset($_POST ['pid'])) {
    $pid = $_POST ['pid'];
    $wasFound = false;
    $i = 0;
    if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
        $_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
    }  else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while(list($key,$value)=each($each_item)){
            if ($key== "item_id" && $value == $pid) {
                array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
                $wasFound = true;
            }
        }
    }
    if($wasFound==false) {
        array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
        }
    }
    header("Location: cart.php");
    exit();
}
?>
</code>```

This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.

```<code>if (isset($_POST['pid'])) {
    // add (+1) item to cart
    $pid = (int)$_POST['pid']; // cast as integer
    // valid pids are > 0
    if($pid > 0){
    if(!isset($_SESSION['cart_array'][$pid])){
    // item is not in the cart, add it with quantity = 1
    $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
    } else {
    // item is in the cart, increment quantity
    $_SESSION['cart_array'][$pid]['quantity']++;
    }
    }
    header("location: cart.php");
    exit();
    }
</code>```

To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once.
Edited by PFMaBiSmAd, 27 December 2012 - 02:05 PM.

This is what I am considering adding to the code block:

```<code>if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);

// then use use $comma_seperated in query where needed later in annother code block?
}
</code>```

Am I on the right path?

答:
Seems good to me - maybe you should add an check, if the session contains cart_array. And very important - indent your code! The one your provided isn't very readable..</p>

```<code>if (isset($_POST['pid'])) {
    $pid = (int)$_POST['pid'];
    if($pid > 0){
        if (!isset($_SESSION['cart_array'])) {
            $_SESSION['cart_array'] = [];
        }

        if(!isset($_SESSION['cart_array'][$pid])){
            $_SESSION['cart_array'][$pid] = ["quantity" => 1];
        } else {
            $_SESSION['cart_array'][$pid]['quantity']++;
        }
    }
    header("location: cart.php");
    exit();
}
</code>```

Body:
Fairly new to php and following e commerce tutorials. When exploring a way to resolve a problem I had with a php code block, I came upon a post another person had with the same code block.
https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/
 The post suggested a way to simplify the code.

Original code block:

   <?php
if (isset($_POST ['pid'])) {
    $pid = $_POST ['pid'];
    $wasFound = false;
    $i = 0;
    if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
        $_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
    }  else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while(list($key,$value)=each($each_item)){
            if ($key== "item_id" && $value == $pid) {
                array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
                $wasFound = true;
            }
        }
    }
    if($wasFound==false) {
        array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
        }
    }
    header("Location: cart.php");
    exit();
}
?>

This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.

if (isset($_POST['pid'])) {
    // add (+1) item to cart
    $pid = (int)$_POST['pid']; // cast as integer
    // valid pids are > 0
    if($pid > 0){
    if(!isset($_SESSION['cart_array'][$pid])){
    // item is not in the cart, add it with quantity = 1
    $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
    } else {
    // item is in the cart, increment quantity
    $_SESSION['cart_array'][$pid]['quantity']++;
    }
    }
    header("location: cart.php");
    exit();
    }

To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once.
Edited by PFMaBiSmAd, 27 December 2012 - 02:05 PM.

This is what I am considering adding to the code block:

if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);

// then use use $comma_seperated in query where needed later in annother code block?
}

Am I on the right path?

Body:
Seems good to me - maybe you should add an check, if the session contains cart_array. And very important - indent your code! The one your provided isn't very readable..

if (isset($_POST['pid'])) {
    $pid = (int)$_POST['pid'];
    if($pid > 0){
        if (!isset($_SESSION['cart_array'])) {
            $_SESSION['cart_array'] = [];
        }

        if(!isset($_SESSION['cart_array'][$pid])){
            $_SESSION['cart_array'][$pid] = ["quantity" => 1];
        } else {
            $_SESSION['cart_array'][$pid]['quantity']++;
        }
    }
    header("location: cart.php");
    exit();
}


问:
Removing digits from list elements
I have a list of job titles (12,000 in total) formatted in this way:

Career_List = ['1) ABLE SEAMAN', '2) ABRASIVE GRADER', '3) ABRASIVE GRINDER']

How do I remove the numbers, parentheses, and spaces from the list elements so that I end up with this output:

    Career_List_Updated = ['ABLE SEAMAN', 'ABRASIVE GRADER', 'ABRASIVE GRINDER']

I know that I am unable to simply remove the first three characters because I have more than ten items in my list.

答:
Split each career at the first space; keep the rest of the line.

```<code>Career_List = ['1) ABLE SEAMAN', '2) ABRASIVE GRADER', '3) ABRASIVE GRINDER', '12000) ZEBRA CLEANER']
Career_List_Updated = []

for career in Career_List:
    job = career.split(' ', 1)
    Career_List_Updated.append(job[1])

print Career_List_Updated
</code>```

Output:

```<code>['ABLE SEAMAN', 'ABRASIVE GRADER', 'ABRASIVE GRINDER', 'ZEBRA CLEANER']
</code>```

One-line version:

```<code>Career_List_Updated = [career.split(' ', 1)[1] \
                       for career in Career_List]
</code>```

Title: Removing digits from list elements

Body:
Split each career at the first space; keep the rest of the line.

Career_List = ['1) ABLE SEAMAN', '2) ABRASIVE GRADER', '3) ABRASIVE GRINDER', '12000) ZEBRA CLEANER']
Career_List_Updated = []

for career in Career_List:
    job = career.split(' ', 1)
    Career_List_Updated.append(job[1])

print Career_List_Updated

Output:

['ABLE SEAMAN', 'ABRASIVE GRADER', 'ABRASIVE GRINDER', 'ZEBRA CLEANER']

One-line version:

Career_List_Updated = [career.split(' ', 1)[1] \
                       for career in Career_List]


问:
Display project version in ASP.NET Core 1.0.0 web application
None of what used to work in RC.x helps anymore.

I have tried these:

PlatformServices.Default.Application.ApplicationVersion;

typeof(Controller).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;

Assembly.GetEntryAssembly().GetName().Version.ToString();

They all return 1.0.0.0 instead of 1.0.0-9 which should be after execution of the dotnet publish --version-suffix 9 having this in project.json: "version": "1.0.0-*"

Basically they give me "File version" from the attached picture instead of "Product version" which dotnet publish actually seems to change.

答:
This work for me too:

```<code>@Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion
</code>```

It works with csproj file - either <Version>1.2.3.4, or <VersionPrefix>1.2.3</VersionPrefix>. However the <VersionSuffix> isn't recoganized as this doc says.

Body:
This work for me too:

@Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion

It works with csproj file - either <Version>1.2.3.4, or <VersionPrefix>1.2.3</VersionPrefix>. However the <VersionSuffix> isn't recoganized as this doc says.


问:
Should i be using the uvm_component/object_utils macros
I see a lot of articles which talk about whether you should be using field macros.

General guideline is:

```<code>`uvm_do... macro:
</code>```

Can be used, but try to avoid if you are lazy.

```<code>`uvm_field... macro:
</code>```

Avoid like the plague.

Sure, people also tell not to use

```<code>`uvm_component_param_utils...
`uvm_object_param_utils...
</code>```

But i cannot seem to find what anyone thinks about the

```<code>`uvm_component_utils...
`uvm_object_utils...
</code>```

Should they be avoided? Or they can be used without much issues?

Thanks :)

答:
I always use uvm_field_ and uvm_object_utils/uvm_component_utils macros. They provide a lot of nifty features.

One feature I love: The uvm_component will automatically get the variable for you from the uvm_config_db  if you use uvm_field_* to register it.

For example:

```<code>class myclass extends uvm_component;

bit enable;
`uvm_component_utils_begin(myclass)
  `uvm_field_int(bit, UVM_ALL_ON) // UVM_READ_ONLY wouldn't work for this feature
`uvm_component_utils_end

virtual class build_phase(uvm_phase phase);
  super.build_phase(phase);
endclass

virtual task run_phase(uvm_phase phase);
  if (enable) begin
     // blah blah
  end
endtask

endclass
</code>```

To set bit enable, all you have to do in a class that is at a higher hierarchichal level is uvm_config_db(int)::set(this, "path/to/class", "enable", 1)

There is no need for any "get" in the class itself. Kinda neat...

Body:
I see a lot of articles which talk about whether you should be using field macros.

General guideline is:

`uvm_do... macro:

Can be used, but try to avoid if you are lazy.

`uvm_field... macro:

Avoid like the plague.

Sure, people also tell not to use

`uvm_component_param_utils...
`uvm_object_param_utils...

But i cannot seem to find what anyone thinks about the

`uvm_component_utils...
`uvm_object_utils...

Should they be avoided? Or they can be used without much issues?

Thanks :)

Body:
I always use uvm_field_ and uvm_object_utils/uvm_component_utils macros. They provide a lot of nifty features.

One feature I love: The uvm_component will automatically get the variable for you from the uvm_config_db  if you use uvm_field_* to register it.

For example:

class myclass extends uvm_component;

bit enable;
`uvm_component_utils_begin(myclass)
  `uvm_field_int(bit, UVM_ALL_ON) // UVM_READ_ONLY wouldn't work for this feature
`uvm_component_utils_end

virtual class build_phase(uvm_phase phase);
  super.build_phase(phase);
endclass

virtual task run_phase(uvm_phase phase);
  if (enable) begin
     // blah blah
  end
endtask

endclass

To set bit enable, all you have to do in a class that is at a higher hierarchichal level is uvm_config_db(int)::set(this, "path/to/class", "enable", 1)

There is no need for any "get" in the class itself. Kinda neat...


问:
Plotting aggregate data in R
I have a set of data that consists of 358 rock samples and their densities, p-wave velocities, and rock type (a category from 1-8).

I used the aggregate function to find the mean density for each rock type and mean p-wave velocity for each rock type.

```<code>dens = aggregate(SONIC_TXT$Density_g.cm3, by=list(SONIC_TXT$Rock_type), mean)
vel = aggregate(SONIC_TXT$P.WaveVelocity_km.sec, by=list(SONIC_TXT$Rock_type), mean)
</code>```

I now want to plot the results of these on a scatterplot of the mean density of each rock type vs. mean p-wave velocity of each rock type.

My attempts were returned with errors saying I needed "finite limits". So I added limits to the plot function and got a plot with those limits and no points. I tried ggplot and got no error, but also just a "plot" with no axes/borders/points/anything at all.

Can anyone help me?

Edit: My attempts consisted of:

plot(dens$vel)

Which resulted in:

```<code>    Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
</code>```

plot(dens$vel, xlim = c(0, 50), ylim = c(0,50),ylab ='ylab', xlab='xlab')

Which resulted in:

matplot(dens, cbind(dens$x,vel$x),type="p",col=c("red","green"),pch=16)

Which resulted in: This plot, which is more along the lines of what I was aiming for. Except for the velocity values don't line up with rock type now.

Edit 2:

```<code>> dens2
  Rock_type Density_g.cm3
1         1      2.633226
2         2      2.677167
3         3      2.774167
4         4      2.919500
5         5      2.823643
6         6      2.794964
7         7      3.006226
8         8      3.240798

> vel2
  Rock_type P.WaveVelocity_km.sec
1         1              5.640581
2         2              5.803310
3         3              5.691533
4         4              6.426667
5         5              5.828643
6         6              6.217643
7         7              6.715594
8         8              7.556798
</code>```

答:
In your data, there is no vel in dens2, and dens2 is a data frame, not a vector.  Try this:

```<code>d <- data.frame(dens=dens2$Density_g.cm3, vel2=vel2$P.WaveVelocity_km.sec,
                type=dens2$Rock_type)
windows()
  with(d, plot(dens, vel2, pch=as.character(type)))
</code>```

(See revision history for original answer, which was speculation, and is outdated now that there is a reproducible example.)

Title: Plotting aggregate data in R

Body:
I have a set of data that consists of 358 rock samples and their densities, p-wave velocities, and rock type (a category from 1-8).

I used the aggregate function to find the mean density for each rock type and mean p-wave velocity for each rock type.

dens = aggregate(SONIC_TXT$Density_g.cm3, by=list(SONIC_TXT$Rock_type), mean)
vel = aggregate(SONIC_TXT$P.WaveVelocity_km.sec, by=list(SONIC_TXT$Rock_type), mean)

I now want to plot the results of these on a scatterplot of the mean density of each rock type vs. mean p-wave velocity of each rock type.

My attempts were returned with errors saying I needed "finite limits". So I added limits to the plot function and got a plot with those limits and no points. I tried ggplot and got no error, but also just a "plot" with no axes/borders/points/anything at all.

Can anyone help me?

Edit: My attempts consisted of:

plot(dens$vel)

Which resulted in:

    Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf

plot(dens$vel, xlim = c(0, 50), ylim = c(0,50),ylab ='ylab', xlab='xlab')

Which resulted in:

matplot(dens, cbind(dens$x,vel$x),type="p",col=c("red","green"),pch=16)

Which resulted in: This plot, which is more along the lines of what I was aiming for. Except for the velocity values don't line up with rock type now.

Edit 2:

> dens2
  Rock_type Density_g.cm3
1         1      2.633226
2         2      2.677167
3         3      2.774167
4         4      2.919500
5         5      2.823643
6         6      2.794964
7         7      3.006226
8         8      3.240798

> vel2
  Rock_type P.WaveVelocity_km.sec
1         1              5.640581
2         2              5.803310
3         3              5.691533
4         4              6.426667
5         5              5.828643
6         6              6.217643
7         7              6.715594
8         8              7.556798

Body:
In your data, there is no vel in dens2, and dens2 is a data frame, not a vector.  Try this:

d <- data.frame(dens=dens2$Density_g.cm3, vel2=vel2$P.WaveVelocity_km.sec,
                type=dens2$Rock_type)
windows()
  with(d, plot(dens, vel2, pch=as.character(type)))

(See revision history for original answer, which was speculation, and is outdated now that there is a reproducible example.)


答:
Take advantage of the fact that str.lstrip() and the rest of the strip functions accept multiple characters as an argument.

```<code>Career_List_Updated =[career.lstrip('0123456789) ') for career in Career_List]
</code>```

Title: Removing digits from list elements

Body:
I have a list of job titles (12,000 in total) formatted in this way:

Career_List = ['1) ABLE SEAMAN', '2) ABRASIVE GRADER', '3) ABRASIVE GRINDER']

How do I remove the numbers, parentheses, and spaces from the list elements so that I end up with this output:

    Career_List_Updated = ['ABLE SEAMAN', 'ABRASIVE GRADER', 'ABRASIVE GRINDER']

I know that I am unable to simply remove the first three characters because I have more than ten items in my list.

Body:
Take advantage of the fact that str.lstrip() and the rest of the strip functions accept multiple characters as an argument.

Career_List_Updated =[career.lstrip('0123456789) ') for career in Career_List]


问:
How to get encrypted object data in Amazon S3 - SSE-CPK?

I just begin Amazon S3 for my project. It has nice Server Side Encryption function.

I have used Customer Provide Key to upload/download with my own key.

It's fine. But sometime i need to get raw data (encrypted data) by request without algorithm and key.

But it response error.

So i want to firgure out a way to solve my problem.

Thanks for your help !

答:
Why?  If AWS exposed raw data, it could be used to break encryption.  SSE is not provided to secure data externally to AWS. Exposing raw data puts your customer's keys and data at risk of being compromised by brute force decryption techniques.

Server-side encryption is about data encryption at rest—that is, Amazon S3 encrypts your data at the object level as it writes it to disks in its data centers and decrypts it for you when you access it.

http://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html

Caution

If you lose the encryption key any GET request for an object without its encryption key will fail, and you lose the object.

http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html


问:
How to rewrite a basic action/reducer to use promises
I'm having trouble understanding how to rewrite normal action/reducer code to make use of redux-thunk or redux-promise-middleware so I can use promises.

I want to wait for my updatePhone to finish updating my state.user.information.phone before it starts testUserPhone. So obviously I need a promise to be returned from updatePhone.

this.props.updatePhone('+1**********')
.then(() => this.props.testUserPhone(this.props.user.information.phone))```
</div>
</div>
</p>

<p>action</p>

```export const updatePhone = (phone) => ({
    type: UPDATE_PHONE,
    payload: phone
})
```

<p>and reducer</p>

```export default (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case 'UPDATE_PHONE':
            return {...state,
                information: {
                    ...state.information,
                    phone: action.payload
                }
            }
        default:
            return state
    }
}
```

<hr>

<p>Should I write something like this as well as the basic function, or can I somehow combine them into one? Because I need the action to fully complete its cycle through my reducer and update <code>phone</code> before it comes back, but I don't want to break my reducer because now it won't be able to access <code>payload</code> and such since it's inside of a returned function -- super confused with how you start off using these libraries.</p>

```export function updatePhoneAsync(phone) {
    return dispatch({
        type: UPDATE_PHONE,
        payload: phone
    })
}
```

<hr>

<p>EDIT: So I've got this now for my action creators</p>

```export const updatePhone = (phone) => ({
    type: UPDATE_PHONE,
    payload: phone
})

export function updatePhoneAsync(phone) {
    return function (dispatch) {
        dispatch(updatePhone(phone))
    }
}
```

<p>Outside in my component;</p>

```this.props.updatePhoneAsync('+1**********')
.then(() => this.props.testUserPhone(this.props.user.information))
```

Which gives me an error 'cannot read property then of undefined'

答:
You should write something like this if you use redux-thunk:

Action creators:

```<code>function update (params if you need them) {
    return function (dispatch) {
        send request here
            .then(data =>
                dispatch(phoneUpdated(data));
}

function phoneUpdated(phone) {
    return {type: 'PHONE_UPDATED', phone};
}
</code>```

Then, feel free to grab this action in your reducer and update the state as you wish.

Also,  you can enhance it with additional actions in case when promise will be rejected, or at the start of request to show loader animations

Body:
I'm having trouble understanding how to rewrite normal action/reducer code to make use of redux-thunk or redux-promise-middleware so I can use promises.

I want to wait for my updatePhone to finish updating my state.user.information.phone before it starts testUserPhone. So obviously I need a promise to be returned from updatePhone.

this.props.updatePhone('+1**********')
.then(() => this.props.testUserPhone(this.props.user.information.phone))

action

export const updatePhone = (phone) => ({
    type: UPDATE_PHONE,
    payload: phone
})

and reducer

export default (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case 'UPDATE_PHONE':
            return {...state,
                information: {
                    ...state.information,
                    phone: action.payload
                }
            }
        default:
            return state
    }
}

Should I write something like this as well as the basic function, or can I somehow combine them into one? Because I need the action to fully complete its cycle through my reducer and update phone before it comes back, but I don't want to break my reducer because now it won't be able to access payload and such since it's inside of a returned function -- super confused with how you start off using these libraries.

export function updatePhoneAsync(phone) {
    return dispatch({
        type: UPDATE_PHONE,
        payload: phone
    })
}

EDIT: So I've got this now for my action creators

export const updatePhone = (phone) => ({
    type: UPDATE_PHONE,
    payload: phone
})

export function updatePhoneAsync(phone) {
    return function (dispatch) {
        dispatch(updatePhone(phone))
    }
}

Outside in my component;

this.props.updatePhoneAsync('+1**********')
.then(() => this.props.testUserPhone(this.props.user.information))

Which gives me an error 'cannot read property then of undefined'

Body:
You should write something like this if you use redux-thunk:

Action creators:

function update (params if you need them) {
    return function (dispatch) {
        send request here
            .then(data =>
                dispatch(phoneUpdated(data));
}

function phoneUpdated(phone) {
    return {type: 'PHONE_UPDATED', phone};
}

Then, feel free to grab this action in your reducer and update the state as you wish.

Also,  you can enhance it with additional actions in case when promise will be rejected, or at the start of request to show loader animations


问:
How to create an applet project in maven?
What is the best way how to create an applet project in maven?
Is there any archetype that I missed? Or I just need to create regular java project?</p>

答: Just use a normal Java project. You may find the proguard-maven-plugin useful, in order to compress the applet .jar.</p>

ContentLicense: CC BY-SA 2.5


问:
Prediction on Neural Network in R
I want to get the accuracy or the RMSE of the Prediction result of a neural network. I started using a Confusion Matrix, but as indicated by previous answers, the Confusion Matrix gives valid results for non Continuous variables.

Is there any way I can get the accuracy or the error rate of a Neural Network Prediction??

As an example here is the code I've got until now:

```<code>library(nnet)
library(caret)
library(e1071)
data(rock)
newformula <- perm ~ area + peri + shape
y <- rock[, "perm"]
x <- rock[!colnames(rock)%in% "perm"]
original <- datacol(rock,"perm")

nnclas_model <- nnet(newformula, data = rock, size = 4, decay = 0.0001, maxit = 500)
nnclas_prediction <- predict(nnclas_model, x)
nnclas_tab <- table(nnclas_prediction, y)
rmse <- sqrt(mean((original - nnclas_prediction)^2))
</code>```

Does anyone know how can I make this work? or how can I get the Accuracy or the of the Neural Network Prediction?
Any help will be deeply appreciated.

答:
I don't know about "nnet", but I have used the "neuralnet" library and am able to get the RMSE. Here is my full code: Just change the data for training_Data and testing_Data as per your requirements and in place of "Channel" give what is your classification attribute

```<code>  dat <- read.csv("Give path of your data file here")
summary(dat)
cleandata <- dat
cleandata <- na.omit(cleandata)

#scaling

apply(cleandata,MARGIN = 2, FUN = function(x)sum(is.na(x)))
maxs    =   apply(cleandata,    MARGIN  =   2,  max)
mins    =   apply(cleandata,    MARGIN  =   2,  min)
scaledData =     as.data.frame(scale(cleandata, center  =   mins,   scale   =   maxs    - mins))
summary(scaledData)

#Splitting data in 80:20 ratio
train = sample(1:nrow(scaledData), nrow(scaledData)*0.8)
test = -train
training_Data = scaledData[train,]
testing_Data = scaledData[test,]
dim(training_Data)
dim(testing_Data)

#neural net

library(neuralnet)
n   <- names(training_Data)
f   <- as.formula(paste("Channel    ~", paste(n[!n  %in%    "Channel"], collapse    =   "   +   ")))
neuralnet_Model <- neuralnet(f,data = training_Data, hidden = c(2,1))
plot(neuralnet_Model)
neuralnet_Model$result.matrix
pred_neuralnet<-compute(neuralnet_Model,testing_Data[,2:8])
pred_neuralnet.scaled   <- pred_neuralnet$net.result *(max(scaledData$Channel)-min(scaledData$Channel))+min(scaledData$Channel)
real.values <- (testing_Data$Channel)*(max(cleandata$Channel)-min(cleandata$Channel))+min(cleandata$Channel)
MSE.neuralnetModel  <- sum((real.values - pred_neuralnet.scaled)^2)/nrow(testing_Data)
MSE.neuralnetModel
plot(real.values, pred_neuralnet.scaled, col='red',main='Real   vs  predicted',pch=18,cex=0.7)
abline(0,1,lwd=2)
legend('bottomright',legend='NN',pch=18,col='red',  bty='n')
</code>```

Title: Prediction on Neural Network in R

Body:
I want to get the accuracy or the RMSE of the Prediction result of a neural network. I started using a Confusion Matrix, but as indicated by previous answers, the Confusion Matrix gives valid results for non Continuous variables.

Is there any way I can get the accuracy or the error rate of a Neural Network Prediction??

As an example here is the code I've got until now:

library(nnet)
library(caret)
library(e1071)
data(rock)
newformula <- perm ~ area + peri + shape
y <- rock[, "perm"]
x <- rock[!colnames(rock)%in% "perm"]
original <- datacol(rock,"perm")

nnclas_model <- nnet(newformula, data = rock, size = 4, decay = 0.0001, maxit = 500)
nnclas_prediction <- predict(nnclas_model, x)
nnclas_tab <- table(nnclas_prediction, y)
rmse <- sqrt(mean((original - nnclas_prediction)^2))

Does anyone know how can I make this work? or how can I get the Accuracy or the of the Neural Network Prediction?
Any help will be deeply appreciated.

Body:
I don't know about "nnet", but I have used the "neuralnet" library and am able to get the RMSE. Here is my full code: Just change the data for training_Data and testing_Data as per your requirements and in place of "Channel" give what is your classification attribute

  dat <- read.csv("Give path of your data file here")
summary(dat)
cleandata <- dat
cleandata <- na.omit(cleandata)

#scaling

apply(cleandata,MARGIN = 2, FUN = function(x)sum(is.na(x)))
maxs    =   apply(cleandata,    MARGIN  =   2,  max)
mins    =   apply(cleandata,    MARGIN  =   2,  min)
scaledData =     as.data.frame(scale(cleandata, center  =   mins,   scale   =   maxs    - mins))
summary(scaledData)

#Splitting data in 80:20 ratio
train = sample(1:nrow(scaledData), nrow(scaledData)*0.8)
test = -train
training_Data = scaledData[train,]
testing_Data = scaledData[test,]
dim(training_Data)
dim(testing_Data)

#neural net

library(neuralnet)
n   <- names(training_Data)
f   <- as.formula(paste("Channel    ~", paste(n[!n  %in%    "Channel"], collapse    =   "   +   ")))
neuralnet_Model <- neuralnet(f,data = training_Data, hidden = c(2,1))
plot(neuralnet_Model)
neuralnet_Model$result.matrix
pred_neuralnet<-compute(neuralnet_Model,testing_Data[,2:8])
pred_neuralnet.scaled   <- pred_neuralnet$net.result *(max(scaledData$Channel)-min(scaledData$Channel))+min(scaledData$Channel)
real.values <- (testing_Data$Channel)*(max(cleandata$Channel)-min(cleandata$Channel))+min(cleandata$Channel)
MSE.neuralnetModel  <- sum((real.values - pred_neuralnet.scaled)^2)/nrow(testing_Data)
MSE.neuralnetModel
plot(real.values, pred_neuralnet.scaled, col='red',main='Real   vs  predicted',pch=18,cex=0.7)
abline(0,1,lwd=2)
legend('bottomright',legend='NN',pch=18,col='red',  bty='n')


问:
Java selenium grabbing entire html contents of the element
I was wondering if there was a way to get the entire html code between two tags of an element, along with the element tag then store it in a string.

Lets say I use the following to create a list of web elements, then fill the list with all the web elements.

```<code>List<WebElement> element = driver.findElements(By.xpath("//*"));
//Some for loop after this to access each value
</code>```

If I use the following to get the 3rd web element, it prints only the tags name, as it should:

```<code>System.out.println(element.get(3).getTagName());
</code>```

so it prints the paragraph element "p" or "input" for example if it is the 3rd web element stored

But I was wondering if its possible to get the entire html code line for the web element and print it rather then only the tag name "p" for example?

e.g.

```<code><p> some text </p>
</code>```

Is there some way to accomplish this?

答:
You can read outerHTML attribute to get the entire element.

```<code>element.getAttribute("outerHTML");
</code>```

Or in your case:

```<code>System.out.println(element.get(3).getAttribute("outerHTML"));
</code>```

Hope it helps!

Body:
I was wondering if there was a way to get the entire html code between two tags of an element, along with the element tag then store it in a string.

Lets say I use the following to create a list of web elements, then fill the list with all the web elements.

List<WebElement> element = driver.findElements(By.xpath("//*"));
//Some for loop after this to access each value

If I use the following to get the 3rd web element, it prints only the tags name, as it should:

System.out.println(element.get(3).getTagName());

so it prints the paragraph element "p" or "input" for example if it is the 3rd web element stored

But I was wondering if its possible to get the entire html code line for the web element and print it rather then only the tag name "p" for example?

e.g.

 some text

Is there some way to accomplish this?

Body:
You can read outerHTML attribute to get the entire element.

element.getAttribute("outerHTML");

Or in your case:

System.out.println(element.get(3).getAttribute("outerHTML"));

Hope it helps!


问:
How to handle json Exception to prevent app crash?
I am developing a android app which shows the images from URL which returns a json. But my app keeps getting crashed and closed whenever the json returns null value. I also tried something to handle null but am not sure if its right way. Here is my code

```<code>private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(GridActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Fetching Images");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://url.com");
        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("wallpaper");
            if(jsonobject==null) {
                Toast.makeText(GridActivity.this, "error" , Toast.LENGTH_SHORT).show();
            } else{

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    //  map.put("rank", jsonobject.getString("rank"));
                    map.put("category", jsonobject.getString("category"));
                    //   map.put("population", jsonobject.getString("population"));
                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            }
        } catch (JSONException e) {
            Toast.makeText(GridActivity.this,"Error on the response", 3000).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        gridview =(GridView)findViewById(R.id.gridViewCustom);
        // Pass the results into ListViewAdapter.java
        adapter = new GridViewAdapter(GridActivity.this, arraylist);

        button = (Button) findViewById(R.id.button);

        // add button listener
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //Log.v("obj", "Creating view..." + jsonobject);
               // Log.v("arry", "Creating view..." + jsonarray);
                new loadMoreListView().execute();
            }
        });
        // Set the adapter to the ListView
        gridview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();

    }
}
</code>```

Logcat:

07-02 17:38:07.069  11429-11461/com.fbphoto_comments.app E/log_tag﹕ Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

答: you are calling Toast inside doInBackground() , delete toast message. You can not call Toast inside doInBackground</p>

Body:
I am developing a android app which shows the images from URL which returns a json. But my app keeps getting crashed and closed whenever the json returns null value. I also tried something to handle null but am not sure if its right way. Here is my code

private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(GridActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Fetching Images");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://url.com");
        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("wallpaper");
            if(jsonobject==null) {
                Toast.makeText(GridActivity.this, "error" , Toast.LENGTH_SHORT).show();
            } else{

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    //  map.put("rank", jsonobject.getString("rank"));
                    map.put("category", jsonobject.getString("category"));
                    //   map.put("population", jsonobject.getString("population"));
                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            }
        } catch (JSONException e) {
            Toast.makeText(GridActivity.this,"Error on the response", 3000).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        gridview =(GridView)findViewById(R.id.gridViewCustom);
        // Pass the results into ListViewAdapter.java
        adapter = new GridViewAdapter(GridActivity.this, arraylist);

        button = (Button) findViewById(R.id.button);

        // add button listener
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //Log.v("obj", "Creating view..." + jsonobject);
               // Log.v("arry", "Creating view..." + jsonarray);
                new loadMoreListView().execute();
            }
        });
        // Set the adapter to the ListView
        gridview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();

    }
}

Logcat:

07-02 17:38:07.069  11429-11461/com.fbphoto_comments.app E/log_tag﹕ Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject


问:
Cannot Get Route Symfony
As the title say explecitly, I don't manage to get some specific route I recently added.
My symfony version : 2.8.18.
So here are the details :

Route I try to match :
 - /platform/cat
 - /platform/cat/{id}

File - app/config/routing.yml :

```<code>gb_platform:
resource: "@GBPlatformBundle/Resources/config/routing.yml"
prefix:   /platform
</code>```

File - GB\PlatformBundle\Resources\config\routing.yml :

```<code>    gb_platform_home_:
    path :   /
      defaults: { _controller: GBPlatformBundle:Advert:index }

gb_platform_home:
    path :   /{page}
    defaults:
        _controller : GBPlatformBundle:Advert:index
        page: 1
    requirements:
        page: \d*

gb_platform_view:
    path :   /advert/{id}
    defaults: { _controller : GBPlatformBundle:Advert:view }
    requirements:
        id: \d+

gb_platform_add:
    path :   /add
    defaults: { _controller : GBPlatformBundle:Advert:add }

gb_platform_edit:
    path :   /edit/{id}
    defaults: { _controller : GBPlatformBundle:Advert:edit }
    requirements:
        id: \d+

gb_platform_delete:
    path :   /delete/{id}
    defaults: { _controller : GBPlatformBundle:Advert:delete }
    requirements:
        id: \d+

gb_platform_cat:
    path :   /cat
    defaults: { _controller : GBPlatformBundle:Category:index }

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: \d+
</code>```

File - GB\PlatformBundle\Resources\controller\CategoryController.php :

```<code>    <?php

namespace GB\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;

use GB\PlatformBundle\Entity\Advert;
use GB\PlatformBundle\Entity\Category;

class CategoryController extends Controller
{
    public function indexAction(Request $request)
    {

    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $catRepo = $em
            ->getRepository('GBPlatformBundle:Category');
        $cat = $catRepo
            ->find($id);

        if($cat === null)
        {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        return $this->render('GBPlatformBundle:Category:view.html.twig', array(
            'category' => $cat,
            ));
    }
}
</code>```

At the origin, the routing.yml of the bundle was invalid. Once it's fixed, I try to get the both command :

php app/console debug:router

php app/console debug:router gb_platform_cat

php app/console debug:router gb_platform_add

Each command were successfull and I saw no difference between /cat and /add while one match and the other don't.
I tried also many times to clear cache with :

php app/console cache:clear --env prod

Still don't work. I'm confused ...
The error is basic : No route found for "GET /platform/cat/7

答:
I finally get the solution.

First of all be sure of the validity of the routing.yml files.
Additionnaly to usual symfony command (which will advice you of a mistake), you can use a validator like : yamllint.com

In my case, routes config was correct. And I knew symfony could find them thanks to debug:router command and comparing them with other functional routes.

What I noticed, is that even changing the controller of routes that can matched, the update wasn't considered by the system. So obviously, it's a cache problem.

At the really begining I used, to reject this hypothesis, the command :

php app/console cache:clear --env prod

But the problem was more global that the production environnement, so I solved my problem without specifying the env :

php app/console cache:clear

The kind of mistake you do once, but not twice so it's .. ;)

Title: Cannot Get Route Symfony

Body:
As the title say explecitly, I don't manage to get some specific route I recently added.
My symfony version : 2.8.18.
So here are the details :

Route I try to match :
 - /platform/cat
 - /platform/cat/{id}

File - app/config/routing.yml :

gb_platform:
resource: "@GBPlatformBundle/Resources/config/routing.yml"
prefix:   /platform

File - GB\PlatformBundle\Resources\config\routing.yml :

    gb_platform_home_:
    path :   /
      defaults: { _controller: GBPlatformBundle:Advert:index }

gb_platform_home:
    path :   /{page}
    defaults:
        _controller : GBPlatformBundle:Advert:index
        page: 1
    requirements:
        page: \d*

gb_platform_view:
    path :   /advert/{id}
    defaults: { _controller : GBPlatformBundle:Advert:view }
    requirements:
        id: \d+

gb_platform_add:
    path :   /add
    defaults: { _controller : GBPlatformBundle:Advert:add }

gb_platform_edit:
    path :   /edit/{id}
    defaults: { _controller : GBPlatformBundle:Advert:edit }
    requirements:
        id: \d+

gb_platform_delete:
    path :   /delete/{id}
    defaults: { _controller : GBPlatformBundle:Advert:delete }
    requirements:
        id: \d+

gb_platform_cat:
    path :   /cat
    defaults: { _controller : GBPlatformBundle:Category:index }

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: \d+

File - GB\PlatformBundle\Resources\controller\CategoryController.php :

    <?php

namespace GB\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;

use GB\PlatformBundle\Entity\Advert;
use GB\PlatformBundle\Entity\Category;

class CategoryController extends Controller
{
    public function indexAction(Request $request)
    {

    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $catRepo = $em
            ->getRepository('GBPlatformBundle:Category');
        $cat = $catRepo
            ->find($id);

        if($cat === null)
        {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        return $this->render('GBPlatformBundle:Category:view.html.twig', array(
            'category' => $cat,
            ));
    }
}

At the origin, the routing.yml of the bundle was invalid. Once it's fixed, I try to get the both command :

php app/console debug:router

php app/console debug:router gb_platform_cat

php app/console debug:router gb_platform_add

Each command were successfull and I saw no difference between /cat and /add while one match and the other don't.
I tried also many times to clear cache with :

php app/console cache:clear --env prod

Still don't work. I'm confused ...
The error is basic : No route found for "GET /platform/cat/7


问:
Jquery Display JSON data corresponding to multiple options selected
I'm developing a widget that request fares.json via AJAX and populates select options with live data. End users should be able to see the fare total update when they use the widget controls.

JSON Data:

```<code>{
"info": {
    "anytime": "Valid anytime",
    "weekday": "Valid Monday through Friday, 4:00 a.m. - 7:00 p.m. On trains arriving or departing 30th Street Station, Suburban and Jefferson Station",
    "evening_weekend": "Valid weekdays after 7:00 p.m.; all day Saturday, Sunday and major holidays. On trains arriving or departing 30th Street Station, Suburban and Jefferson Station",
    "advance_purchase": "Tickets available for purchase at all SEPTA offices.",
    "onboard_purchase": "Tickets available for purchase from a train conductor aboard SEPTA regional rail trains."
},
"zones": [{
    "name": "CCP/Zone 1",
    "zone": 1,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 4.75
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 6.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 3.75
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 38.00
    }]
}, {
    "name": "Zone 2",
    "zone": 2,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 4.75
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 6.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 3.75
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 45.00
    }]
}, {
    "name": "Zone 3",
    "zone": 3,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 5.75
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 7.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 7.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 54.50
    }]
}, {
    "name": "Zone 4",
    "zone": 4,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 6.50
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 8.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 7.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 62.50
    }]
}, {
    "name": "NJ",
    "zone": 5,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 9.00
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 10.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 9.00
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 10.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 80.00
    }]
}]}
</code>```

My HTML has id's for each place where data should populate.

HTML:

```<code><select id="zone"></select><select id="time"></select>
<form id="radio" class="widget-container--radio">
    <input type="radio" name="purchase" value="advance_purchase"> Station Kiosk<br>
    <input type="radio" name="purchase" value="onboard_purchase"> Onboard<br>
</form>
<form><input type="number" name="firstname" class="widget-container--quantity"><br></form>
<div id="fare-total" class="widget-container--fare"></div>
</code>```

And I wrote a bit of jQuery to get the JSON data and output options. The desired affect is when a option is selected (name, type, purchase, and trip) the fare total will display below in #fare-total. How do I achieve this?

Jquery:

```<code>var $zone = $('#zone');
var $time = $('#time');
var $radio = $('#radio');
var $fareTotal = $('#fare-total');
$.getJSON('fares.json', function(data) {
  $zone.html('');
  $time.html('');
  $radio.html('');
  $fareTotal.html('');
  for (i = 0; i < data['zones'].length; i++) {
    $zone.append('<option class="' + data['zones'][i]['name'] + '">' + data['zones'][i]['name'] + '</option>');
    $time.append('<option>' + data['zones'][i]['fares'][i]['type'] + '</option>');
    $fareTotal.append('<h2 class="">$' + data['zones'][i]['fares'][i]['price'] + '</h2>');
  }
});
</code>```

答:
If the fare data is static, I would advise moving it to a local source or global variable as was suggested by @Barmar.

If the fares change a lot, then AJAX is a better way to go. Here are some suggestions.

Working Example: https://jsfiddle.net/Twisty/vsjn63vy/

Suggested JavaScript

```<code>$(function() {
  var $zone = $('#zone');
  var $time = $('#time');
  var $radio = $('#radio');
  var $fareTotal = $('#fare-total');
  $.getJSON('fares.json', function(data) {
      $zone.html('');
      $time.html('');
      $radio.html('');
      $fareTotal.html('');
      $.each(data.zones, function(i, zone) {
        $zone.append($("<option>", {
          class: zone.name
        }).html(zone.name));
        $time.append($("<option>").html(zone.fares[i].type));
        $fareTotal.append($("<h2>").html(zone.fares[i].price));
      });
    }
  });
});
</code>```

Body:
I'm developing a widget that request fares.json via AJAX and populates select options with live data. End users should be able to see the fare total update when they use the widget controls.

JSON Data:

{
"info": {
    "anytime": "Valid anytime",
    "weekday": "Valid Monday through Friday, 4:00 a.m. - 7:00 p.m. On trains arriving or departing 30th Street Station, Suburban and Jefferson Station",
    "evening_weekend": "Valid weekdays after 7:00 p.m.; all day Saturday, Sunday and major holidays. On trains arriving or departing 30th Street Station, Suburban and Jefferson Station",
    "advance_purchase": "Tickets available for purchase at all SEPTA offices.",
    "onboard_purchase": "Tickets available for purchase from a train conductor aboard SEPTA regional rail trains."
},
"zones": [{
    "name": "CCP/Zone 1",
    "zone": 1,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 4.75
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 6.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 3.75
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 38.00
    }]
}, {
    "name": "Zone 2",
    "zone": 2,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 4.75
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 6.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 3.75
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 45.00
    }]
}, {
    "name": "Zone 3",
    "zone": 3,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 5.75
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 7.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 7.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 54.50
    }]
}, {
    "name": "Zone 4",
    "zone": 4,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 6.50
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 8.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 5.00
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 7.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 62.50
    }]
}, {
    "name": "NJ",
    "zone": 5,
    "fares": [{
        "type": "weekday",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 9.00
    }, {
        "type": "weekday",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 10.00
    }, {
        "type": "evening_weekend",
        "purchase": "advance_purchase",
        "trips": 1,
        "price": 9.00
    }, {
        "type": "evening_weekend",
        "purchase": "onboard_purchase",
        "trips": 1,
        "price": 10.00
    }, {
        "type": "anytime",
        "purchase": "advance_purchase",
        "trips": 10,
        "price": 80.00
    }]
}]}

My HTML has id's for each place where data should populate.

HTML:

<select id="zone"></select><select id="time"></select>
<form id="radio" class="widget-container--radio">
    <input type="radio" name="purchase" value="advance_purchase"> Station Kiosk

    <input type="radio" name="purchase" value="onboard_purchase"> Onboard

</form>
<form><input type="number" name="firstname" class="widget-container--quantity">
</form>

And I wrote a bit of jQuery to get the JSON data and output options. The desired affect is when a option is selected (name, type, purchase, and trip) the fare total will display below in #fare-total. How do I achieve this?

Jquery:

var $zone = $('#zone');
var $time = $('#time');
var $radio = $('#radio');
var $fareTotal = $('#fare-total');
$.getJSON('fares.json', function(data) {
  $zone.html('');
  $time.html('');
  $radio.html('');
  $fareTotal.html('');
  for (i = 0; i < data['zones'].length; i++) {
    $zone.append('<option class="' + data['zones'][i]['name'] + '">' + data['zones'][i]['name'] + '</option>');
    $time.append('<option>' + data['zones'][i]['fares'][i]['type'] + '</option>');
    $fareTotal.append('
$' + data['zones'][i]['fares'][i]['price'] + '
');
  }
});

Body:
If the fare data is static, I would advise moving it to a local source or global variable as was suggested by @Barmar.

If the fares change a lot, then AJAX is a better way to go. Here are some suggestions.

Working Example: https://jsfiddle.net/Twisty/vsjn63vy/

Suggested JavaScript

$(function() {
  var $zone = $('#zone');
  var $time = $('#time');
  var $radio = $('#radio');
  var $fareTotal = $('#fare-total');
  $.getJSON('fares.json', function(data) {
      $zone.html('');
      $time.html('');
      $radio.html('');
      $fareTotal.html('');
      $.each(data.zones, function(i, zone) {
        $zone.append($("<option>", {
          class: zone.name
        }).html(zone.name));
        $time.append($("<option>").html(zone.fares[i].type));
        $fareTotal.append($("<h2>").html(zone.fares[i].price));
      });
    }
  });
});