问:
What value can a Rails route helper have as a parameter?
I'm working on a Rails tutorial and I don't understand the value a route helper can have as parameter.

Why is it correct for the "article_path" to have "article" as its parameter?

```<code><ul id=“articles”>
    <% @articles.each do |article| %>
        <li>
            <%= link_to article.title, article_path(article) %>
        </li>
    <% end %>
</ul>
</code>```

答:
In below route:

```<code>article_path(article)
</code>```

you can pass article as whole object or article.id both are valid.

Body:
I'm working on a Rails tutorial and I don't understand the value a route helper can have as parameter.

Why is it correct for the "article_path" to have "article" as its parameter?

    <% @articles.each do |article| %>

            <%= link_to article.title, article_path(article) %>

    <% end %>

Body:
In below route:

article_path(article)

you can pass article as whole object or article.id both are valid.


来源: stackexchange

问:
How to pass to URLSession.shared.dataTask called in a loop?
I am downloading image from server and when image is downloaded I have to save that image in coredata with id. Here is the code

```<code>for actionDict:JSON in actionData
  {
    if(actionDict["ProtocolImage"].stringValue.isValidURL())
      {
          URLSession.shared.sessionDescription = "\(actionDict["Id"].intValue)"
            URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in
                if data != nil{
                    let image = UIImage(data: data!)
                    if image != nil{
                       ProtocolActionModel.updateValueWhere(id: Int64(URLSession.shared.sessionDescription!)!, key: "protocolImage", value:( UIImagePNGRepresentation(image!)! as NSData))
                    }
                }
            }).resume()
      }
  }
</code>```

(actionDict["Id"].intValue is id associated with image that I want to save in coredata with image but when I save it is always set to last item id of for loop.

actionData is

```<code>{
    data =     (
                {
            CheckDesc = vcnhfgb;
            CheckName = hjnhfnmjh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1487201399293)/";
            Id = 3;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/522cb086-0b0d-4ad9-b5ae-79f6f9a9fbf2.jpg";
            Sorting = "<null>";
        },
                {
            CheckDesc = bfghrthbn;
            CheckName = ddfgb;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167861457)/";
            Id = 71;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png";
            Sorting = 41;
        },
                {
            CheckDesc = bnvbncyh;
            CheckName = nbnyhjhg;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167894280)/";
            Id = 72;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/e4311494-27ad-4d12-958b-68e0c705a94d.png";
            Sorting = 42;
        },
                {
            CheckDesc = hjbnvbytuu;
            CheckName = nmnmhjgh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167918147)/";
            Id = 73;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/15ac0300-8877-4503-8c6d-957b5248e829.png";
            Sorting = 43;
        },
                {
            CheckDesc = "";
            CheckName = tyres;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499172466890)/";
            Id = 74;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "<null>";
            Sorting = 44;
        }
    );
    message = success;
    status = 1;
}
</code>```

reponse

```<code><NSHTTPURLResponse: 0x600000634720> { URL: http://example/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png } { status code: 200, headers {
    "Accept-Ranges" = bytes;
    "Content-Length" = 254882;
    "Content-Type" = "image/png";
    Date = "Wed, 05 Jul 2017 05:31:46 GMT";
    Etag = "\"e09aa43b9f4d21:0\"";
    "Last-Modified" = "Tue, 04 Jul 2017 11:31:01 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-Powered-By" = "ASP.NET";
    "X-Powered-By-Plesk" = PleskWin;
} }
</code>```

Please provide any solution that will solve my problem.

答:
I have not compiled this hope you can get the idea. Assuming URL is unique to ID you can keep it as a key and access it inside the completion handler.</p>

```<code>//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

var keyDictionary = [String: Int]()
for actionDict:JSON in actionData
{
    if(actionDict["ProtocolImage"].stringValue.isValidURL())
    {
        keyDictionary[actionDict["ProtocolImage"].stringValue] = actionDict["Id"].intValue
        URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in
            if data != nil{
                let image = UIImage(data: data!)
                if image != nil{
                    realValue = keyDictionary[response.URL];
                    ProtocolActionModel.updateValueWhere(id: Int64(realvalue!)!, key: "protocolImage", value:( UIImagePNGRepresentation(image!)! as NSData))
                }
            }
        }).resume()
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am downloading image from server and when image is downloaded I have to save that image in coredata with id. Here is the code

for actionDict:JSON in actionData
  {
    if(actionDict["ProtocolImage"].stringValue.isValidURL())
      {
          URLSession.shared.sessionDescription = "\(actionDict["Id"].intValue)"
            URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in
                if data != nil{
                    let image = UIImage(data: data!)
                    if image != nil{
                       ProtocolActionModel.updateValueWhere(id: Int64(URLSession.shared.sessionDescription!)!, key: "protocolImage", value:( UIImagePNGRepresentation(image!)! as NSData))
                    }
                }
            }).resume()
      }
  }

(actionDict["Id"].intValue is id associated with image that I want to save in coredata with image but when I save it is always set to last item id of for loop.

actionData is

{
    data =     (
                {
            CheckDesc = vcnhfgb;
            CheckName = hjnhfnmjh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1487201399293)/";
            Id = 3;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/522cb086-0b0d-4ad9-b5ae-79f6f9a9fbf2.jpg";
            Sorting = "<null>";
        },
                {
            CheckDesc = bfghrthbn;
            CheckName = ddfgb;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167861457)/";
            Id = 71;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png";
            Sorting = 41;
        },
                {
            CheckDesc = bnvbncyh;
            CheckName = nbnyhjhg;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167894280)/";
            Id = 72;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/e4311494-27ad-4d12-958b-68e0c705a94d.png";
            Sorting = 42;
        },
                {
            CheckDesc = hjbnvbytuu;
            CheckName = nmnmhjgh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167918147)/";
            Id = 73;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/15ac0300-8877-4503-8c6d-957b5248e829.png";
            Sorting = 43;
        },
                {
            CheckDesc = "";
            CheckName = tyres;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499172466890)/";
            Id = 74;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "<null>";
            Sorting = 44;
        }
    );
    message = success;
    status = 1;
}

reponse

<NSHTTPURLResponse: 0x600000634720> { URL: http://example/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png } { status code: 200, headers {
    "Accept-Ranges" = bytes;
    "Content-Length" = 254882;
    "Content-Type" = "image/png";
    Date = "Wed, 05 Jul 2017 05:31:46 GMT";
    Etag = "\"e09aa43b9f4d21:0\"";
    "Last-Modified" = "Tue, 04 Jul 2017 11:31:01 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-Powered-By" = "ASP.NET";
    "X-Powered-By-Plesk" = PleskWin;
} }

Please provide any solution that will solve my problem.

Body:
I have not compiled this hope you can get the idea. Assuming URL is unique to ID you can keep it as a key and access it inside the completion handler.

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

var keyDictionary = [String: Int]()
for actionDict:JSON in actionData
{
    if(actionDict["ProtocolImage"].stringValue.isValidURL())
    {
        keyDictionary[actionDict["ProtocolImage"].stringValue] = actionDict["Id"].intValue
        URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in
            if data != nil{
                let image = UIImage(data: data!)
                if image != nil{
                    realValue = keyDictionary[response.URL];
                    ProtocolActionModel.updateValueWhere(id: Int64(realvalue!)!, key: "protocolImage", value:( UIImagePNGRepresentation(image!)! as NSData))
                }
            }
        }).resume()
    }
}


问:
How to make a 'struct' Nullable by definition?
```<code>struct AccountInfo
{
   String Username;
   String Password;
}
</code>```

now if I want to have a Nullable instance I should write:

```<code>Nullable<AccountInfo> myAccount = null;
</code>```

But I want make the struct Nullable by nature and it can be used like this (without use of Nullable<T>):

```<code>AccountInfo myAccount = null;
</code>```

答:
You can't. Struct are considered value types, and by definition can't be null. The easiest way to make it nullable is to make it a reference type.

The answer you need to ask yourself is "Why is this a struct?" and unless you can think of a really solid reason, don't, and make it a class.  The argument about a struct being "faster", is really overblown, as structs aren't necessarily created on the stack (you shouldn't rely on this), and speed "gained" varies on a case by case basis.

See the post by Eric Lippert on the class vs. struct debate and speed.

ContentLicense: CC BY-SA 2.5

Body:
struct AccountInfo
{
   String Username;
   String Password;
}

now if I want to have a Nullable instance I should write:

Nullable<AccountInfo> myAccount = null;

But I want make the struct Nullable by nature and it can be used like this (without use of Nullable<T>):

AccountInfo myAccount = null;


问:
Errors with ES2015 transpiling; static proptypes, display names; configuring webpack, babel
JS newb here:

I've spent a couple days on this bug, and I've looked at many answers and practiced my most earnest Google-Fu, and tried many different babel plugins and presets configurations, as well as tried migrating my webpack 1 project into a webpack 2 incarnation, and in the end I'm still hitting the same wall. Please give me an assist.

When I try to build my project, all open sourced here, and most recently active and relevant to this question in the webpack2migration branch, I've been unable to build for production (and not even dev after futzing more and more with it through unproductive debugging)

This is the error I haven't gotten around, admittedly because I don't understand some (maybe many) of the complexities in webpack and how babel is to be correctly configured for what I'm struggling with.

Here's the error:

```<code>ERROR in ../~/react-google-maps/src/lib/async/withScriptjs.js
Module parse failed: /Users/sg/Desktop/blog-home/node_modules/react-google-maps/src/lib/async/withScriptjs.js Unexpected token (19:23)
You may need an appropriate loader to handle this file type.
| export default function withScriptjs(WrappedComponent) {
|   return class Container extends Component {
|     static displayName = `withScriptjs(${getDisplayName(WrappedComponent)})`;
|
|  static propTypes = {
</code>```

Initially, I thought this was a bug with react-google-maps, but I suspect it is something different now. I have encountered this kind of bug once before a few months ago within a different project, and I know I've been mostly making a mess of my package.json.

Yes, I know there are many silly problems in there, like package duplications, unused packages, unnecessary dependencies... I've been hitting every angle I can think of, too hard and with not enough care towards cleanup yet; I'm asking for help before getting some sleep and trying yet again in the morning.

The project was to integrate a working small frontend game I'm prototyping, and I wanted to integrate it into my homepage, which I'm also beginning another sweep to clean up and refactor, for better presentation and code quality.

I humbly ask for some supportive help in configuring my build correctly where I obviously am having a lot of trouble.

When I began to integrate the little game into my home page, the build worked perfectly on my local machine in both development and production build configurations, but when I pushed my changes and triggered a build to my heroku host site it kept failing on this same file, I suppose because it can't parse it.

I hope that is enough to go on, and I'll be happy to help narrow this down as needed. :)

Best regards, and thanks for your time!

package.json

```<code>{
  "name": "react-sg-home-page",
  "version": "0.0.9",
  "description": "My home page and portfolio site",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+ssh://git@github.com/sgoldens/home.git"
  },
  "jest": {
    "verbose": true,
    "collectCoverage": true,
    "setupTestFrameworkScriptFile": "mock-local-storage"
  },
  "config": {
    "blanket": {
      "pattern": [
        ""
      ],
      "data-cover-never": [
        "node_modules",
        "__tests__",
        "*.spec.*"
      ]
    }
  },
  "engines": {
    "node": "7.7.4"
  },
  "scripts": {
    "buildcolors": "NODE_ENV=production webpack --config ./webpack.config.js --progress --colors",
    "start_nf": "nf start",
    "istanbul": "istanbul cover ./node_modules/mocha/bin/_mocha -- --reporter dot --full-trace __tests__",
    "lint:watch": "npm run lint -- --watch",
    "mochatest": "babel-node ./node_modules/.bin/isparta cover _mocha --require blanket -- --reporter dot --full-trace __tests__",
    "postinstall": "webpack -p --config ./webpack.config.js",
    "remove-public": "rm -rf ./public",
    "test": "jest --coverage",
    "test:watch": "npm test -- --watch",
    "start_prod": "node server.js",
    "start": "webpack-dev-server",
    "dev": "webpack-dashboard -t 'Marvin' -- webpack-dev-server",
    "build": "babel-node tools/build.js && babel-node tools/buildHtml.js",
    "lint-break-on-errors": "eslint ./source/js ./webpack.config.js -f table --ext .js --ext .jsx",
    "lint": "eslint ./source/js ./webpack.config.js -f table --ext .js --ext .jsx || true",
    "preview": "rm -rf ./build && NODE_ENV=\"production\" webpack-dashboard -t 'Preview Mode - Marvin' -- webpack-dev-server",
    "hook-add": "prepush install",
    "hook-remove": "prepush remove",
    "heroku-prebuild": "npm run remove-public && mkdir public",
    "heroku-postinstall": "node server.js"
  },
  "author": "Sasha Goldenson",
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^6.5.3",
    "babel-core": "^6.7.2",
    "babel-eslint": "^7.1.0",
    "babel-jest": "^19.0.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-syntax-decorators": "^6.13.0",
    "babel-plugin-transform-class-properties": "^6.6.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.6.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-stage-0": "^6.16.0",
    "babel-runtime": "^6.6.1",
    "chai": "3.5.0",
    "chai-jquery": "^2.0.0",
    "css-loader": "^0.28.0",
    "enzyme": "2.6.0",
    "eslint": "^3.10.1",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-config-google": "^0.7.1",
    "eslint-config-standard": "^10.2.1",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-node": "^4.2.2",
    "eslint-plugin-promise": "^3.5.0",
    "eslint-plugin-react": "^6.10.0",
    "eslint-plugin-standard": "^3.0.1",
    "eslint-watch": "2.1.11",
    "expect": "^1.19.0",
    "factory-girl": "^4.2.2",
    "isparta": "^4.0.0",
    "istanbul": "^1.0.0-alpha.2",
    "jasmine-core": "^2.6.1",
    "jest": "17.0.3",
    "jest-cli": "*",
    "karma": "^1.6.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-firefox-launcher": "^1.0.1",
    "karma-jasmine": "^1.1.0",
    "karma-safari-launcher": "^1.0.0",
    "mocha": "3.1.2",
    "mocha-lcov-reporter": "^1.3.0",
    "mock-local-storage": "^1.0.2",
    "nock": "^8.0.0",
    "react-addons-test-utils": "^15.4.0",
    "redux-mock-store": "^1.2.3",
    "standard": "^10.0.2",
    "webpack-dev-middleware": "1.6.1",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "babel-cli": "^6.24.0",
    "babel-core": "^6.24.0",
    "babel-es6-polyfill": "^1.1.0",
    "babel-loader": "^6.4.1",
    "babel-plugin-class-display-name": "^2.1.0",
    "babel-plugin-lodash": "^3.2.11",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-syntax-decorators": "^6.13.0",
    "babel-plugin-transform-async-to-generator": "^6.22.0",
    "babel-plugin-transform-class-display-name": "^0.0.3",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-es2015-classes": "6.18.0",
    "babel-plugin-transform-es2015-template-literals": "^6.22.0",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-plugin-transform-react-constant-elements": "^6.23.0",
    "babel-plugin-transform-react-display-name": "^6.25.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.3.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.23.0",
    "babel-preset-babili": "0.0.12",
    "babel-preset-env": "^1.2.2",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-es2016": "^6.22.0",
    "babel-preset-latest": "^6.24.0",
    "babel-preset-modern-async": "^1.0.0-alpha.3",
    "babel-preset-modern-browsers": "^9.0.2",
    "babel-preset-react": "^6.1.18",
    "babel-preset-stage-0": "^6.22.0",
    "babel-preset-stage-1": "^6.1.18",
    "babel-register": "^6.24.1",
    "babel-relay-plugin-loader": "^0.10.0",
    "babili-webpack-plugin": "0.0.11",
    "blanket": "^1.2.3",
    "bluebird": "^3.1.2",
    "bootstrap": "^3.3.7",
    "cheerio": "^0.20.0",
    "colors": "1.1.2",
    "compression": "^1.6.1",
    "coveralls": "^2.12.0",
    "css-loader": "^0.28.4",
    "es6-promise": "^3.3.1",
    "eventsource-polyfill": "0.9.6",
    "express": "~4.9.8",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.11.1",
    "font-awesome": "^4.7.0",
    "foreman": "2.0.0",
    "get-env": "^0.5.10",
    "history": "^4.6.3",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.24.1",
    "image-webpack-loader": "^3.3.0",
    "immutability-helper": "^2.2.2",
    "immutable": "^3.8.1",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.2.1",
    "json-loader": "^0.5.4",
    "lodash-webpack-plugin": "^0.11.2",
    "lodash.debounce": "^4.0.8",
    "material-ui": "^0.16.0-rc2",
    "node-sass": "^3.13.0",
    "npm-run-all": "^1.8.0",
    "open": "0.0.5",
    "postcss-loader": "^1.1.1",
    "prepush": "^3.1.11",
    "prop-types": "^15.5.10",
    "react": "^15.6.0",
    "react-addons-css-transition-group": "^15.6.0",
    "react-addons-update": "^15.6.0",
    "react-bootstrap": "^0.30.7",
    "react-display-name": "^0.2.0",
    "react-dom": "15.6.1",
    "react-google-maps": "^7.0.0",
    "react-icons": "^2.2.5",
    "react-lazy-cache": "^3.0.1",
    "react-logo": "^1.0.8",
    "react-modal": "1.5.2",
    "react-mui-speeddial": "0.0.6",
    "react-pure-render": "^1.0.2",
    "react-redux": "^4.4.6",
    "react-router-bootstrap": "^0.23.1",
    "react-router-dom": "next",
    "react-rte": "^0.11.0",
    "react-rte-image": "^0.11.1",
    "react-rte-material": "^0.12.5",
    "react-tap-event-plugin": "*",
    "react-tooltip": "3.2.2",
    "react-transform-catch-errors": "^1.0.2",
    "react-transform-hmr": "^1.0.4",
    "redbox-react": "^1.3.4",
    "redux": "^3.0.4",
    "redux-devtools": "^3.3.2",
    "redux-devtools-dock-monitor": "^1.1.1",
    "redux-devtools-extension": "^2.13.0",
    "redux-devtools-log-monitor": "^1.2.0",
    "redux-form": "6.6.1",
    "redux-form-material-ui": "^4.1.3",
    "redux-logger": "^3.0.0",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.2.0",
    "regenerator-runtime": "^0.10.3",
    "reinstall": "^1.1.1",
    "reselect": "^3.0.0",
    "rimraf": "^2.5.2",
    "sass-loader": "^4.0.2",
    "serve-favicon": "^2.3.0",
    "sinon": "1.17.6",
    "style-loader": "0.13.1",
    "svg-react-loader": "^0.3.7",
    "svg-sprite-loader": "^2.1.0",
    "svgo": "^0.7.2",
    "svgo-loader": "^1.2.1",
    "transform-runtime": "0.0.0",
    "url-loader": "0.5.7",
    "webpack": "^2.2.1",
    "webpack-dashboard": "^0.4.0",
    "webpack-dev-server": "^2.2.1",
    "webpack-hot-middleware": "2.10.0",
    "youtube-api-search": "0.0.5"
  },
  "bugs": {
    "url": "https://github.com/sgoldens/home/issues"
  },
  "homepage": "https://github.com/sgoldens/home#readme",
  "keywords": [
    "home"
  ],
  "prepush": [
    "npm run lint-break-on-errors --silent"
  ]
}
</code>```

.babelrc

```<code>{
  "plugins": [
    ["transform-class-properties", { "spec": true }],
    "transform-class-display-name",
    "class-display-name",
    "transform-react-display-name",
    "syntax-decorators",
    "transform-decorators-legacy",
    ["transform-es2015-template-literals", {
        "loose": true,
        "spec": true
      }]
  ],
  "presets": [
    "react",
    "es2015",
    "stage-0"
  ],
  "env": {
    "development": {
      "presets": [
        "react-hmre"
      ]
    }
  }
}
</code>```

webpack.config.js

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

const DashboardPlugin = require('webpack-dashboard/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const SpritePlugin = require('svg-sprite-loader/plugin');
const autoprefixer = require('autoprefixer');

const nodeEnv = process.env.NODE_ENV || 'development';
const isProduction = nodeEnv === 'production';

const jsSourcePath = path.join(__dirname, './src');
const buildPath = path.join(__dirname, './build');
const imgPath = path.join(__dirname, './images');
const iconPath = path.join(__dirname, './images');
const sourcePath = path.join(__dirname, './src');

// Common plugins
const plugins = [
  new SpritePlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'build',
    filename: 'build.js',
    minChunks(module) {
      const context = module.context;
      return context && context.indexOf('node_modules') >= 0;
    },
  }),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(nodeEnv),
      'API_HOST': JSON.stringify('https://posts-sgoldens.herokuapp.com'),
      'API_PORT': JSON.stringify(process.env.PORT || 5000)
    },
  }),
  new webpack.NamedModulesPlugin(),
  new HtmlWebpackPlugin({
    template: path.join(sourcePath, 'index.html'),
    path: buildPath,
    filename: 'index.html',
  }),
  new webpack.LoaderOptionsPlugin({
    options: {
      postcss: [
        autoprefixer({
          browsers: [
            'last 3 version',
            'ie >= 10',
          ],
        }),
      ],
      context: sourcePath,
    },
  }),
];

// Common rules
const rules = [
  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    use: [
      'babel-loader',
    ],
  },
  {
    test: /\.svg$/,
    use: [
      {
        loader: 'svg-sprite-loader',
        options: {
          extract: true,
          spriteFilename: 'icons-sprite.svg',
        },
      },
      'svgo-loader',
    ],
    include: iconPath,
  },
  {
    test: /\.(png|gif|jpg|svg)$/,
    include: imgPath,
    use: 'url-loader?limit=20480&name=assets/[name]-[hash].[ext]',
  },
];

if (isProduction) {
  // Production plugins
  plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
      output: {
        comments: false,
      },
    }),
    new ExtractTextPlugin('style-[hash].css')
  );

  // Production rules
  rules.push(
    {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader!postcss-loader!sass-loader',
      }),
    }
  );
} else {
  // Development plugins
  plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new DashboardPlugin()
  );

  // Development rules
  rules.push(
    {
      test: /\.scss$/,
      exclude: /node_modules/,
      use: [
        'style-loader',
        // Using source maps breaks urls in the CSS loader
        // https://github.com/webpack/css-loader/issues/232
        // This comment solves it, but breaks testing from a local network
        // https://github.com/webpack/css-loader/issues/232#issuecomment-240449998
        // 'css-loader?sourceMap',
        'css-loader',
        'postcss-loader',
        'sass-loader?sourceMap',
      ],
    }
  );
}

module.exports = {
  devtool: isProduction ? false : 'source-map',
  context: jsSourcePath,
  entry: {
    js: './index.js',
  },
  output: {
    path: buildPath,
    publicPath: '/',
    filename: 'bundle.js',
  },
  module: {
    rules,
  },
  resolve: {
    extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      jsSourcePath,
    ],
  },
  plugins,
  devServer: {
    contentBase: isProduction ? buildPath : sourcePath,
    historyApiFallback: true,
    port: 3000,
    compress: isProduction,
    inline: !isProduction,
    hot: !isProduction,
    host: '0.0.0.0',
    disableHostCheck: true,
    stats: {
      assets: true,
      children: false,
      chunks: false,
      hash: false,
      modules: false,
      publicPath: false,
      timings: true,
      version: false,
      warnings: true,
      colors: {
        green: '\u001b[32m',
      },
    },
  },
};
</code>```

答:
You code is importing separate source file from node_modules folder react-google-maps/*src*/lib/async/withScriptjs.js

But your webpack rules exclude files in node_modules from babel compilation process

```<code>  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/, // NB!
    use: [
      'babel-loader',
    ],
  }
</code>```

You could import compiled version instead /react-google-maps/**lib**/async/withScriptjs.js

Body:
JS newb here:

I've spent a couple days on this bug, and I've looked at many answers and practiced my most earnest Google-Fu, and tried many different babel plugins and presets configurations, as well as tried migrating my webpack 1 project into a webpack 2 incarnation, and in the end I'm still hitting the same wall. Please give me an assist.

When I try to build my project, all open sourced here, and most recently active and relevant to this question in the webpack2migration branch, I've been unable to build for production (and not even dev after futzing more and more with it through unproductive debugging)

This is the error I haven't gotten around, admittedly because I don't understand some (maybe many) of the complexities in webpack and how babel is to be correctly configured for what I'm struggling with.

Here's the error:

ERROR in ../~/react-google-maps/src/lib/async/withScriptjs.js
Module parse failed: /Users/sg/Desktop/blog-home/node_modules/react-google-maps/src/lib/async/withScriptjs.js Unexpected token (19:23)
You may need an appropriate loader to handle this file type.
| export default function withScriptjs(WrappedComponent) {
|   return class Container extends Component {
|     static displayName = `withScriptjs(${getDisplayName(WrappedComponent)})`;
|
|  static propTypes = {

Initially, I thought this was a bug with react-google-maps, but I suspect it is something different now. I have encountered this kind of bug once before a few months ago within a different project, and I know I've been mostly making a mess of my package.json.

Yes, I know there are many silly problems in there, like package duplications, unused packages, unnecessary dependencies... I've been hitting every angle I can think of, too hard and with not enough care towards cleanup yet; I'm asking for help before getting some sleep and trying yet again in the morning.

The project was to integrate a working small frontend game I'm prototyping, and I wanted to integrate it into my homepage, which I'm also beginning another sweep to clean up and refactor, for better presentation and code quality.

I humbly ask for some supportive help in configuring my build correctly where I obviously am having a lot of trouble.

When I began to integrate the little game into my home page, the build worked perfectly on my local machine in both development and production build configurations, but when I pushed my changes and triggered a build to my heroku host site it kept failing on this same file, I suppose because it can't parse it.

I hope that is enough to go on, and I'll be happy to help narrow this down as needed. :)

Best regards, and thanks for your time!

package.json

{
  "name": "react-sg-home-page",
  "version": "0.0.9",
  "description": "My home page and portfolio site",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+ssh://git@github.com/sgoldens/home.git"
  },
  "jest": {
    "verbose": true,
    "collectCoverage": true,
    "setupTestFrameworkScriptFile": "mock-local-storage"
  },
  "config": {
    "blanket": {
      "pattern": [
        ""
      ],
      "data-cover-never": [
        "node_modules",
        "__tests__",
        "*.spec.*"
      ]
    }
  },
  "engines": {
    "node": "7.7.4"
  },
  "scripts": {
    "buildcolors": "NODE_ENV=production webpack --config ./webpack.config.js --progress --colors",
    "start_nf": "nf start",
    "istanbul": "istanbul cover ./node_modules/mocha/bin/_mocha -- --reporter dot --full-trace __tests__",
    "lint:watch": "npm run lint -- --watch",
    "mochatest": "babel-node ./node_modules/.bin/isparta cover _mocha --require blanket -- --reporter dot --full-trace __tests__",
    "postinstall": "webpack -p --config ./webpack.config.js",
    "remove-public": "rm -rf ./public",
    "test": "jest --coverage",
    "test:watch": "npm test -- --watch",
    "start_prod": "node server.js",
    "start": "webpack-dev-server",
    "dev": "webpack-dashboard -t 'Marvin' -- webpack-dev-server",
    "build": "babel-node tools/build.js && babel-node tools/buildHtml.js",
    "lint-break-on-errors": "eslint ./source/js ./webpack.config.js -f table --ext .js --ext .jsx",
    "lint": "eslint ./source/js ./webpack.config.js -f table --ext .js --ext .jsx || true",
    "preview": "rm -rf ./build && NODE_ENV=\"production\" webpack-dashboard -t 'Preview Mode - Marvin' -- webpack-dev-server",
    "hook-add": "prepush install",
    "hook-remove": "prepush remove",
    "heroku-prebuild": "npm run remove-public && mkdir public",
    "heroku-postinstall": "node server.js"
  },
  "author": "Sasha Goldenson",
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^6.5.3",
    "babel-core": "^6.7.2",
    "babel-eslint": "^7.1.0",
    "babel-jest": "^19.0.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-syntax-decorators": "^6.13.0",
    "babel-plugin-transform-class-properties": "^6.6.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.6.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-stage-0": "^6.16.0",
    "babel-runtime": "^6.6.1",
    "chai": "3.5.0",
    "chai-jquery": "^2.0.0",
    "css-loader": "^0.28.0",
    "enzyme": "2.6.0",
    "eslint": "^3.10.1",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-config-google": "^0.7.1",
    "eslint-config-standard": "^10.2.1",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-node": "^4.2.2",
    "eslint-plugin-promise": "^3.5.0",
    "eslint-plugin-react": "^6.10.0",
    "eslint-plugin-standard": "^3.0.1",
    "eslint-watch": "2.1.11",
    "expect": "^1.19.0",
    "factory-girl": "^4.2.2",
    "isparta": "^4.0.0",
    "istanbul": "^1.0.0-alpha.2",
    "jasmine-core": "^2.6.1",
    "jest": "17.0.3",
    "jest-cli": "*",
    "karma": "^1.6.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-firefox-launcher": "^1.0.1",
    "karma-jasmine": "^1.1.0",
    "karma-safari-launcher": "^1.0.0",
    "mocha": "3.1.2",
    "mocha-lcov-reporter": "^1.3.0",
    "mock-local-storage": "^1.0.2",
    "nock": "^8.0.0",
    "react-addons-test-utils": "^15.4.0",
    "redux-mock-store": "^1.2.3",
    "standard": "^10.0.2",
    "webpack-dev-middleware": "1.6.1",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "babel-cli": "^6.24.0",
    "babel-core": "^6.24.0",
    "babel-es6-polyfill": "^1.1.0",
    "babel-loader": "^6.4.1",
    "babel-plugin-class-display-name": "^2.1.0",
    "babel-plugin-lodash": "^3.2.11",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-syntax-decorators": "^6.13.0",
    "babel-plugin-transform-async-to-generator": "^6.22.0",
    "babel-plugin-transform-class-display-name": "^0.0.3",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-es2015-classes": "6.18.0",
    "babel-plugin-transform-es2015-template-literals": "^6.22.0",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-plugin-transform-react-constant-elements": "^6.23.0",
    "babel-plugin-transform-react-display-name": "^6.25.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.3.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.23.0",
    "babel-preset-babili": "0.0.12",
    "babel-preset-env": "^1.2.2",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-es2016": "^6.22.0",
    "babel-preset-latest": "^6.24.0",
    "babel-preset-modern-async": "^1.0.0-alpha.3",
    "babel-preset-modern-browsers": "^9.0.2",
    "babel-preset-react": "^6.1.18",
    "babel-preset-stage-0": "^6.22.0",
    "babel-preset-stage-1": "^6.1.18",
    "babel-register": "^6.24.1",
    "babel-relay-plugin-loader": "^0.10.0",
    "babili-webpack-plugin": "0.0.11",
    "blanket": "^1.2.3",
    "bluebird": "^3.1.2",
    "bootstrap": "^3.3.7",
    "cheerio": "^0.20.0",
    "colors": "1.1.2",
    "compression": "^1.6.1",
    "coveralls": "^2.12.0",
    "css-loader": "^0.28.4",
    "es6-promise": "^3.3.1",
    "eventsource-polyfill": "0.9.6",
    "express": "~4.9.8",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.11.1",
    "font-awesome": "^4.7.0",
    "foreman": "2.0.0",
    "get-env": "^0.5.10",
    "history": "^4.6.3",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.24.1",
    "image-webpack-loader": "^3.3.0",
    "immutability-helper": "^2.2.2",
    "immutable": "^3.8.1",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.2.1",
    "json-loader": "^0.5.4",
    "lodash-webpack-plugin": "^0.11.2",
    "lodash.debounce": "^4.0.8",
    "material-ui": "^0.16.0-rc2",
    "node-sass": "^3.13.0",
    "npm-run-all": "^1.8.0",
    "open": "0.0.5",
    "postcss-loader": "^1.1.1",
    "prepush": "^3.1.11",
    "prop-types": "^15.5.10",
    "react": "^15.6.0",
    "react-addons-css-transition-group": "^15.6.0",
    "react-addons-update": "^15.6.0",
    "react-bootstrap": "^0.30.7",
    "react-display-name": "^0.2.0",
    "react-dom": "15.6.1",
    "react-google-maps": "^7.0.0",
    "react-icons": "^2.2.5",
    "react-lazy-cache": "^3.0.1",
    "react-logo": "^1.0.8",
    "react-modal": "1.5.2",
    "react-mui-speeddial": "0.0.6",
    "react-pure-render": "^1.0.2",
    "react-redux": "^4.4.6",
    "react-router-bootstrap": "^0.23.1",
    "react-router-dom": "next",
    "react-rte": "^0.11.0",
    "react-rte-image": "^0.11.1",
    "react-rte-material": "^0.12.5",
    "react-tap-event-plugin": "*",
    "react-tooltip": "3.2.2",
    "react-transform-catch-errors": "^1.0.2",
    "react-transform-hmr": "^1.0.4",
    "redbox-react": "^1.3.4",
    "redux": "^3.0.4",
    "redux-devtools": "^3.3.2",
    "redux-devtools-dock-monitor": "^1.1.1",
    "redux-devtools-extension": "^2.13.0",
    "redux-devtools-log-monitor": "^1.2.0",
    "redux-form": "6.6.1",
    "redux-form-material-ui": "^4.1.3",
    "redux-logger": "^3.0.0",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.2.0",
    "regenerator-runtime": "^0.10.3",
    "reinstall": "^1.1.1",
    "reselect": "^3.0.0",
    "rimraf": "^2.5.2",
    "sass-loader": "^4.0.2",
    "serve-favicon": "^2.3.0",
    "sinon": "1.17.6",
    "style-loader": "0.13.1",
    "svg-react-loader": "^0.3.7",
    "svg-sprite-loader": "^2.1.0",
    "svgo": "^0.7.2",
    "svgo-loader": "^1.2.1",
    "transform-runtime": "0.0.0",
    "url-loader": "0.5.7",
    "webpack": "^2.2.1",
    "webpack-dashboard": "^0.4.0",
    "webpack-dev-server": "^2.2.1",
    "webpack-hot-middleware": "2.10.0",
    "youtube-api-search": "0.0.5"
  },
  "bugs": {
    "url": "https://github.com/sgoldens/home/issues"
  },
  "homepage": "https://github.com/sgoldens/home#readme",
  "keywords": [
    "home"
  ],
  "prepush": [
    "npm run lint-break-on-errors --silent"
  ]
}

.babelrc

{
  "plugins": [
    ["transform-class-properties", { "spec": true }],
    "transform-class-display-name",
    "class-display-name",
    "transform-react-display-name",
    "syntax-decorators",
    "transform-decorators-legacy",
    ["transform-es2015-template-literals", {
        "loose": true,
        "spec": true
      }]
  ],
  "presets": [
    "react",
    "es2015",
    "stage-0"
  ],
  "env": {
    "development": {
      "presets": [
        "react-hmre"
      ]
    }
  }
}

webpack.config.js

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

const DashboardPlugin = require('webpack-dashboard/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const SpritePlugin = require('svg-sprite-loader/plugin');
const autoprefixer = require('autoprefixer');

const nodeEnv = process.env.NODE_ENV || 'development';
const isProduction = nodeEnv === 'production';

const jsSourcePath = path.join(__dirname, './src');
const buildPath = path.join(__dirname, './build');
const imgPath = path.join(__dirname, './images');
const iconPath = path.join(__dirname, './images');
const sourcePath = path.join(__dirname, './src');

// Common plugins
const plugins = [
  new SpritePlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'build',
    filename: 'build.js',
    minChunks(module) {
      const context = module.context;
      return context && context.indexOf('node_modules') >= 0;
    },
  }),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(nodeEnv),
      'API_HOST': JSON.stringify('https://posts-sgoldens.herokuapp.com'),
      'API_PORT': JSON.stringify(process.env.PORT || 5000)
    },
  }),
  new webpack.NamedModulesPlugin(),
  new HtmlWebpackPlugin({
    template: path.join(sourcePath, 'index.html'),
    path: buildPath,
    filename: 'index.html',
  }),
  new webpack.LoaderOptionsPlugin({
    options: {
      postcss: [
        autoprefixer({
          browsers: [
            'last 3 version',
            'ie >= 10',
          ],
        }),
      ],
      context: sourcePath,
    },
  }),
];

// Common rules
const rules = [
  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    use: [
      'babel-loader',
    ],
  },
  {
    test: /\.svg$/,
    use: [
      {
        loader: 'svg-sprite-loader',
        options: {
          extract: true,
          spriteFilename: 'icons-sprite.svg',
        },
      },
      'svgo-loader',
    ],
    include: iconPath,
  },
  {
    test: /\.(png|gif|jpg|svg)$/,
    include: imgPath,
    use: 'url-loader?limit=20480&name=assets/[name]-[hash].[ext]',
  },
];

if (isProduction) {
  // Production plugins
  plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
      output: {
        comments: false,
      },
    }),
    new ExtractTextPlugin('style-[hash].css')
  );

  // Production rules
  rules.push(
    {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader!postcss-loader!sass-loader',
      }),
    }
  );
} else {
  // Development plugins
  plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new DashboardPlugin()
  );

  // Development rules
  rules.push(
    {
      test: /\.scss$/,
      exclude: /node_modules/,
      use: [
        'style-loader',
        // Using source maps breaks urls in the CSS loader
        // https://github.com/webpack/css-loader/issues/232
        // This comment solves it, but breaks testing from a local network
        // https://github.com/webpack/css-loader/issues/232#issuecomment-240449998
        // 'css-loader?sourceMap',
        'css-loader',
        'postcss-loader',
        'sass-loader?sourceMap',
      ],
    }
  );
}

module.exports = {
  devtool: isProduction ? false : 'source-map',
  context: jsSourcePath,
  entry: {
    js: './index.js',
  },
  output: {
    path: buildPath,
    publicPath: '/',
    filename: 'bundle.js',
  },
  module: {
    rules,
  },
  resolve: {
    extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      jsSourcePath,
    ],
  },
  plugins,
  devServer: {
    contentBase: isProduction ? buildPath : sourcePath,
    historyApiFallback: true,
    port: 3000,
    compress: isProduction,
    inline: !isProduction,
    hot: !isProduction,
    host: '0.0.0.0',
    disableHostCheck: true,
    stats: {
      assets: true,
      children: false,
      chunks: false,
      hash: false,
      modules: false,
      publicPath: false,
      timings: true,
      version: false,
      warnings: true,
      colors: {
        green: '\u001b[32m',
      },
    },
  },
};

Body:
You code is importing separate source file from node_modules folder react-google-maps/*src*/lib/async/withScriptjs.js

But your webpack rules exclude files in node_modules from babel compilation process

  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/, // NB!
    use: [
      'babel-loader',
    ],
  }

You could import compiled version instead /react-google-maps/**lib**/async/withScriptjs.js


问:
PHP + Mysql : How to insert data having , " ' (Semicolon, Single + Double Quotation Marks)
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.

Question is simple what is the easiest way to send those sting into the database.

```<code>base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
</code>```

答:
Use mysqli_real_escape_string

```<code>$someText = mysqli_real_escape_string($con,"It's a test.");
</code>```

where $con is your database connection variable.

Body:
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.

Question is simple what is the easiest way to send those sting into the database.

base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.

Body:
Use mysqli_real_escape_string

$someText = mysqli_real_escape_string($con,"It's a test.");

where $con is your database connection variable.


问:
How to populate Dropdown with jQuery each() Loop
i want to to exactly the same like this:

```<code>window.onload = function populateDropdown(){
    console.log('Hallo i bims, ein Method')
    for(var i = 0; i < 100; i++){
        var select = document.getElementById('age');
        select.options[select.options.length] = new Option(i, i);
    }
};
</code>```

in jQuery.. i already tried it with $.each(), but i don't understand how i can do the the step:

```<code>(;i < 99; i++)
</code>```

Can u give me some hints pls ?

答:
$.each() will loop through the selected elements (all the already existing elements only)

To achive this you'll need to use a for loop or alike.

```<code>for(var i = 0, i < 100; i++) {
    $('#age').append('<option/>', {
        value: i,
        html: i
    });
}
</code>```

Body:
i want to to exactly the same like this:

window.onload = function populateDropdown(){
    console.log('Hallo i bims, ein Method')
    for(var i = 0; i < 100; i++){
        var select = document.getElementById('age');
        select.options[select.options.length] = new Option(i, i);
    }
};

in jQuery.. i already tried it with $.each(), but i don't understand how i can do the the step:

(;i < 99; i++)

Can u give me some hints pls ?

Body:
$.each() will loop through the selected elements (all the already existing elements only)

To achive this you'll need to use a for loop or alike.

for(var i = 0, i < 100; i++) {
    $('#age').append('<option/>', {
        value: i,
        html: i
    });
}


问:
Local Object Variables Thread Safety In Java
I know that primitive local variables are thread safe because they are allocated in stack and it is unique for each thread.

What about object variables: are they thread safe in local scope.

I have the following pseudocode:

```<code>private void myMethod(int myInt) {

    final Map<String, Object> myMap = new HashMap<>();

    // Put some values into map.
    ...
    // Get some values from map.
}
</code>```

In this case do i need to change the HashMap to ConcurrentHashMap or is it already thread safe?

答:
As long as any other Thread does not read or write this variable you don't need to worry.
The synchronization is needed when one thread is writing and second is reading a variable. In case of no synchronization the reading thread can see stale value.

Java concurrency is very broad topic, it is hard to learn it without any background like reading a book first. My favorite book in this topic is: "Java concurrency in practice", I advise you to read it first, then come back here and ask if you will have more questions.

Body:
I know that primitive local variables are thread safe because they are allocated in stack and it is unique for each thread.

What about object variables: are they thread safe in local scope.

I have the following pseudocode:

private void myMethod(int myInt) {

    final Map<String, Object> myMap = new HashMap<>();

    // Put some values into map.
    ...
    // Get some values from map.
}

In this case do i need to change the HashMap to ConcurrentHashMap or is it already thread safe?


问:
Should not allow the space in password field?
Need to show error message whenever i enter space in password input field using ng-pattern.</p>

答:
Here is the link Jsfiddle demo

You can check for indexof or you can use regX for it.

HTML

```<code><div ng-app="myApp">
  <div ng-controller="ctrl">

    <form>
      <span>{{error}}</span>
      <input type='password' ng-model='pass' ng-change='check()'>
    </form>
  </div>
</div>
</code>```

**JS **

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

  app.controller('ctrl', function($scope) {
    $scope.error = '';
    $scope.check = function() {
      $scope.pass.indexOf(' ') > -1 ? ($scope.error = 'Invalid') : ($scope.error = '');
    }
  })
</code>```

Hope this will help you

updated for space

Body:
Here is the link Jsfiddle demo

You can check for indexof or you can use regX for it.

HTML

<div ng-app="myApp">
  <div ng-controller="ctrl">

    <form>
      <span>{{error}}</span>
      <input type='password' ng-model='pass' ng-change='check()'>
    </form>
  </div>
</div>

**JS **

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

  app.controller('ctrl', function($scope) {
    $scope.error = '';
    $scope.check = function() {
      $scope.pass.indexOf(' ') > -1 ? ($scope.error = 'Invalid') : ($scope.error = '');
    }
  })

Hope this will help you

updated for space


问:
Jest is hung there
I have a project using jest. It's running good historically. After 1 year when I open it, somehow jest is hung. No info, no error, not proceed. (See pic) Any insights?

答:
Jest runs the tests with a multithreaded approach that might sometimes run into a deadlock. The same happened to me on Git-bash when I used to run my projects in a windows environment. Try adding a

-- -i

to your test command to run it without using multithreading and see if it solves the problem.

Title: Jest is hung there


问:
SQL Select SQL Statement output + ( )
Table Name: aa_company

```<code>Column_A    Column_B    Column_C
ABC         0001        abc@gmail.com

BCD         0002        bcd@gmail.com

CDE         0003        cde@gmail.com

Select Column_A, Column_B, Column_C
FROM aa_company;
</code>```

if I want the output result add one more column, how can i do it?

```<code>Column_A    Column_B    Column_C          Column_D
ABC         0001        abc@gmail.com     ABC (0001)

BCD         0002        bcd@gmail.com     BCD (0002)

CDE         0003        cde@gmail.com     CDE (0003)
</code>```

答:
```<code>CREATE TABLE #TABLE1
    ([COLUMN_A] VARCHAR(3), [COLUMN_B] VARCHAR(50), [COLUMN_C] VARCHAR(13))
;

INSERT INTO #TABLE1
    ([COLUMN_A], [COLUMN_B], [COLUMN_C])
VALUES
    ('ABC', '0001', 'ABC@GMAIL.COM'),
    ('BCD', '0002', 'BCD@GMAIL.COM'),
    ('CDE', '0003', 'CDE@GMAIL.COM')
;
</code>```

using concat function

```<code>   SELECT COLUMN_A, COLUMN_B, COLUMN_C,CONCAT(COLUMN_A,'('+COLUMN_B+')') AS COLUMN_D FROM #TABLE1
</code>```

or
using + operator

```<code>   Select Column_A, Column_B, Column_C, Column_A + ' (' + Column_B + ')'  COLUMN_D  FROM #TABLE1;
</code>```

Title: SQL Select SQL Statement output + ( )

Body:
Table Name: aa_company

Column_A    Column_B    Column_C
ABC         0001        abc@gmail.com

BCD         0002        bcd@gmail.com

CDE         0003        cde@gmail.com

Select Column_A, Column_B, Column_C
FROM aa_company;

if I want the output result add one more column, how can i do it?

Column_A    Column_B    Column_C          Column_D
ABC         0001        abc@gmail.com     ABC (0001)

BCD         0002        bcd@gmail.com     BCD (0002)

CDE         0003        cde@gmail.com     CDE (0003)

Body:
CREATE TABLE #TABLE1
    ([COLUMN_A] VARCHAR(3), [COLUMN_B] VARCHAR(50), [COLUMN_C] VARCHAR(13))
;

INSERT INTO #TABLE1
    ([COLUMN_A], [COLUMN_B], [COLUMN_C])
VALUES
    ('ABC', '0001', 'ABC@GMAIL.COM'),
    ('BCD', '0002', 'BCD@GMAIL.COM'),
    ('CDE', '0003', 'CDE@GMAIL.COM')
;

using concat function

   SELECT COLUMN_A, COLUMN_B, COLUMN_C,CONCAT(COLUMN_A,'('+COLUMN_B+')') AS COLUMN_D FROM #TABLE1

or
using + operator

   Select Column_A, Column_B, Column_C, Column_A + ' (' + Column_B + ')'  COLUMN_D  FROM #TABLE1;


问:
evaluating else if after an if condition is true
Consider this snippet:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}
</code>```

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

答:
The reason your "else if" statement is not happening is because

```<code>if (textBox1.MaxLength > 0)
</code>```

is always true, since MaxLength obviously will always be greater then 0, unless it was changed to be 0.

I would like to add that

```<code>textBox1.MaxLength < 32768
</code>```

Likely also will always be true.

Additionally

When this property is set to 0, the
  maximum length of the text that can be
  entered in the control is limited only
  by available memory.

Body:
Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

Body:
The reason your "else if" statement is not happening is because

if (textBox1.MaxLength > 0)

is always true, since MaxLength obviously will always be greater then 0, unless it was changed to be 0.

I would like to add that

textBox1.MaxLength < 32768

Likely also will always be true.

Additionally

When this property is set to 0, the
  maximum length of the text that can be
  entered in the control is limited only
  by available memory.


问:
Android - only in release apk, java.lang.IllegalArgumentException: Unable to create converter for class
I'm using retrofit, gson and realm, I don't really know what causes this error, but it only occurs in release apk when minifyEnabled is true, so I guess it's a proguard issued but I don't know exactly what's the issue.

Here's my error:

```<code>java.lang.IllegalArgumentException: Unable to create converter for class com.ool.oolapp.data.models.NewsFeedResponse
   for method a.getPosts
   at retrofit2.ServiceMethod$Builder.methodError(Unknown Source)
   at retrofit2.ServiceMethod$Builder.createResponseConverter(Unknown Source)
   at retrofit2.ServiceMethod$Builder.build(Unknown Source)
   at retrofit2.Retrofit.loadServiceMethod(Unknown Source)
   at retrofit2.Retrofit$1.invoke(Unknown Source)
   at java.lang.reflect.Proxy.invoke(Proxy.java:393)
   at $Proxy1.getPosts(Unknown Source)
   at com.ool.oolapp.data.a.b.a(Unknown Source)
   at com.ool.oolapp.data.b.k.a(Unknown Source)
   at com.ool.oolapp.data.b.k.a(Unknown Source)
   at com.ool.oolapp.home.a.c.a(Unknown Source)
   at com.ool.oolapp.home.b.b.b(Unknown Source)
   at com.ool.oolapp.home.b.b.a(Unknown Source)
   at com.ool.oolapp.home.view.d.v(Unknown Source)
   at android.support.v4.b.p.L(Unknown Source)
   at android.support.v4.b.v.a(Unknown Source)
   at android.support.v4.b.v.e(Unknown Source)
   at android.support.v4.b.v.a(Unknown Source)
   at android.support.v4.b.g.e(Unknown Source)
   at android.support.v4.b.v.b(Unknown Source)
   at android.support.v4.b.v.a(Unknown Source)
   at android.support.v4.b.v.b(Unknown Source)
   at android.support.v4.b.v.b(Unknown Source)
   at android.support.v4.b.g.d(Unknown Source)
   at android.support.v4.b.aa.b(Unknown Source)
   at android.support.v4.view.ViewPager.a(Unknown Source)
   at android.support.v4.view.ViewPager.c(Unknown Source)
   at android.support.v4.view.ViewPager.onMeasure(Unknown Source)
   at android.view.View.measure(View.java:18794)
   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
   at android.support.v7.widget.ContentFrameLayout.onMeasure(Unknown Source)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
   at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
   at android.view.Choreographer.doCallbacks(Choreographer.java:670)
   at android.view.Choreographer.doFrame(Choreographer.java:606)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:148)
</code>```

Here's com.ool.oolapp.data.models.NewsFeedResponse:

```<code>public class NewsFeedResponse {
    @SerializedName("posts")
    private List<Post> posts;

    public List<Post> getPosts() {
        return posts;
    }

    public void setPosts(List<Post> posts) {
        this.posts = posts;
    }
}
</code>```

And Post.java:

```<code>    @RealmClass
public class Post implements RealmModel {
    @PrimaryKey
    @SerializedName("postId")
    private int postId;
    @SerializedName("userId")
    private int userId;
    @SerializedName("userDto")
    private UserDto userDto;
    @SerializedName("caption")
    private String caption;
    @SerializedName("voiceDuration")
    private int voiceDuration;
    @SerializedName("commentCount")
    private int commentCount;
    @SerializedName("likesCount")
    private int likesCount;
    @SerializedName("shareCount")
    private int shareCount;
    @SerializedName("picUrl")
    private String picUrl;
    @SerializedName("voiceUrl")
    private String voiceUrl;
    @SerializedName("creationDate")
    @JsonAdapter(TimestampDeserializer.class)
    private Date creationDate;
    @SerializedName("comments")
    private RealmList<Comment> comments;

    public Post() {
    }

    public Post(String picUrl, String caption, int voiceDuration) {
        this.picUrl = picUrl;
        this.caption = caption;
        this.voiceDuration = voiceDuration;
    }

    public String getCreatedFrom()
    {
        return Utility.getCreatedFromString(creationDate);
    }

    public int getPostId() {
        return postId;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public int getVoiceDuration() {
        return voiceDuration;
    }

    public void setVoiceDuration(int voiceDuration) {
        this.voiceDuration = voiceDuration;
    }

    public String getVoiceUrl() {
        return voiceUrl;
    }

    public void setVoiceUrl(String voiceUrl) {
        this.voiceUrl = voiceUrl;
    }

    public int getUserId() {
        return userId;
    }

    public void setPostId(int postId) {
        this.postId = postId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public int getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(int commentCount) {
        this.commentCount = commentCount;
    }

    public int getLikesCount() {
        return likesCount;
    }

    public void setLikesCount(int likesCount) {
        this.likesCount = likesCount;
    }

    public int getShareCount() {
        return shareCount;
    }

    public void setShareCount(int shareCount) {
        this.shareCount = shareCount;
    }

    public RealmList<Comment> getComments() {
        return comments;
    }

    public void setComments(RealmList<Comment> comments) {
        this.comments = comments;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public UserDto getUserDto() {
        return userDto;
    }

    public void setUserDto(UserDto userDto) {
        this.userDto = userDto;
    }
}
</code>```

My UserDto class:

```<code>@RealmClass
public class UserDto implements RealmModel {
    @PrimaryKey
    @SerializedName("userId")
    private int userId;
    @SerializedName("fName")
    private String fName;
    @SerializedName("lName")
    private String lName;
    @SerializedName("pictureLocation")
    private String pictureLocation;

    public UserDto() {}

    public UserDto(int userId, String fname, String lname, String pictureLocation) {
        setUserId(userId);
        setfName(fname);
        setlName(lname);
        setPictureLocation(pictureLocation);
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getFName() {
        return fName;
    }

    public String getLName() {
        return lName;
    }

    public String getPictureLocation() {
        return pictureLocation;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }

    public void setPictureLocation(String pictureLocation) {
        this.pictureLocation = pictureLocation;
    }
}
</code>```

Here's my retrofit configurations:

```<code>private Retrofit.Builder createRetrofitBuilder() {
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    if(BuildConfig.BUILD_TYPE.equals("release")) {
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
    } else {
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .build();
    GsonBuilder gsonBuilder = new GsonBuilder();
    return new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()));
}
</code>```

And finally my Proguard file:

```<code>    # retrofit
    # Platform calls Class.forName on types which do not exist on Android to determine platform.
    -dontnote retrofit2.Platform
    # Platform used when running on Java 8 VMs. Will not be used at runtime.
    -dontwarn retrofit2.Platform$Java8
    # Retain generic type information for use by reflection by converters and adapters.
    -keepattributes Signature
    # Retain declared checked exceptions for use by a Proxy instance.
    -keepattributes Exceptions
    #okio
    -dontwarn okio.**
    #Picasso
    -dontwarn com.squareup.okhttp.**
    #retrolambda
    -dontwarn java.lang.invoke.*
    -dontwarn **$$Lambda$*

    # Amazon AWS
    -dontwarn com.fasterxml.jackson.core.**
    # Guava
    -dontwarn sun.misc.Unsafe
    -dontwarn java.lang.ClassValue

    -keep class retrofit2.** { *; }
    -keep class com.ool.oolapp.data.models.** {*;}
    -keepclassmembernames interface * {
        @retrofit2.http.* <methods>;
    }
    -keepattributes *Annotation*
</code>```

答:
It seems that Retrofit is failing in the method getPosts(), most likely due the Post class not being found. It seems that you're not including the Realm specific ProGuard rules:

```<code>-keep class io.realm.annotations.RealmModule
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.internal.Keep
-keep @io.realm.internal.Keep class *
-dontwarn javax.**
-dontwarn io.realm.**
</code>```

that force all classes annotated with @RealmModule to be preserved during obfuscation and trimming. Adding these rules to your ProGuard file should solve the problem.

Body:
I'm using retrofit, gson and realm, I don't really know what causes this error, but it only occurs in release apk when minifyEnabled is true, so I guess it's a proguard issued but I don't know exactly what's the issue.

Here's my error:

java.lang.IllegalArgumentException: Unable to create converter for class com.ool.oolapp.data.models.NewsFeedResponse
   for method a.getPosts
   at retrofit2.ServiceMethod$Builder.methodError(Unknown Source)
   at retrofit2.ServiceMethod$Builder.createResponseConverter(Unknown Source)
   at retrofit2.ServiceMethod$Builder.build(Unknown Source)
   at retrofit2.Retrofit.loadServiceMethod(Unknown Source)
   at retrofit2.Retrofit$1.invoke(Unknown Source)
   at java.lang.reflect.Proxy.invoke(Proxy.java:393)
   at $Proxy1.getPosts(Unknown Source)
   at com.ool.oolapp.data.a.b.a(Unknown Source)
   at com.ool.oolapp.data.b.k.a(Unknown Source)
   at com.ool.oolapp.data.b.k.a(Unknown Source)
   at com.ool.oolapp.home.a.c.a(Unknown Source)
   at com.ool.oolapp.home.b.b.b(Unknown Source)
   at com.ool.oolapp.home.b.b.a(Unknown Source)
   at com.ool.oolapp.home.view.d.v(Unknown Source)
   at android.support.v4.b.p.L(Unknown Source)
   at android.support.v4.b.v.a(Unknown Source)
   at android.support.v4.b.v.e(Unknown Source)
   at android.support.v4.b.v.a(Unknown Source)
   at android.support.v4.b.g.e(Unknown Source)
   at android.support.v4.b.v.b(Unknown Source)
   at android.support.v4.b.v.a(Unknown Source)
   at android.support.v4.b.v.b(Unknown Source)
   at android.support.v4.b.v.b(Unknown Source)
   at android.support.v4.b.g.d(Unknown Source)
   at android.support.v4.b.aa.b(Unknown Source)
   at android.support.v4.view.ViewPager.a(Unknown Source)
   at android.support.v4.view.ViewPager.c(Unknown Source)
   at android.support.v4.view.ViewPager.onMeasure(Unknown Source)
   at android.view.View.measure(View.java:18794)
   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
   at android.support.v7.widget.ContentFrameLayout.onMeasure(Unknown Source)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
   at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
   at android.view.View.measure(View.java:18794)
   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
   at android.view.Choreographer.doCallbacks(Choreographer.java:670)
   at android.view.Choreographer.doFrame(Choreographer.java:606)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:148)

Here's com.ool.oolapp.data.models.NewsFeedResponse:

public class NewsFeedResponse {
    @SerializedName("posts")
    private List<Post> posts;

    public List<Post> getPosts() {
        return posts;
    }

    public void setPosts(List<Post> posts) {
        this.posts = posts;
    }
}

And Post.java:

    @RealmClass
public class Post implements RealmModel {
    @PrimaryKey
    @SerializedName("postId")
    private int postId;
    @SerializedName("userId")
    private int userId;
    @SerializedName("userDto")
    private UserDto userDto;
    @SerializedName("caption")
    private String caption;
    @SerializedName("voiceDuration")
    private int voiceDuration;
    @SerializedName("commentCount")
    private int commentCount;
    @SerializedName("likesCount")
    private int likesCount;
    @SerializedName("shareCount")
    private int shareCount;
    @SerializedName("picUrl")
    private String picUrl;
    @SerializedName("voiceUrl")
    private String voiceUrl;
    @SerializedName("creationDate")
    @JsonAdapter(TimestampDeserializer.class)
    private Date creationDate;
    @SerializedName("comments")
    private RealmList<Comment> comments;

    public Post() {
    }

    public Post(String picUrl, String caption, int voiceDuration) {
        this.picUrl = picUrl;
        this.caption = caption;
        this.voiceDuration = voiceDuration;
    }

    public String getCreatedFrom()
    {
        return Utility.getCreatedFromString(creationDate);
    }

    public int getPostId() {
        return postId;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public int getVoiceDuration() {
        return voiceDuration;
    }

    public void setVoiceDuration(int voiceDuration) {
        this.voiceDuration = voiceDuration;
    }

    public String getVoiceUrl() {
        return voiceUrl;
    }

    public void setVoiceUrl(String voiceUrl) {
        this.voiceUrl = voiceUrl;
    }

    public int getUserId() {
        return userId;
    }

    public void setPostId(int postId) {
        this.postId = postId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public int getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(int commentCount) {
        this.commentCount = commentCount;
    }

    public int getLikesCount() {
        return likesCount;
    }

    public void setLikesCount(int likesCount) {
        this.likesCount = likesCount;
    }

    public int getShareCount() {
        return shareCount;
    }

    public void setShareCount(int shareCount) {
        this.shareCount = shareCount;
    }

    public RealmList<Comment> getComments() {
        return comments;
    }

    public void setComments(RealmList<Comment> comments) {
        this.comments = comments;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public UserDto getUserDto() {
        return userDto;
    }

    public void setUserDto(UserDto userDto) {
        this.userDto = userDto;
    }
}

My UserDto class:

@RealmClass
public class UserDto implements RealmModel {
    @PrimaryKey
    @SerializedName("userId")
    private int userId;
    @SerializedName("fName")
    private String fName;
    @SerializedName("lName")
    private String lName;
    @SerializedName("pictureLocation")
    private String pictureLocation;

    public UserDto() {}

    public UserDto(int userId, String fname, String lname, String pictureLocation) {
        setUserId(userId);
        setfName(fname);
        setlName(lname);
        setPictureLocation(pictureLocation);
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getFName() {
        return fName;
    }

    public String getLName() {
        return lName;
    }

    public String getPictureLocation() {
        return pictureLocation;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }

    public void setPictureLocation(String pictureLocation) {
        this.pictureLocation = pictureLocation;
    }
}

Here's my retrofit configurations:

private Retrofit.Builder createRetrofitBuilder() {
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    if(BuildConfig.BUILD_TYPE.equals("release")) {
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
    } else {
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .build();
    GsonBuilder gsonBuilder = new GsonBuilder();
    return new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()));
}

And finally my Proguard file:

    # retrofit
    # Platform calls Class.forName on types which do not exist on Android to determine platform.
    -dontnote retrofit2.Platform
    # Platform used when running on Java 8 VMs. Will not be used at runtime.
    -dontwarn retrofit2.Platform$Java8
    # Retain generic type information for use by reflection by converters and adapters.
    -keepattributes Signature
    # Retain declared checked exceptions for use by a Proxy instance.
    -keepattributes Exceptions
    #okio
    -dontwarn okio.**
    #Picasso
    -dontwarn com.squareup.okhttp.**
    #retrolambda
    -dontwarn java.lang.invoke.*
    -dontwarn **$$Lambda$*

    # Amazon AWS
    -dontwarn com.fasterxml.jackson.core.**
    # Guava
    -dontwarn sun.misc.Unsafe
    -dontwarn java.lang.ClassValue

    -keep class retrofit2.** { *; }
    -keep class com.ool.oolapp.data.models.** {*;}
    -keepclassmembernames interface * {
        @retrofit2.http.* <methods>;
    }
    -keepattributes *Annotation*

Body:
It seems that Retrofit is failing in the method getPosts(), most likely due the Post class not being found. It seems that you're not including the Realm specific ProGuard rules:

-keep class io.realm.annotations.RealmModule
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.internal.Keep
-keep @io.realm.internal.Keep class *
-dontwarn javax.**
-dontwarn io.realm.**

that force all classes annotated with @RealmModule to be preserved during obfuscation and trimming. Adding these rules to your ProGuard file should solve the problem.


问:
How to grant select on dba_users for role?
It is possible to make grant select on dba_users to role? I trying to give access for users and all works fine, but when i try to do this for all group, this access didnt work.</p>

答:
Privileges which are granted through a role do not apply inside PL/SQL blocks. You have to grant the privilege to each USER individually.

See How Roles Work in PL/SQL Blocks


问:
pyteomics: calculate mass from a file containing the sequence of several proteins
I want to calculate the mass for every protein of my file.

My code so far:

```<code>from pyteomics import mass
 with open('file.txt') as f:
        for line in f:
             mass.calculate_mass(line)
</code>```

When I replace the mass.calculate_mass with print(line) all the lines are correctly printed. But with mass.calculate_mass(line) come several error messages:

```<code>Traceback (most recent call last):
File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 275, in parse
    n, body, c = re.match(_modX_sequence, sequence).groups() AttributeError: 'NoneType' object has no attribute 'groups'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 304, in __init__
    self._from_sequence(args[0], aa_comp)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 200, in _from_sequence
    show_unmodified_termini=True)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 277, in parse
    raise PyteomicsError('Not a valid modX sequence: ' + sequence) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Not a valid modX sequence: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 307, in __init__
    self._from_formula(args[0], mass_data)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 205, in _from_formula
    raise PyteomicsError('Invalid formula: ' + formula) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Invalid formula: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/calculatemass.py", line 5, in <module>
    mass.calculate_mass(line)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 499, in calculate_mass
    else Composition(*args, **kwargs))   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 312, in __init__
    'formula'.format(args[0])) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: 'Could not create a Composition object from string: "\'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY\'\n": not a valid sequence or formula'
</code>```

my file looks like this:

```<code>'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'
</code>```

I also tried it with

sequence='MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'

There are no empty lines in my file.
If I try the same in the shell, it works:

```<code>mass.calculate_mass('MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY')
</code>```

49589.2790365072

I also tried mass.calculate_mass(str(line)) but that did not help.

Do you know what I am doing wrong?

答:
I think you have an issue with "EOL" char ('\n'). Try:

```<code>mass.calculate_mass(line.strip())
</code>```

Does it work?

line.strip() removes leading/trailing white spaces from your line. See strip() for more information.

Body:
I want to calculate the mass for every protein of my file.

My code so far:

from pyteomics import mass
 with open('file.txt') as f:
        for line in f:
             mass.calculate_mass(line)

When I replace the mass.calculate_mass with print(line) all the lines are correctly printed. But with mass.calculate_mass(line) come several error messages:

Traceback (most recent call last):
File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 275, in parse
    n, body, c = re.match(_modX_sequence, sequence).groups() AttributeError: 'NoneType' object has no attribute 'groups'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 304, in __init__
    self._from_sequence(args[0], aa_comp)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 200, in _from_sequence
    show_unmodified_termini=True)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/parser.py", line 277, in parse
    raise PyteomicsError('Not a valid modX sequence: ' + sequence) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Not a valid modX sequence: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 307, in __init__
    self._from_formula(args[0], mass_data)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 205, in _from_formula
    raise PyteomicsError('Invalid formula: ' + formula) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: "Invalid formula: 'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'\n"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/home/michaela/calculatemass.py", line 5, in <module>
    mass.calculate_mass(line)   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 499, in calculate_mass
    else Composition(*args, **kwargs))   File "/home/michaela/.local/lib/python3.5/site-packages/pyteomics/mass/mass.py", line 312, in __init__
    'formula'.format(args[0])) pyteomics.auxiliary.PyteomicsError: Pyteomics error, message: 'Could not create a Composition object from string: "\'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY\'\n": not a valid sequence or formula'

my file looks like this:

'MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'

I also tried it with

sequence='MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY'

There are no empty lines in my file.
If I try the same in the shell, it works:

mass.calculate_mass('MELNLTQLPLVHITFCGRPAVSIGVVNLVGLFGSTDYVLLQRIGSQGQTALRKGDGGGRHSKDSRDSSLDSLEIENRVRSSNMKLCRNTGLPVGCYNVVEGGIYDVVRYSDLRKGKVKGMDFATLNRHSDGRPKTRRGCRSRRKRRRDGTVENAAQSTPSDTVSSSFKQPSTPVPTDPSGTSGGTNGVSQRAKVVRAAQPSERKAHQKATKVSQTSKQTGGKEAPAVDEKNSNGTKVERTRTTKPRAPGIPKERPPRVGKEKVQQLKPVAEAAPQHAPSRSPSPRQANSNFAAVVLTASDLRSCDLGSSLSNVSVCTDKAETQMTPTTGPVTTSMQLNKSKHVPSSTGRTAAQDNGAKKTPQVATPVGESANAKKQQDVVDVDNALLVGHGSSSNGKKEGGSTGLANVRTDHSRDVVDRRAAAAPSNSIVECPCAPDAASPELGFVTVESALSRDFSLGSSLASSADSVY')

49589.2790365072

I also tried mass.calculate_mass(str(line)) but that did not help.

Do you know what I am doing wrong?

Body:
I think you have an issue with "EOL" char ('\n'). Try:

mass.calculate_mass(line.strip())

Does it work?

line.strip() removes leading/trailing white spaces from your line. See strip() for more information.