问:
Module/Project structure in Python
I'm trying to build a simple project in Python,however I can't seem to wrap my head around how it's done despite reading the documentations over and over and reading example code.

I'm semi-new to Python, having a background of only single-file scripting.
However I made numerous Node.js and Java projects with multiple folders and packages.
In Python However I can't seem to grasp the project structure and workflow mechanisms- init.py, virtualenvs, setuptools etc. it all seems very alien and unintuitive to me, hurting my  overall productivity(ironically Python is supposed to be a language aimed at productivity, right?)

My project has this example structure:

```<code>package_test  (package)
    |
    |------- __init__.py
    |------- main.py (entry point)
    |
    |------- /lib (modules)
    |           |
    |           |----- __init__.py
    |           |----- lib.py
    |
    |------- /Tests
    |           |
    |           |----- __init__.py
    |           |----- test.py
</code>```

in main.py:

```<code> from lib import lib

 lib.libtest()
</code>```

in lib.py:

```<code> def libtest():
     print("libtest")
</code>```

in test.py:

```<code> from lib import lib

 lib.libtest()
</code>```

Running main.py works, However when running test.py it cannot find the module. I have tried solutions such as appending to sys.path, putting '..' before lib, and more- none have worked.

This is just an example, but I wish to develop more complex projects in Python with multiple subfolders in the future(I think Python has some cool features and nice libraries), yet this problem keeps bothering me. I never had to think about these issues when developing in Java or in Node, not to mention stuff such as virtualenv etc.

Thank you in Advance

答:
Your test.py needs to know lib.py is one level above it and inside the lib folder. So all you should need to do is append the path of your lib folder before running the import of lib.py into test.py. Something like

```<code>import sys
sys.path.append("..//lib")
import lib
</code>```

Please note that the answer above assumes you run on Windows. A more comprehensive approach would be to replace the windows paths with proper os.path syntax. Also another assumption made by this code is that you will run your test.py from it's folder, not with an absolute/relative path.

```<code>import sys
import os.path
sys.path.append(os.path.join(os.path.pardir, 'lib'))
import lib
</code>```

If you want to run your test.py with a path, your code could look like this:

```<code>import sys
import os.path
# os.path.abspath(__file__) gets the absolute path of the current python scrip
# os.path.dirname gets the absolute path of whatever file you ask it to (minus the filename)
# The line below appends the full path of your lib folder to the current script's path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, 'lib'))
# This should allow test.py to import libtest regardless of where your run it from. Assuming your provided project structure.
from lib import libtest
libtest()
</code>```

Title: Module/Project structure in Python

Body:
I'm trying to build a simple project in Python,however I can't seem to wrap my head around how it's done despite reading the documentations over and over and reading example code.

I'm semi-new to Python, having a background of only single-file scripting.
However I made numerous Node.js and Java projects with multiple folders and packages.
In Python However I can't seem to grasp the project structure and workflow mechanisms- init.py, virtualenvs, setuptools etc. it all seems very alien and unintuitive to me, hurting my  overall productivity(ironically Python is supposed to be a language aimed at productivity, right?)

My project has this example structure:

package_test  (package)
    |
    |------- __init__.py
    |------- main.py (entry point)
    |
    |------- /lib (modules)
    |           |
    |           |----- __init__.py
    |           |----- lib.py
    |
    |------- /Tests
    |           |
    |           |----- __init__.py
    |           |----- test.py

in main.py:

 from lib import lib

 lib.libtest()

in lib.py:

 def libtest():
     print("libtest")

in test.py:

 from lib import lib

 lib.libtest()

Running main.py works, However when running test.py it cannot find the module. I have tried solutions such as appending to sys.path, putting '..' before lib, and more- none have worked.

This is just an example, but I wish to develop more complex projects in Python with multiple subfolders in the future(I think Python has some cool features and nice libraries), yet this problem keeps bothering me. I never had to think about these issues when developing in Java or in Node, not to mention stuff such as virtualenv etc.

Thank you in Advance

Body:
Your test.py needs to know lib.py is one level above it and inside the lib folder. So all you should need to do is append the path of your lib folder before running the import of lib.py into test.py. Something like

import sys
sys.path.append("..//lib")
import lib

Please note that the answer above assumes you run on Windows. A more comprehensive approach would be to replace the windows paths with proper os.path syntax. Also another assumption made by this code is that you will run your test.py from it's folder, not with an absolute/relative path.

import sys
import os.path
sys.path.append(os.path.join(os.path.pardir, 'lib'))
import lib

If you want to run your test.py with a path, your code could look like this:

import sys
import os.path
# os.path.abspath(__file__) gets the absolute path of the current python scrip
# os.path.dirname gets the absolute path of whatever file you ask it to (minus the filename)
# The line below appends the full path of your lib folder to the current script's path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, 'lib'))
# This should allow test.py to import libtest regardless of where your run it from. Assuming your provided project structure.
from lib import libtest
libtest()


来源: stackexchange

问:
UICollectionView highlighted cell with shadow
I have UICollectionView in which the centre cell will be highlighted as shown below image.

i have used following code to make shadow around the center cell.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell : STSuggestStyleCell = collectionView.dequeueReusableCell(for: indexPath)

    if indexPath.row == 4{

        cell.imageProfile.layer.cornerRadius = 2.0
        cell.imageProfile.layer.borderWidth = 1.0;
        cell.imageProfile.layer.borderColor = UIColor.clear.cgColor
        cell.imageProfile.layer.masksToBounds = true;

        cell.imageProfile.layer.shadowColor = UIColor.lightGray.cgColor;
        cell.imageProfile.layer.shadowOffset = CGSize(width: 2.0, height: 2.0);
        cell.imageProfile.layer.shadowRadius = 2.0;
        cell.imageProfile.layer.shadowOpacity = 2.0;
        cell.imageProfile.layer.masksToBounds = false;
        cell.imageProfile.layer.shadowPath = UIBezierPath(roundedRect: cell.imageProfile.bounds, cornerRadius: cell.imageProfile.layer.cornerRadius).cgPath

                    cell.imageProfile.backgroundColor = UIColor.white

    }

    return cell
}
</code>```

But it is not working properly.

Can anyone tell me how to achieve the above design using UICollectionView?

答:
Look at the red line for the cell in the center

The cell itself does not have shadow effects. The shadow is on the neighbor cells. So what you need to do here is to ask the cell to "overlay" on other cells.

Simply call cell.clipToBounds = true to allow your center cell to overlay on neighbor cells. Then make sure you expend your shadow effect out of the center cell.

ContentLicense: CC BY-SA 3.0

Body:
I have UICollectionView in which the centre cell will be highlighted as shown below image.

i have used following code to make shadow around the center cell.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell : STSuggestStyleCell = collectionView.dequeueReusableCell(for: indexPath)

    if indexPath.row == 4{

        cell.imageProfile.layer.cornerRadius = 2.0
        cell.imageProfile.layer.borderWidth = 1.0;
        cell.imageProfile.layer.borderColor = UIColor.clear.cgColor
        cell.imageProfile.layer.masksToBounds = true;

        cell.imageProfile.layer.shadowColor = UIColor.lightGray.cgColor;
        cell.imageProfile.layer.shadowOffset = CGSize(width: 2.0, height: 2.0);
        cell.imageProfile.layer.shadowRadius = 2.0;
        cell.imageProfile.layer.shadowOpacity = 2.0;
        cell.imageProfile.layer.masksToBounds = false;
        cell.imageProfile.layer.shadowPath = UIBezierPath(roundedRect: cell.imageProfile.bounds, cornerRadius: cell.imageProfile.layer.cornerRadius).cgPath

                    cell.imageProfile.backgroundColor = UIColor.white

    }

    return cell
}

But it is not working properly.

Can anyone tell me how to achieve the above design using UICollectionView?


问:
Two-key encryption/decryption?
I'm looking to store some fairly sensitive data using PHP and MySQL and will be using some form of reversible encryption to do so since I need to get the data back out in plain text for it to be of any use.

I'll be deriving the encryption key from the users' username/password combination but I'm stumped for what to do in the (inevitable) event of a password being forgotten. I realise that the purpose of encryption is that it can only be undone using the correct key but this must have been addressed before..

I'm trying to get my head around whether or not public key cryptography would apply to the problem but all I can think of is that the private key will still need to be correct to decrypt the data..

Any ideas?

答:
Basically, if you encrypt something, and lose the encryption key, you're screwed.

When it comes to securing data, you need to consider why you're securing it, and what you're attempting to secure it against. And what tradeoffs are worth making in order to do so - the only truly secure system is one that is completely isolated from the internet, which is a level of security that is self-defeating for most applications.

So here are some questions to ask yourself:

If someone compromises my database, is it acceptable for them to be able to access this data?

What if someone compromises my entire application stack?

If the answers to the above two questions are "no", then the key material must be held by the user. And they will lose access to their data if they lose the key.

You can provide an option for manual key recovery if you also have a "master key" that you don't store anywhere near your application, only you hold it and you use it to manually reset passwords. If that's also not an option (say, only the user should be able to access the data, not the system administrator), then you're going to have to make a compromise somewhere.

ContentLicense: CC BY-SA 2.5

Title: Two-key encryption/decryption?


问:
[Error: failed to connect to [localhost:27017]] from NodeJS to mongodb
I am having problem connecting to MongoDB from NodeJS using following sample code. I tried running "mongod" with or without sudo but nodejs code still fail to connect. I am able to successfully connect to database using "mongo".

Running on  : MAC OS 10.6.8

```<code>   var mongoClient = require('mongodb').MongoClient;
   mongoClient.connect("mongodb://localhost:27017/test", function(error, db) {
        if(!error){
             console.log("We are connected");
        }
        else
           console.dir(error);
    });
</code>```

get following error running above code : [Error: failed to connect to [localhost:27017]]

Also tried mongoose but similar error:

```<code>    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/test');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
          console.log("DB connected");
    // yay!
    });
</code>```

Output:   connection error: [Error: failed to connect to [localhost:27017]]

Here is the log of mongod

```<code>mongod --help for help and startup options
2014-07-11T23:33:47.843-0700 kern.sched unavailable
2014-07-11T23:33:47.849-0700 [initandlisten] MongoDB starting : pid=29942 port=27017 dbpath=/data/db 64-bit host=usc8bcc8a0d0b1
2014-07-11T23:33:47.849-0700 [initandlisten]
2014-07-11T23:33:47.849-0700 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-07-11T23:33:47.849-0700 [initandlisten] db version v2.6.3
2014-07-11T23:33:47.849-0700 [initandlisten] git version: nogitversion
2014-07-11T23:33:47.849-0700 [initandlisten] build info: Darwin usc8bcc8a0d0b1 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
2014-07-11T23:33:47.849-0700 [initandlisten] allocator: system
2014-07-11T23:33:47.849-0700 [initandlisten] options: {}
2014-07-11T23:33:47.850-0700 [initandlisten] journal dir=/data/db/journal
2014-07-11T23:33:47.850-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-07-11T23:33:47.901-0700 [initandlisten] waiting for connections on port 27017
2014-07-11T23:34:47.901-0700 [clientcursormon] mem (MB) res:48 virt:2810
2014-07-11T23:34:47.901-0700 [clientcursormon]  mapped (incl journal view):320
2014-07-11T23:34:47.901-0700 [clientcursormon]  connections:0
</code>```

答:
yes , I came across this error too, and my hosts is as follow:

127.0.0.1 xxxxxx(the ip of my computer)

and when I ran npm start in express project, it got an error like that . After I tried to change the mapping of 127.0.0.1 to localhost, it had no error.

Body:
I am having problem connecting to MongoDB from NodeJS using following sample code. I tried running "mongod" with or without sudo but nodejs code still fail to connect. I am able to successfully connect to database using "mongo".

Running on  : MAC OS 10.6.8

   var mongoClient = require('mongodb').MongoClient;
   mongoClient.connect("mongodb://localhost:27017/test", function(error, db) {
        if(!error){
             console.log("We are connected");
        }
        else
           console.dir(error);
    });

get following error running above code : [Error: failed to connect to [localhost:27017]]

Also tried mongoose but similar error:

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/test');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
          console.log("DB connected");
    // yay!
    });

Output:   connection error: [Error: failed to connect to [localhost:27017]]

Here is the log of mongod

mongod --help for help and startup options
2014-07-11T23:33:47.843-0700 kern.sched unavailable
2014-07-11T23:33:47.849-0700 [initandlisten] MongoDB starting : pid=29942 port=27017 dbpath=/data/db 64-bit host=usc8bcc8a0d0b1
2014-07-11T23:33:47.849-0700 [initandlisten]
2014-07-11T23:33:47.849-0700 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-07-11T23:33:47.849-0700 [initandlisten] db version v2.6.3
2014-07-11T23:33:47.849-0700 [initandlisten] git version: nogitversion
2014-07-11T23:33:47.849-0700 [initandlisten] build info: Darwin usc8bcc8a0d0b1 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
2014-07-11T23:33:47.849-0700 [initandlisten] allocator: system
2014-07-11T23:33:47.849-0700 [initandlisten] options: {}
2014-07-11T23:33:47.850-0700 [initandlisten] journal dir=/data/db/journal
2014-07-11T23:33:47.850-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-07-11T23:33:47.901-0700 [initandlisten] waiting for connections on port 27017
2014-07-11T23:34:47.901-0700 [clientcursormon] mem (MB) res:48 virt:2810
2014-07-11T23:34:47.901-0700 [clientcursormon]  mapped (incl journal view):320
2014-07-11T23:34:47.901-0700 [clientcursormon]  connections:0


问:
How to implement CSRF protection in Ajax calls using express.js (looking for complete example)?
I am trying to implement CSRF protection in an app built using node.js using the express.js framework. The app makes abundant use of Ajax post calls to the server. I understand that the connect framework provides CSRF middleware, but I am not sure how to implement it in the scope of client-side Ajax post requests.

There are bits and pieces about this in other Questions posted here in stackoverflow, but I have yet to find a reasonably complete example of how to implement it from both the client and server sides.

Does anyone have a working example they care to share on how to implement this? Most of the examples I have seen, assume you are rendering the form on the server-side and then sending it (along with the embedded csrf_token form field) to the client-side. In my app, all content is rendered on the client-side (including templates) via Backbone.js. All the server does is provide values in JSON format, which are utilized by various Models in Backbone.js on the client-side.  By my understanding I would need to retrieve the csrf_token via ajax first before it can be used.  However, I am concerned this may be problematic from a security standpoint. Is this a valid concern?

答:
1. Add csrf protection middleware:

```<code>app.use(csrf({cookie: true}));

// csrf middleware
app.use(function (req, res, next) {
   res.cookie('X-CSRF-Token', req.csrfToken());
   // this line below is for using csrfToken value in normal forms (as a hidden input)
   res.locals.csrfToken = req.csrfToken();
   next();
});

// routing setup goes here
</code>```

2. Add a beforeSend callback using $.ajaxSetup: (add this somewhere before all your ajax calls)

```<code>$.ajaxSetup({
beforeSend: function (xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRF-Token", getCookie('X-CSRF-Token'));
    }
}
});
</code>```

3. That's it!  now you can send ajax requests and you don't need to add anything in headers or as a request parameter to pass through csrf.

Body:
1. Add csrf protection middleware:

app.use(csrf({cookie: true}));

// csrf middleware
app.use(function (req, res, next) {
   res.cookie('X-CSRF-Token', req.csrfToken());
   // this line below is for using csrfToken value in normal forms (as a hidden input)
   res.locals.csrfToken = req.csrfToken();
   next();
});

// routing setup goes here

2. Add a beforeSend callback using $.ajaxSetup: (add this somewhere before all your ajax calls)

$.ajaxSetup({
beforeSend: function (xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRF-Token", getCookie('X-CSRF-Token'));
    }
}
});

3. That's it!  now you can send ajax requests and you don't need to add anything in headers or as a request parameter to pass through csrf.


问:
Element like a PageView in android
I'm creating an app for both Androids and iOS. In a view, I'm using a pageView as a subview (I mean it doesn't fill all the viewController) in the iOS app.

I need to implement the same thing in Android and I don't know what element I should use.

Here you have an example of a page view.

Thanks for the help.

答: Use a ViewPager with multiple fragments to get the same effect.

Title: Element like a PageView in android


问:
'AWSCognito' is not defined
I have used the following example to implement AWS Cognito in nodeJS but i am facing the error
"'AWSCognito' is not defined  no-undef"

Reference Link : https://github.com/aws/amazon-cognito-identity-js/

Following is my code in App.js file. I have used react-app.

```<code>    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    import { CognitoUserPool, CognitoUserAttribute, CognitoUser } from 'amazon-cognito-identity-js';

    class App extends Component {
      constructor(props, context){
        super(props, context);
        this.state = {
          items: []
        }
      }
      render() {
        const {items} = this.state;
        return (
          <div className="App">
            <div className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <h2>Welcome to React</h2>
            </div>
            <p className="App-intro">
              To get started, edit <code>src/App.js</code> and save to reload.
            </p>
            <button onClick={(e) => this.doRegister(e)}>Register</button>
            { items.map(item => <p>{item.id}</p>) }
          </div>
        );
      }
      doRegister(){
        console.log("Register User");
        var poolData = {
            UserPoolId : 'xxxxxxxxxxx', // Your user pool id here
            ClientId : 'xxxxxxxxxxxxxxxxxx' // Your client id here
        };

        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
        console.debug(userPool);
      }
    }

    export default App;
</code>```

This is the code in package.json. You can see the aws-cognito-identity library is already added.

```<code>    {
      "name": "my-app",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "amazon-cognito-identity-js": "^1.19.0",
        "react": "^15.6.1",
        "react-dom": "^15.6.1",
        "react-scripts": "1.0.10"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject"
      },
      "devDependencies": {
        "json-loader": "^0.5.4",
        "webpack": "^3.0.0"
      }
    }
</code>```

Why it is showing AWSCognito is undefined. Is there anything missing in my code related to AWS Cognito?

答:
You need the AWS SDK for JavaScript in addition to Amazon Cognito Identity SDK for JavaScript.

```<code>npm install aws-sdk --save
</code>```

Then, you can import it as:

```<code>import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js';

class App extends Component {
  ...
  const poolData = { UserPoolId: 'YOUR_USER_POOL_ID', ClientId: 'YOUR_CLIENT_ID' };
  const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
  ...
}
</code>```

Title: 'AWSCognito' is not defined

Body:
I have used the following example to implement AWS Cognito in nodeJS but i am facing the error
"'AWSCognito' is not defined  no-undef"

Reference Link : https://github.com/aws/amazon-cognito-identity-js/

Following is my code in App.js file. I have used react-app.

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    import { CognitoUserPool, CognitoUserAttribute, CognitoUser } from 'amazon-cognito-identity-js';

    class App extends Component {
      constructor(props, context){
        super(props, context);
        this.state = {
          items: []
        }
      }
      render() {
        const {items} = this.state;
        return (

Welcome to React

              To get started, edit src/App.js and save to reload.

            <button onClick={(e) => this.doRegister(e)}>Register</button>
            { items.map(item =>
{item.id}
) }

        );
      }
      doRegister(){
        console.log("Register User");
        var poolData = {
            UserPoolId : 'xxxxxxxxxxx', // Your user pool id here
            ClientId : 'xxxxxxxxxxxxxxxxxx' // Your client id here
        };

        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
        console.debug(userPool);
      }
    }

    export default App;

This is the code in package.json. You can see the aws-cognito-identity library is already added.

    {
      "name": "my-app",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "amazon-cognito-identity-js": "^1.19.0",
        "react": "^15.6.1",
        "react-dom": "^15.6.1",
        "react-scripts": "1.0.10"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject"
      },
      "devDependencies": {
        "json-loader": "^0.5.4",
        "webpack": "^3.0.0"
      }
    }

Why it is showing AWSCognito is undefined. Is there anything missing in my code related to AWS Cognito?

Body:
You need the AWS SDK for JavaScript in addition to Amazon Cognito Identity SDK for JavaScript.

npm install aws-sdk --save

Then, you can import it as:

import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js';

class App extends Component {
  ...
  const poolData = { UserPoolId: 'YOUR_USER_POOL_ID', ClientId: 'YOUR_CLIENT_ID' };
  const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
  ...
}


问:
Transform a list into a map - foreach or streams?
I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

```<code>    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));
</code>```

Would you stick to the old approach or go with new lambda expressions?

答:
You could write the for-each with stream. eg.</p>

```<code>abk.stream()
    .filter(Object::notNull)
    .forEach(s->map.put(s, STATIC_VAL));
</code>```

Body:
I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));

Would you stick to the old approach or go with new lambda expressions?

Body:
You could write the for-each with stream. eg.

abk.stream()
    .filter(Object::notNull)
    .forEach(s->map.put(s, STATIC_VAL));


问:
MS Access 2013 : Reserved error ( -7713 ): There is no message for this error
In MS Access 2013, an error displays after trying to open/view a Query: Reserved error (-7713): There is no message for this error</p>

答:
Please find solution describe below.

Replace dbFailonerror with dbSeeChanges when using SQL update Statements

```<code>"CurrentDb.Execute StrSQL, dbSeeChanges"
</code>```

Body:
Please find solution describe below.

Replace dbFailonerror with dbSeeChanges when using SQL update Statements

"CurrentDb.Execute StrSQL, dbSeeChanges"


问:
Install python module by first creating the wheel
I just download files to build an API in python - a brief tuto on that API suggest that in order to install it a module, the following must be performed:

```<code>* you can use this to build a wheel

python3 setup.py bdist_wheel

* you can use this to install the wheel

python3 -m pip install --user --upgrade dist/ibapi-9.73.1-py3-none-any.whl
</code>```

This seems pretty straightforward, however I am completely unfamilar with that aspect of python and a bit at loss... I tried to run the command python3 setup.py bdist_wheel both in the folder containing the API and by first entering a python 3 environement (by typing source activate python3 - i am using anaconda. Both return the error setup.py cannot be found.

Anyone knows where both command should be run in order to properly install the module?

答:
You can follow the steps below:

cd  C:\TWS API\source\pythonclient

python setup.py bdist_wheel

cd C:\Python36\Scripts

python -m pip install --upgrade "C:\TWS API\source\pythonclient\dist\ibapi-9.73.2-py3-none-any.whl"

Note: Change python and API versions to the ones you are using.

Body:
I just download files to build an API in python - a brief tuto on that API suggest that in order to install it a module, the following must be performed:

* you can use this to build a wheel

python3 setup.py bdist_wheel

* you can use this to install the wheel

python3 -m pip install --user --upgrade dist/ibapi-9.73.1-py3-none-any.whl

This seems pretty straightforward, however I am completely unfamilar with that aspect of python and a bit at loss... I tried to run the command python3 setup.py bdist_wheel both in the folder containing the API and by first entering a python 3 environement (by typing source activate python3 - i am using anaconda. Both return the error setup.py cannot be found.

Anyone knows where both command should be run in order to properly install the module?


问:
ListView replaces first object instead of adding a new one
I created a test project, and in that project I am trying to create a listview that the user can add to when they click a button. The button opens an new activity with an editText and another button to go back to the listview activity and an item should have been added. It works the first time, but when I add another Item it replaces the old one. I have search for a while now, and all the other answer don't seem to help me. Thanks in advance.

```<code>public class MainActivity extends Activity {

ListView simpleList;
String input;
ArrayList<Item> listItems =new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    simpleList = (ListView) findViewById(R.id.listView);
    addData();
    MyAdapter myAdapter=new MyAdapter(this,R.layout.row, listItems);
    simpleList.setAdapter(myAdapter);
}

public void addData(){
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        input = extras.getString("Homework");
        listItems.add(new Item(input, input, input));
    }
}

public void toInput(View view){
    Intent intent = new Intent(this, inputScreen.class);
    startActivity(intent);
}}
</code>```

This is my main activity, the adapter is a custom adapter that is made in this class.

```<code>public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> listItems = new ArrayList<>();

public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
    super(context, textViewResourceId, objects);
    listItems = objects;
}

public int getCount(){
    return super.getCount();
}

public View getView(int position, View convertView, ViewGroup parent){
    View v = convertView;
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = inflater.inflate(R.layout.row, null);
    TextView textView = (TextView) v.findViewById(R.id.homeworkDisplay);
    TextView textView2 = (TextView) v.findViewById(R.id.dueDisplay);
    TextView textView3 = (TextView) v.findViewById(R.id.classDisplay);
    textView.setText(listItems.get(position).getHomework());
    textView2.setText(listItems.get(position).getDate());
    textView3.setText(listItems.get(position).getClasses());
    return v;
}}
</code>```

The string that is added to the listview is sent from the another activity that gets it from an editText, here is it's class

```<code>public class inputScreen extends Activity{

EditText userInput;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input_screen);
    userInput = (EditText) findViewById(R.id.editText);

}

public void sendInfo(View view){
    Intent goingBack = new Intent(this,MainActivity.class);
    goingBack.putExtra("Homework", userInput.getText().toString());
    startActivity(goingBack);

}}
</code>```

I know there is alot of code there, you don't need to go through it all as I am sure the problem is in MainActivity. I have another class called items that returns homework. Thank you!

答:
Used startActivity() is not correct.
your activity stack is like this :

the start
~~~~~~~~~~~~
MainActivity
~~~~~~~~~~~~

after you call toInput in MainActivity()

~~~~~~~~~~~~
InputScreen(activity)
MainActivity
~~~~~~~~~~~~

then when you call send() in InputScreen

~~~~~~~~~~~~
MainActivity
InputScreen
MainActivity
~~~~~~~~~~~~

see what's happening?

the first time in InputScreen you called send() start MainActivity with extras

then you started a new MainActivity ,then went the addData() ,you got data, and changed listView.

but when you do it again , you always start new Activities ,so only the first one was gonna change

always repeat the first step always start a new activity

you should call startActivityForResult() in MainActivity to start inputScreen and override the onActivityResult method in MainActivity

just google startActivity and startActivityForResult you will work this out .
and anther key word you should google is ,listView --> data source

sorry,I am not a native English speaker, if I did something wrong ,please forgive me ~~~~

Body:
I created a test project, and in that project I am trying to create a listview that the user can add to when they click a button. The button opens an new activity with an editText and another button to go back to the listview activity and an item should have been added. It works the first time, but when I add another Item it replaces the old one. I have search for a while now, and all the other answer don't seem to help me. Thanks in advance.

public class MainActivity extends Activity {

ListView simpleList;
String input;
ArrayList<Item> listItems =new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    simpleList = (ListView) findViewById(R.id.listView);
    addData();
    MyAdapter myAdapter=new MyAdapter(this,R.layout.row, listItems);
    simpleList.setAdapter(myAdapter);
}

public void addData(){
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        input = extras.getString("Homework");
        listItems.add(new Item(input, input, input));
    }
}

public void toInput(View view){
    Intent intent = new Intent(this, inputScreen.class);
    startActivity(intent);
}}

This is my main activity, the adapter is a custom adapter that is made in this class.

public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> listItems = new ArrayList<>();

public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
    super(context, textViewResourceId, objects);
    listItems = objects;
}

public int getCount(){
    return super.getCount();
}

public View getView(int position, View convertView, ViewGroup parent){
    View v = convertView;
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = inflater.inflate(R.layout.row, null);
    TextView textView = (TextView) v.findViewById(R.id.homeworkDisplay);
    TextView textView2 = (TextView) v.findViewById(R.id.dueDisplay);
    TextView textView3 = (TextView) v.findViewById(R.id.classDisplay);
    textView.setText(listItems.get(position).getHomework());
    textView2.setText(listItems.get(position).getDate());
    textView3.setText(listItems.get(position).getClasses());
    return v;
}}

The string that is added to the listview is sent from the another activity that gets it from an editText, here is it's class

public class inputScreen extends Activity{

EditText userInput;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input_screen);
    userInput = (EditText) findViewById(R.id.editText);

}

public void sendInfo(View view){
    Intent goingBack = new Intent(this,MainActivity.class);
    goingBack.putExtra("Homework", userInput.getText().toString());
    startActivity(goingBack);

}}

I know there is alot of code there, you don't need to go through it all as I am sure the problem is in MainActivity. I have another class called items that returns homework. Thank you!


问:
Group by column value
I have created a custom module and in admin grid where i am calling module collection.

```<code>protected function _prepareCollection()
  {
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
    $collection = Mage::getModel('mymodule/custom')->getCollection();
    $this->setCollection($collection);
    return parent::_prepareCollection();
  }
</code>```

I want to use group by a column value in my module table..

I tried this

```<code>protected function _prepareCollection()
      {
        Mage::setIsDeveloperMode(true);
        ini_set('display_errors', 1);
        $collection = Mage::getModel('mymodule/custom')->getCollection()->getSelect()->group('column_2');
        $this->setCollection($collection);
        return parent::_prepareCollection();
      }
</code>```

but it doesn't work its throwing an error

```<code>Unrecognized method 'setPageSize()'
</code>```

which i am not using anywhere in my grid.php

can anybody suggest me the problem with my code or solution of my problem

答:
//Try with below code.</p>

```<code>$collection = Mage::getModel('mymodule/custom')->getCollection();
$collection->getSelect()->group('column_2');
</code>```

Title: Group by column value

Body:
I have created a custom module and in admin grid where i am calling module collection.

protected function _prepareCollection()
  {
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
    $collection = Mage::getModel('mymodule/custom')->getCollection();
    $this->setCollection($collection);
    return parent::_prepareCollection();
  }

I want to use group by a column value in my module table..

I tried this

protected function _prepareCollection()
      {
        Mage::setIsDeveloperMode(true);
        ini_set('display_errors', 1);
        $collection = Mage::getModel('mymodule/custom')->getCollection()->getSelect()->group('column_2');
        $this->setCollection($collection);
        return parent::_prepareCollection();
      }

but it doesn't work its throwing an error

Unrecognized method 'setPageSize()'

which i am not using anywhere in my grid.php

can anybody suggest me the problem with my code or solution of my problem

Body:
//Try with below code.

$collection = Mage::getModel('mymodule/custom')->getCollection();
$collection->getSelect()->group('column_2');


问:
Hatching frequency on plots
Suppose I have the following script that produces a plot (as shown below) where some datapoints have hatching. At DPI = 200, the hatching frequency (space between dots) is good, but if I want to increase the resolution of the plot (DPI = 600 for example), the dots become very fine. Is there a way to set the gap between dots? Thanks in advance.

```<code>import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

Sig = np.random.rand(50,50)
Sig = np.ma.masked_greater(Sig, 0.25)

f, ax1 = plt.subplots(1,1)

ax1.pcolor(np.linspace(0,90,50),np.linspace(0,50,50),Sig, hatch=".",alpha=0)

fig = plt.gcf()
fig.set_size_inches(8, 8)
fig.savefig('Trial.png',bbox_inches='tight', dpi=200)
</code>```

答:
There is no way to accurately control the spacing between hatch patterns. You do have the option to increase  the hatch density though. Instead of hatch = "." you can add the symbol more often, hatch="..."; this will produce a denser pattern.

The above figure has been produced with standard dpi of 100.
Changing the dpi to 300 gives the following image:

As can be seen the issue of a changed hatch density for different dpi is not there anymore; it has been brought up in this issue and afterwards been fixed. The solution is thus to update to the newest matplotlib version.

Title: Hatching frequency on plots

Body:
Suppose I have the following script that produces a plot (as shown below) where some datapoints have hatching. At DPI = 200, the hatching frequency (space between dots) is good, but if I want to increase the resolution of the plot (DPI = 600 for example), the dots become very fine. Is there a way to set the gap between dots? Thanks in advance.

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

Sig = np.random.rand(50,50)
Sig = np.ma.masked_greater(Sig, 0.25)

f, ax1 = plt.subplots(1,1)

ax1.pcolor(np.linspace(0,90,50),np.linspace(0,50,50),Sig, hatch=".",alpha=0)

fig = plt.gcf()
fig.set_size_inches(8, 8)
fig.savefig('Trial.png',bbox_inches='tight', dpi=200)


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
In my experience, more often than not, people null out references out of paranoia not out of necessity. Here is a quick guideline:

If object A references object B and you no longer need this reference and object A is not eligible for garbage collection then you should explicitly null out the field. There is no need to null out a field if the enclosing object is getting garbage collected anyway. Nulling out fields in a dispose() method is almost always useless.

There is no need to null out object references created in a method. They will get cleared automatically once the method terminates. The exception to this rule is if you're running in a very long method or some massive loop and you need to ensure that some references get cleared before the end of the method. Again, these cases are extremely rare.

I would say that the vast majority of the time you will not need to null out references. Trying to outsmart the garbage collector is useless. You will just end up with inefficient, unreadable code.

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

OwnerDisplayName: Gili

ContentLicense: CC BY-SA 4.0


问:
Form validation with jquery - return false
Can some one tell my why the folowing code doesn't work. It alerts as it should. But it return true afterwards, even if a field is empty.</p>

```<code><form id="theform" method="post" action="mailme.php">
<input id="field1" name="a" value="field1" type="text" />
<input id="field2" name="b" value="field2" type="text" />
<input id="field3" name="c" value="field3" type="text" />
<input id="field4" name="d" value="field4" type="text" />

<input type="submit" />
</form>
<script>
$('#theform').submit(function(){
    $('#theform input[type=text]').each(function(n,element){
        if ($(element).val()=='') {
             alert('The ' + element.id+' must have a value');
             return false;
        }
    });
    return true;
});

</script>
</code>```

答:
You're returning from the .each() callback function, a return false breaks that, but doesn't return from the outer function (your submit handler), instead you should do something like this:

```<code>$('#theform').submit(function(){
    var result = true;
    $('#theform input[type=text]').each(function(n,element){
        if ($(element).val()=='') {
             alert('The ' + element.id + ' must have a value');
             return result = false;
        }
    });
    return result;
});
</code>```

In this it finds the first empty element , sets the result to false and returns in one statement, then returns the result from the outer function...if there were no empty fields, this would still be true.

Body:
Can some one tell my why the folowing code doesn't work. It alerts as it should. But it return true afterwards, even if a field is empty.

<form id="theform" method="post" action="mailme.php">
<input id="field1" name="a" value="field1" type="text" />
<input id="field2" name="b" value="field2" type="text" />
<input id="field3" name="c" value="field3" type="text" />
<input id="field4" name="d" value="field4" type="text" />

<input type="submit" />
</form>

Body:
You're returning from the .each() callback function, a return false breaks that, but doesn't return from the outer function (your submit handler), instead you should do something like this:

$('#theform').submit(function(){
    var result = true;
    $('#theform input[type=text]').each(function(n,element){
        if ($(element).val()=='') {
             alert('The ' + element.id + ' must have a value');
             return result = false;
        }
    });
    return result;
});

In this it finds the first empty element , sets the result to false and returns in one statement, then returns the result from the outer function...if there were no empty fields, this would still be true.


问:
Is there a way in go to convert a []byte slice to an io.Reader?

I have just started with go and was wondering, if it is possible to convert an []byte slice to an io.Reader. The Otherway around is possible as shown in ioutil.ReadAll.

If not is it possible to use code.google.com/p/go.net/html.Tokenizer somehow with a byte slice?

答:
You can use the NewReader in the bytes package:

```<code>in := bytes.NewReader(b []byte)
</code>```

https://golang.org/pkg/bytes/#NewReader

Body:
You can use the NewReader in the bytes package:

in := bytes.NewReader(b []byte)

https://golang.org/pkg/bytes/#NewReader


答:
Check with this:</p>

```<code>protected function _prepareCollection()
{
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
    $collection = Mage::getModel('mymodule/custom')->getCollection();
    $collection->getSelect()->group('column_2');
    $this->setCollection($collection);
    return parent::_prepareCollection();
}
</code>```

Title: Group by column value

Body:
Check with this:

protected function _prepareCollection()
{
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
    $collection = Mage::getModel('mymodule/custom')->getCollection();
    $collection->getSelect()->group('column_2');
    $this->setCollection($collection);
    return parent::_prepareCollection();
}


问:
mysql where clause based on another query
I am trying to get a single query to work rather than two where the first makes an array and then loop through the other.

The first query returns a set of users, and then I want to query another table based on these users, with a bit of research I ended up with this but it doesn't work...

```<code>SELECT FreeText, (
    SELECT EmailAddress FROM customers WHERE AccessLevel = 'callcentre'
) AS User FROM orders WHERE FreeText = User
</code>```

I would prefer to do a single query but if thats not possible then I will work around it with the first creating and array then looping through the second

Any help appreciated

Example results, User would contain names, e.g. lsmith, nrowe, pmerle

Then the second query would retrurn the order rows where they are set as the FreeTxt

Example table structure

```<code>customers table
Id, Email,  Add1,        Add2    ect...
23, lsmith, someaddress, road...

Orders
Id, customerId, FreeTxt, Product
54, 23,         lsmith,  mob
</code>```

Output for this would be lsmith + Id from orders I only asked for FreeTxt whilst testing

答:
The subquery  is not necessary you can do the same  with a inner join<br>
but be sure that the  orders.FreeText  = customers.EmailAddress really match </p>

```<code>  SELECT orders.FreeText, customers.EmailAddress
  FROM orders
  INNER JOIN customer on orders.FreeText  = customers.EmailAddress
        and customers.AccessLevel = 'callcentre';
</code>```

Body:
I am trying to get a single query to work rather than two where the first makes an array and then loop through the other.

The first query returns a set of users, and then I want to query another table based on these users, with a bit of research I ended up with this but it doesn't work...

SELECT FreeText, (
    SELECT EmailAddress FROM customers WHERE AccessLevel = 'callcentre'
) AS User FROM orders WHERE FreeText = User

I would prefer to do a single query but if thats not possible then I will work around it with the first creating and array then looping through the second

Any help appreciated

Example results, User would contain names, e.g. lsmith, nrowe, pmerle

Then the second query would retrurn the order rows where they are set as the FreeTxt

Example table structure

customers table
Id, Email,  Add1,        Add2    ect...
23, lsmith, someaddress, road...

Orders
Id, customerId, FreeTxt, Product
54, 23,         lsmith,  mob

Output for this would be lsmith + Id from orders I only asked for FreeTxt whilst testing

Body:
The subquery  is not necessary you can do the same  with a inner join

but be sure that the  orders.FreeText  = customers.EmailAddress really match

  SELECT orders.FreeText, customers.EmailAddress
  FROM orders
  INNER JOIN customer on orders.FreeText  = customers.EmailAddress
        and customers.AccessLevel = 'callcentre';


问:
Scheduled task running powershell script with SendKeys and getting Access is denied
I have a scheduled task that runs a power shell console window with script (script is always runned from machine that has that scheduled task, so there is no remote task calling) that contains:

```<code>Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('~');
</code>```

Problem is when I'm logged (remotely or locally) it runs smoothly (power shell console opens, procedure runs, key is pressed and procedure completes), but when I log off script is throwing exception in power shell console window:

```<code>Exception calling "SendWait" with "1" argument(s): "Access is denied"
At C:\Testing\Powershell\PageFeature.ps1:4 char:2
+  [System.Windows.Forms.SendKeys]::SendWait('~');
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
</code>```

I set task to run with my credentials even when I log off, and still getting messages in the console window.

What could be the root problem of this?

答:
maybe just try:</p>

```<code>$obj = new-object -ComObject WScript.Shell
$obj.SendKeys("~")
</code>```

Body:
I have a scheduled task that runs a power shell console window with script (script is always runned from machine that has that scheduled task, so there is no remote task calling) that contains:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('~');

Problem is when I'm logged (remotely or locally) it runs smoothly (power shell console opens, procedure runs, key is pressed and procedure completes), but when I log off script is throwing exception in power shell console window:

Exception calling "SendWait" with "1" argument(s): "Access is denied"
At C:\Testing\Powershell\PageFeature.ps1:4 char:2
+  [System.Windows.Forms.SendKeys]::SendWait('~');
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception

I set task to run with my credentials even when I log off, and still getting messages in the console window.

What could be the root problem of this?

Body:
maybe just try:

$obj = new-object -ComObject WScript.Shell
$obj.SendKeys("~")


问:
Filling of a structure using memcpy
This is my code. I thought I will be getting a SegFault on b2->x.pointer1->data because I didn't malloc the b2->x.pointer1. Can anybody please give me some explanation to it? What values were copied to b2->x.pointer1 while doing memcpy? And also regarding the book-keeping of struct *b2 particularly which was filled by memcpy, that how it kept a record of its members? All my motive is to know that how b2->x.pointer1 got its memory on heap.

```<code>struct A
{
    int data;
};

struct B
{
    int data;
    union X
    {
        struct A *pointer1;
        //another
    }x;
};

int main(int argc, char **argv)
{

    struct B *b1 = (struct B*) malloc(sizeof(struct B));
    b1->data = 100;
    b1->x.pointer1 = (struct A*) malloc(sizeof(struct A));
    b1->x.pointer1->data = 1;

    struct B *b2 = (struct B*) malloc(sizeof(struct B));
    //b2->x.pointer1 = (struct A*) malloc(sizeof(struct A));

    memcpy(b2, b1, sizeof(struct B));

    printf("%d", b2->x.pointer1->data);

    return 0;
}
</code>```

And what if I'll free(b1)? Will it free the b1->x.pointer1 too or will there be some memory leak here?

答:
In addition to Michael Walz's answer...

Can anybody please give me some explanation to it?

memcpy does a bit by bit copy of the specified number of bytes. That's why you don't segfault. If you go down and look in the memory, you will find that the bits in b2 have become exactly same as b1.

What values were copied to b2->x.pointer1 while doing memcpy?

The data copied will be same as source (b1 in this case) from where you are copying. For the computer, b1 and b2 are just two different locations which have the same bit pattern.

Title: Filling of a structure using memcpy

Body:
This is my code. I thought I will be getting a SegFault on b2->x.pointer1->data because I didn't malloc the b2->x.pointer1. Can anybody please give me some explanation to it? What values were copied to b2->x.pointer1 while doing memcpy? And also regarding the book-keeping of struct *b2 particularly which was filled by memcpy, that how it kept a record of its members? All my motive is to know that how b2->x.pointer1 got its memory on heap.

struct A
{
    int data;
};

struct B
{
    int data;
    union X
    {
        struct A *pointer1;
        //another
    }x;
};

int main(int argc, char **argv)
{

    struct B *b1 = (struct B*) malloc(sizeof(struct B));
    b1->data = 100;
    b1->x.pointer1 = (struct A*) malloc(sizeof(struct A));
    b1->x.pointer1->data = 1;

    struct B *b2 = (struct B*) malloc(sizeof(struct B));
    //b2->x.pointer1 = (struct A*) malloc(sizeof(struct A));

    memcpy(b2, b1, sizeof(struct B));

    printf("%d", b2->x.pointer1->data);

    return 0;
}

And what if I'll free(b1)? Will it free the b1->x.pointer1 too or will there be some memory leak here?


问:
How can I write SQL Query?
I need a request that displays the name and surname of the clients with the smallest credit limit - among married women who do not live in Japan, Brazil or Italy.

Diagram:

答:
This will Give all the people not in 'Japan', 'Brazil' or 'Italy') ,

```<code>Select C.Cust_first_name,C.Cust_Last_name from Customers C
          Inner Join Countries C1
               on C.Country_Id=C1.Country_Id
        Where C1.Country_Name Not in('Japan', 'Brazil' or 'Italy')
        and
    C.Cust_Credit_Limit=(Select Min(Cust_Credit_Limit) From from Customers C)
</code>```

If we Convert The Question to Code that will be the above code,
The Script would return the name and last name of person not in ('Japan', 'Brazil' or 'Italy') And has the lowest salary In the entire customer Base.

Title: How can I write SQL Query?

Body:
This will Give all the people not in 'Japan', 'Brazil' or 'Italy') ,

Select C.Cust_first_name,C.Cust_Last_name from Customers C
          Inner Join Countries C1
               on C.Country_Id=C1.Country_Id
        Where C1.Country_Name Not in('Japan', 'Brazil' or 'Italy')
        and
    C.Cust_Credit_Limit=(Select Min(Cust_Credit_Limit) From from Customers C)

If we Convert The Question to Code that will be the above code,
The Script would return the name and last name of person not in ('Japan', 'Brazil' or 'Italy') And has the lowest salary In the entire customer Base.


问:
Control the appearance of a Google Map from My Maps
I'm having a difficult time looking for instructions on how to customize the appearance of an embed map instance I've created in Google Maps and stored in My Maps. There are jquery plugins for generating and manipulating new map instances, but I haven't found any on how to manipulate existing map instance from My Maps.

Does anyone have a recommendation for a jquery plugin that can manipulate the appearance of a My Maps map instance?

答:
I figured it out: import the RSS/KML feed into a map overlay:

http://code.google.com/apis/maps/documentation/javascript/v2/services.html#XML_Overlays


问:
Why can't I add a constraint when creating the table?
```<code>CREATE TABLE `CHARSET`
   (
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    ADD constraint PK_80 PRIMARY KEY (CHARSET_CODE)

   ) ;
</code>```

Giving me a red pointer on the last line where i am trying to add constraint.

答:
Remove the ADD before contstraint, that should do the trick.

```<code>CREATE TABLE `CHARSET` (
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    CONSTRAINT PK_80 PRIMARY KEY (CHARSET_CODE)
);
</code>```

Body:
CREATE TABLE `CHARSET`
   (
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    ADD constraint PK_80 PRIMARY KEY (CHARSET_CODE)

   ) ;

Giving me a red pointer on the last line where i am trying to add constraint.

Body:
Remove the ADD before contstraint, that should do the trick.

CREATE TABLE `CHARSET` (
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    CONSTRAINT PK_80 PRIMARY KEY (CHARSET_CODE)
);


问:
can I place a input field within a link, without making the input a link too?
I have the following problem: I have a Newsletter Banner with some content (Text, Icons and stuff) and the most important: input for E-Mail+submitbutton.

Now I would like to link the whole newsletter banner to a subpage with more information about the newsletter, but when I then click the textfield or submitbutton I get redirected to the link...

Is there any solution for this problem?

Here is a fiddle showing the problem:
try to click the input and you see it´ll be a link.

https://jsfiddle.net/wu6js2v7/2/

Btw: its no solution for me to only party link the banner

答:
Okay, I had another idea, which works fine for this. Or better even 2 possibilities:

the first one is: position absolute the input (won´t work in my case, but maybe helps others)

the second one is ofc Javascript, I´m using a "data-link" attribute in the wrapperdiv and this does the magic:

```<code>$(".datalink_click").on("click", function(){
    var link = $(this).attr('data-link');
    window.location.href = link;
});
$(".datalink_click input").on("click", function(e){
    e.stopPropagation();
});
</code>```

Body:
Okay, I had another idea, which works fine for this. Or better even 2 possibilities:

the first one is: position absolute the input (won´t work in my case, but maybe helps others)

the second one is ofc Javascript, I´m using a "data-link" attribute in the wrapperdiv and this does the magic:

$(".datalink_click").on("click", function(){
    var link = $(this).attr('data-link');
    window.location.href = link;
});
$(".datalink_click input").on("click", function(e){
    e.stopPropagation();
});


问:
(NSFetchedResultsController): couldn't read cache file to update store info timestamps
I upgraded my project to Xcode 8. Now, I'm getting this error log with Xcode 8 and iOS 10 combination.

Setting the cacheName to nil in the below code seems fix it.

```<code>NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:NULL cacheName:@"myCache"];
</code>```

What should I do to get rid of this error log and use cache in my FRC?

答:
After paying more attention to the above error message, I could see that your App was creating a large amount of File Descriptors, opening files in a cache folder and never closing or releasing them.
So it better to disable the NSFetchedResultsController caching for now.

Hope Apple will fix the issue

Body:
I upgraded my project to Xcode 8. Now, I'm getting this error log with Xcode 8 and iOS 10 combination.

Setting the cacheName to nil in the below code seems fix it.

NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:NULL cacheName:@"myCache"];

What should I do to get rid of this error log and use cache in my FRC?


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答:
I have used it so far in two real projects very successfully. both are in the near real-time traffic information field (traffic as in cars on highways), distributed over several nodes, integrating messages between several parties, reliable backend systems. I'm not at liberty to give specifics on clients yet, when I do get the OK maybe it can be added as a reference.

Akka has really pulled through on those projects, even though we started when it was on version 0.7. (we are using scala by the way)

One of the big advantages is the ease at which you can compose a system out of actors and messages with almost no boilerplating, it scales extremely well without all the complexities of hand-rolled threading and you get asynchronous message passing between objects almost for free.

It is very good in modeling any type of asynchronous message handling. I would prefer to write any type of (web) services system in this style than any other style. (Have you ever tried to write an asynchronous web service (server side) with JAX-WS? that's a lot of plumbing). So I would say any system that does not want to hang on one of its components because everything is implicitly called using synchronous methods, and that one component is locking on something. It is very stable and the let-it-crash + supervisor solution to failure really works well. Everything is easy to setup programmatically and not hard to unit test.

Then there are the excellent add-on modules.
The Camel module really plugs in well into Akka and enables such easy development of asynchronous services with configurable endpoints.

I'm very happy with the framework and it is becoming a defacto standard for the connected systems that we build.


问:
Delegate for Limitation of characters in Objective c
I have a form which have Delegate for field to limit to enter 4 digits in a field.Now i have another field i want to use another limitation on different field in same form which can limit the field to enter only seven values.How can i use two delegate in same form, if i use them they show error that its twice used. This is the delegate which i have use for the first field.

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
</code>```

{

}

答:
Instead of using Delegates, rather look into one delegate doing everything...

You can use an if inside the delegate, differentiating between the textfields:

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == textField1)
    {
        if(range.length + range.location > 4)
        {
            return NO;
        }

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return newLength <= 4;
    }

    if (textField == textField2)
    {
        if(range.length + range.location > 7)
        {
            return NO;
        }

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return newLength <= 7;
    }
    return YES;
}
</code>```

Hope this helps...

Body:
I have a form which have Delegate for field to limit to enter 4 digits in a field.Now i have another field i want to use another limitation on different field in same form which can limit the field to enter only seven values.How can i use two delegate in same form, if i use them they show error that its twice used. This is the delegate which i have use for the first field.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

}

Body:
Instead of using Delegates, rather look into one delegate doing everything...

You can use an if inside the delegate, differentiating between the textfields:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == textField1)
    {
        if(range.length + range.location > 4)
        {
            return NO;
        }

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return newLength <= 4;
    }

    if (textField == textField2)
    {
        if(range.length + range.location > 7)
        {
            return NO;
        }

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return newLength <= 7;
    }
    return YES;
}

Hope this helps...


问:
Python export some list and put all in for loop
I am writing a program that exports monitoring data.

I have python code which sends API requests and gets a response as json in form of a dictionary.

Responses look like this:

```<code>[
  {
    "diskwrite": 667719532544,
    "name": "test-hostname",
    "maxmem": 536870912,
    "diskread": 876677015576,
    "mem": 496111616,
    "id": "qemu/102",
    "node": "node1",
    "template": 0,
    "cpu": 0.00947819269772254,
    "vmid": 102,
    "type": "qemu",
    "maxcpu": 2,
    "netout": 15081562546,
    "maxdisk": 10737418240,
    **"status": "running",**
    "netin": 15852619497,
    "disk": 0,
    "uptime": 3273086
  },
  {
    "maxcpu": 8,
    "type": "qemu",
    "vmid": 106,
    "cpu": 0.500598230113925,
    "template": 0,
    "node": "node1",
    "id": "qemu/106",
    "mem": 10341007360,
    "maxmem": 10737418240,
    "diskread": 8586078094720,
    "name": "some.other-hostname",
    "diskwrite": 6052378838016,
    "uptime": 1900411,
    "disk": 0,
    "netin": 4899018841106,
    **"status": "stopping",**
    "maxdisk": 107374182400,
    "netout": 4788420573355
  },
  ...
</code>```

I'd like to loop through all the hostnames and their items as is ("diskwrite", "mem", "cpu", etc) but I'd like to add these items to a dictionary only if they have a status of running ("status":"running").

```<code>ram_metric.set({'type': "total"}, ram[0])
cpu_metric.set({'type': 'average', 'interval': '5 minutes'}, cpu[0])
</code>```

I also need a loop that will make this line of code and for every "name" item creating this row with host=name:

```<code>ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
                       {'host': host})
cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
                       {'host': host})
</code>```

Please, I don't know how to do that.

答:
I can try to help.

The response you are getting is a list with dictionaries and you are only interested if the status is running so first:

```<code>def get_all_vm():
    all_vm = get_request("/api2/json/cluster/resources?type=vm")
    vm = all_vm['data']
    list = [item for item in vm if item['status'] == "running"]
    return list
metric = get_all_vm()
</code>```

Now you can loop through all the items and (1) add new values by item["newkey"] = newvalue or (2) loop through existing keys with dict iteration

```<code>for item in metric:
   item["justanexample"] = "test"
   for key,value in item.items():
       if key == "mem":
           ram_metric.set({'name': metric['data']['name'], 'type': 'usage'}, metric['data']['mem'])
       elif key == "cpu":
           cpu_metric.set({'name': metric['data']['name'], 'type': 'load'}, metric['data']['cpu'])
...
</code>```

Body:
I am writing a program that exports monitoring data.

I have python code which sends API requests and gets a response as json in form of a dictionary.

Responses look like this:

[
  {
    "diskwrite": 667719532544,
    "name": "test-hostname",
    "maxmem": 536870912,
    "diskread": 876677015576,
    "mem": 496111616,
    "id": "qemu/102",
    "node": "node1",
    "template": 0,
    "cpu": 0.00947819269772254,
    "vmid": 102,
    "type": "qemu",
    "maxcpu": 2,
    "netout": 15081562546,
    "maxdisk": 10737418240,
    **"status": "running",**
    "netin": 15852619497,
    "disk": 0,
    "uptime": 3273086
  },
  {
    "maxcpu": 8,
    "type": "qemu",
    "vmid": 106,
    "cpu": 0.500598230113925,
    "template": 0,
    "node": "node1",
    "id": "qemu/106",
    "mem": 10341007360,
    "maxmem": 10737418240,
    "diskread": 8586078094720,
    "name": "some.other-hostname",
    "diskwrite": 6052378838016,
    "uptime": 1900411,
    "disk": 0,
    "netin": 4899018841106,
    **"status": "stopping",**
    "maxdisk": 107374182400,
    "netout": 4788420573355
  },
  ...

I'd like to loop through all the hostnames and their items as is ("diskwrite", "mem", "cpu", etc) but I'd like to add these items to a dictionary only if they have a status of running ("status":"running").

ram_metric.set({'type': "total"}, ram[0])
cpu_metric.set({'type': 'average', 'interval': '5 minutes'}, cpu[0])

I also need a loop that will make this line of code and for every "name" item creating this row with host=name:

ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
                       {'host': host})
cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
                       {'host': host})

Please, I don't know how to do that.

Body:
I can try to help.

The response you are getting is a list with dictionaries and you are only interested if the status is running so first:

def get_all_vm():
    all_vm = get_request("/api2/json/cluster/resources?type=vm")
    vm = all_vm['data']
    list = [item for item in vm if item['status'] == "running"]
    return list
metric = get_all_vm()

Now you can loop through all the items and (1) add new values by item["newkey"] = newvalue or (2) loop through existing keys with dict iteration

for item in metric:
   item["justanexample"] = "test"
   for key,value in item.items():
       if key == "mem":
           ram_metric.set({'name': metric['data']['name'], 'type': 'usage'}, metric['data']['mem'])
       elif key == "cpu":
           cpu_metric.set({'name': metric['data']['name'], 'type': 'load'}, metric['data']['cpu'])
...


问:
How do I run Django migrations automatically on Deis when using a buildpack deployments?
The post-compile hook on Deis seems to function differently than on Heroku.

On Heroku I could simply add a bin/post-compile file containing:

```<code>#!/usr/bin/env bash

python manage.py migrate --noinput
</code>```

On Deis this gives me a traceback

```<code>Traceback (most recent call last):
    File "manage.py", line 8, in <module>
        from django.core.management import execute_from_command_line
No module named django.core.management
</code>```

Is anyone running Django on Deis using buildpacks and have a working example of this?

答:
I have eventually found two solutions.

The simple answer is to just provide a full path to python.  I've tested this by adding a bin/post-compile file to deis/example-python-django

```<code>#!/usr/bin/env bash

/app/.heroku/python/bin/python manage.py migrate --noinput
</code>```

This solution however doesn't work if you need access to any of your config variables, which is most likely the case if you are following the 12 Factor app methodology.

Unfortunately deis doesn't run the post-compile hooks in quite the same way Heroku does so we need to export our environment variables first.  Using the sub-env function from the heroku-buildpack-python as a guide I came up with this...

```<code>#!/usr/bin/env bash

echo "-----> Running post-compile hook"

BUILD_DIR=/tmp/build
ENV_DIR=/tmp/environment

BLACKLIST='^(GIT_DIR|STACK|PYTHONHOME|LD_LIBRARY_PATH|LIBRARY_PATH|PATH)$'

# Python-specific variables.
export PYTHONHOME=$BUILD_DIR/.heroku/python
export PYTHONPATH=$BUILD_DIR/

if [ -d "$ENV_DIR" ]; then
  for e in $(ls $ENV_DIR); do
    echo "$e" | grep -E "$WHITELIST" | grep -qvE "$BLACKLIST" &&
    export "$e=$(cat $ENV_DIR/$e)"
    :
  done
fi

$PYTHONHOME/bin/python manage.py migrate --noinput
</code>```

Body:
The post-compile hook on Deis seems to function differently than on Heroku.

On Heroku I could simply add a bin/post-compile file containing:

#!/usr/bin/env bash

python manage.py migrate --noinput

On Deis this gives me a traceback

Traceback (most recent call last):
    File "manage.py", line 8, in <module>
        from django.core.management import execute_from_command_line
No module named django.core.management

Is anyone running Django on Deis using buildpacks and have a working example of this?

Body:
I have eventually found two solutions.

The simple answer is to just provide a full path to python.  I've tested this by adding a bin/post-compile file to deis/example-python-django

#!/usr/bin/env bash

/app/.heroku/python/bin/python manage.py migrate --noinput

This solution however doesn't work if you need access to any of your config variables, which is most likely the case if you are following the 12 Factor app methodology.

Unfortunately deis doesn't run the post-compile hooks in quite the same way Heroku does so we need to export our environment variables first.  Using the sub-env function from the heroku-buildpack-python as a guide I came up with this...

#!/usr/bin/env bash

echo "-----> Running post-compile hook"

BUILD_DIR=/tmp/build
ENV_DIR=/tmp/environment

BLACKLIST='^(GIT_DIR|STACK|PYTHONHOME|LD_LIBRARY_PATH|LIBRARY_PATH|PATH)$'

# Python-specific variables.
export PYTHONHOME=$BUILD_DIR/.heroku/python
export PYTHONPATH=$BUILD_DIR/

if [ -d "$ENV_DIR" ]; then
  for e in $(ls $ENV_DIR); do
    echo "$e" | grep -E "$WHITELIST" | grep -qvE "$BLACKLIST" &&
    export "$e=$(cat $ENV_DIR/$e)"
    :
  done
fi

$PYTHONHOME/bin/python manage.py migrate --noinput


答:
```<code>CREATE TABLE CHARSET
(
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    CONSTRAINT PK_80 PRIMARY KEY (CHARSET_CODE)
) ;
</code>```

Remove ADD in your query and run it. It will work.

Title: Why can't I add a constraint when creating the table?

Body:
CREATE TABLE CHARSET
(
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    CONSTRAINT PK_80 PRIMARY KEY (CHARSET_CODE)
) ;

Remove ADD in your query and run it. It will work.


问:
How to pass a multi dimensional array to a view in CodeIgniter
this is really doing my nut in.
I'm passing a multidimensional array to a view like this:

```<code>$res = $this->deliciouslib->getRecentPosts();
</code>```

(as you can see its the delicious API I'm playing with)

$result is an array and print_r($result) give something like this:

My problem is how to iterate through this in the view! I have been trying stuff like this,

```<code>$result = $this->deliciouslib->getRecentPosts();
$i=0;

foreach($result as $value)
{
     $val = 'val'.$i;
     $data[$val]=$value;
     $i++;
}

$this->load->view('delicious_view',$data);
return true;
</code>```

And then, in the view something like...

```<code>foreach ($val0 as $value)
{
   echo $value."<br>";
}
</code>```

Obviously this doesn't work, as I need all of "$val(i)"!.

Man I got BrainCramp!! I'm probably dancing around the answer, like a basketball round the hoop, but I'm totally stumnped nonetheless. Any Ideas how I can iterated throught the entire array, would be most helpful....

答:
Answer to your problem could be way of calling data from the array.  Possible solutions:

Get the data in an array with index.

```<code>$data['**result**']=$this->deliciouslib->getRecentPosts();
</code>```

Now since the result of getRecentPosts() is an array of data, pass it to view

```<code>$this->load->view('view_name', $data);
</code>```

If the result is an array, on View Page, access it via RIGHT INDEXING

```<code>$result[0-9]['col_name'] e.g **var_dump($result[9]['Title']**);
</code>```

Otherwise if it is an array of objects,

```<code>$result[0-9]=>col_name<br> e.g **var_dump($result[9]=>title)**;
</code>```

Body:
this is really doing my nut in.
I'm passing a multidimensional array to a view like this:

$res = $this->deliciouslib->getRecentPosts();

(as you can see its the delicious API I'm playing with)

$result is an array and print_r($result) give something like this:

My problem is how to iterate through this in the view! I have been trying stuff like this,

$result = $this->deliciouslib->getRecentPosts();
$i=0;

foreach($result as $value)
{
     $val = 'val'.$i;
     $data[$val]=$value;
     $i++;
}

$this->load->view('delicious_view',$data);
return true;

And then, in the view something like...

foreach ($val0 as $value)
{
   echo $value."
";
}

Obviously this doesn't work, as I need all of "$val(i)"!.

Man I got BrainCramp!! I'm probably dancing around the answer, like a basketball round the hoop, but I'm totally stumnped nonetheless. Any Ideas how I can iterated throught the entire array, would be most helpful....

Body:
Answer to your problem could be way of calling data from the array.  Possible solutions:

Get the data in an array with index.

$data['**result**']=$this->deliciouslib->getRecentPosts();

Now since the result of getRecentPosts() is an array of data, pass it to view

$this->load->view('view_name', $data);

If the result is an array, on View Page, access it via RIGHT INDEXING

$result[0-9]['col_name'] e.g **var_dump($result[9]['Title']**);

Otherwise if it is an array of objects,

$result[0-9]=>col_name<br> e.g **var_dump($result[9]=>title)**;


问:
Gulp: Merging files
I have the following project structure:

```<code>my_app
├── gulpfile.js
├── package.json
└── source
    └── locales
        ├ en
        │ ├─ core.json
        │ └─ ui.json
        ├ es
        │ ├─ core.json
        │ └─ ui.json
        ├ fr
        │ ├─ core.json
        │ └─ ui.json
        ├ ...
</code>```

Goal: I want to merge the files in each language directory into one, ie.:

```<code>my_app
    ├── gulpfile.js
    ├── package.json
    └── source
        └── locales
            ├ en
            │ └─ strings.json
            ├ es
            │ └─ strings.json
            ├ fr
            │ └─ strings.json
            ├ ...
</code>```

Here's my current gulp task that instead of doing that, merges ALL files:

```<code>var merge = require('gulp-merge-json');
...
gulp.src([
        'source/locales/**/*.json',
        'source/locales/**/*.json'
      ])
      .pipe(merge({fileName: 'strings.json'}))
      .pipe(gulp.dest('source/locales/'));
</code>```

But that makes the directory structure like this:

```<code>my_app
    ├── gulpfile.js
    ├── package.json
    └── source
        └── locales
            └ strings.json
</code>```

Any suggestions?

答:
You could try by processing each locale folder into its own gulp task:

```<code>var fs    = require('fs'),
    path  = require('path'),
    gulp  = require('gulp'),
    merge = require('gulp-merge-json'),
    comb  = require('merge-stream');

function getLocales(dir) {
  return fs.readdirSync(dir).filter(function(file) {
    return fs.statSync(path.join(dir, file)).isDirectory();
  });
}

gulp.task('default', function() {
  var locales = getLocales('source/locales');
  var tasks = locales.map(function(locale) {
    return gulp.src('source/locales/' + locale + '/*.json')
      .pipe(merge({fileName: 'strings.json'}))
      .pipe(gulp.dest('source/locales/' + locale));
  });

  return comb(tasks);
});
</code>```

Title: Gulp: Merging files

Body:
I have the following project structure:

my_app
├── gulpfile.js
├── package.json
└── source
    └── locales
        ├ en
        │ ├─ core.json
        │ └─ ui.json
        ├ es
        │ ├─ core.json
        │ └─ ui.json
        ├ fr
        │ ├─ core.json
        │ └─ ui.json
        ├ ...

Goal: I want to merge the files in each language directory into one, ie.:

my_app
    ├── gulpfile.js
    ├── package.json
    └── source
        └── locales
            ├ en
            │ └─ strings.json
            ├ es
            │ └─ strings.json
            ├ fr
            │ └─ strings.json
            ├ ...

Here's my current gulp task that instead of doing that, merges ALL files:

var merge = require('gulp-merge-json');
...
gulp.src([
        'source/locales/**/*.json',
        'source/locales/**/*.json'
      ])
      .pipe(merge({fileName: 'strings.json'}))
      .pipe(gulp.dest('source/locales/'));

But that makes the directory structure like this:

my_app
    ├── gulpfile.js
    ├── package.json
    └── source
        └── locales
            └ strings.json

Any suggestions?

Body:
You could try by processing each locale folder into its own gulp task:

var fs    = require('fs'),
    path  = require('path'),
    gulp  = require('gulp'),
    merge = require('gulp-merge-json'),
    comb  = require('merge-stream');

function getLocales(dir) {
  return fs.readdirSync(dir).filter(function(file) {
    return fs.statSync(path.join(dir, file)).isDirectory();
  });
}

gulp.task('default', function() {
  var locales = getLocales('source/locales');
  var tasks = locales.map(function(locale) {
    return gulp.src('source/locales/' + locale + '/*.json')
      .pipe(merge({fileName: 'strings.json'}))
      .pipe(gulp.dest('source/locales/' + locale));
  });

  return comb(tasks);
});


问:
Load image to markers on maps
I have implemented a simple google map where i display a list of markers depending on a list that i have for that.

To display them i iterate over the list and create each marker, like this:

```<code>for (final PhotosForPlants p : photos) {
            if (p.getLat() != null && p.getLon() != null && p.getLat() != 0.0 && p.getLon() != 0.0) // check for 0.0
            {
                if (p.getId() == currentPlantId) {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    yellowPos = plantLocation;
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(plantLocation, 35f));
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

                    m.setTag(p);
                    markers.add(m);
                } else {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    positions.add(plantLocation);
                    positionSave = index;
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                    m.setTag(p);
                    markers.add(m);
                }

            }
            index++;
        }
    }
</code>```

instead of having a simple marker image, i need to have something like a square image loaded from my server, i try to use picasso for it but i don't know if i get any problem doing it this way to get the bitmap:

```<code> public void loadBitmap(String url) {

        if (loadtarget == null) loadtarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // do something with the Bitmap
                handleLoadedBitmap(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }

        };

        Picasso.with(this).load(url).into(loadtarget);
    }

    public Bitmap handleLoadedBitmap(Bitmap b) {
        return b;
    }
</code>```

my main problem is that i don't know how i can retrive each image loaded for the specific marker, and how to set it ip with my maps :S.

Any help?

答:
Answer to the second part of your question: If you have a Bitmap object you can modify your code with

```<code> Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                        .icon(BitmapDescriptorFactory.fromBitmap(myBitmap)));
</code>```

in order to use myBitmap as the marker.

Title: Load image to markers on maps

Body:
I have implemented a simple google map where i display a list of markers depending on a list that i have for that.

To display them i iterate over the list and create each marker, like this:

for (final PhotosForPlants p : photos) {
            if (p.getLat() != null && p.getLon() != null && p.getLat() != 0.0 && p.getLon() != 0.0) // check for 0.0
            {
                if (p.getId() == currentPlantId) {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    yellowPos = plantLocation;
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(plantLocation, 35f));
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

                    m.setTag(p);
                    markers.add(m);
                } else {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    positions.add(plantLocation);
                    positionSave = index;
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                    m.setTag(p);
                    markers.add(m);
                }

            }
            index++;
        }
    }

instead of having a simple marker image, i need to have something like a square image loaded from my server, i try to use picasso for it but i don't know if i get any problem doing it this way to get the bitmap:

 public void loadBitmap(String url) {

        if (loadtarget == null) loadtarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // do something with the Bitmap
                handleLoadedBitmap(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }

        };

        Picasso.with(this).load(url).into(loadtarget);
    }

    public Bitmap handleLoadedBitmap(Bitmap b) {
        return b;
    }

my main problem is that i don't know how i can retrive each image loaded for the specific marker, and how to set it ip with my maps :S.

Any help?

Body:
Answer to the second part of your question: If you have a Bitmap object you can modify your code with

 Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                        .icon(BitmapDescriptorFactory.fromBitmap(myBitmap)));

in order to use myBitmap as the marker.


问:
Regressing over a data frame matrix without intercept using lm
I would like to regress over a data frame matrix using lm without the intercept. If your matrix is stored as a data frame, you can simply call lm(matrix) and the first column is assumed to be the dependent variable while the rest are taken as the independent variables, with the regression including an intercept. My question is: how do I efficiently do the same if I want to regress without including the intercept?

Minimal working example:

```<code>mat <- matrix(c(2, 4, 3, 1, 5, 7, 3, 5, 30), nrow=3, ncol=3)
mat <- data.frame(mat)
lm(mat)
</code>```

outputs a regression with an intercept term

答:
It depends what you mean by "efficent".

If you mean syntactically brief/efficient, then I think the most elegant way is do provide the formula directly as @nicola shows in the comments (lm(X1 ~ . + 0, data = mat)).

If you mean removing the intercept programatically (programatically efficient, I guess), then the below code will do that.

```<code>mat <- matrix(c(2, 4, 3, 1, 5, 7, 3, 5, 30), nrow=3, ncol=3)
mat <- data.frame(mat)

lm(update(as.formula(mat), . ~ . - 1), data = mat)
#
#Call:
#lm(formula = update(as.formula(mat), . ~ . - 1), data = mat)
#
#Coefficients:
#     X2       X3
# 0.9364  -0.1144
</code>```

Note, that when you call lm(mat), lm will try to coerce mat to a formula object (try to run as.formula(mat)) and use that formula. As you can see (and have noted), this automatically selects the first column as the dependent variable and the remaining as explanatory variables. All we need to do then, is updating that formula to not include the intercept using update.

Body:
I would like to regress over a data frame matrix using lm without the intercept. If your matrix is stored as a data frame, you can simply call lm(matrix) and the first column is assumed to be the dependent variable while the rest are taken as the independent variables, with the regression including an intercept. My question is: how do I efficiently do the same if I want to regress without including the intercept?

Minimal working example:

mat <- matrix(c(2, 4, 3, 1, 5, 7, 3, 5, 30), nrow=3, ncol=3)
mat <- data.frame(mat)
lm(mat)

outputs a regression with an intercept term

Body:
It depends what you mean by "efficent".

If you mean syntactically brief/efficient, then I think the most elegant way is do provide the formula directly as @nicola shows in the comments (lm(X1 ~ . + 0, data = mat)).

If you mean removing the intercept programatically (programatically efficient, I guess), then the below code will do that.

mat <- matrix(c(2, 4, 3, 1, 5, 7, 3, 5, 30), nrow=3, ncol=3)
mat <- data.frame(mat)

lm(update(as.formula(mat), . ~ . - 1), data = mat)
#
#Call:
#lm(formula = update(as.formula(mat), . ~ . - 1), data = mat)
#
#Coefficients:
#     X2       X3
# 0.9364  -0.1144

Note, that when you call lm(mat), lm will try to coerce mat to a formula object (try to run as.formula(mat)) and use that formula. As you can see (and have noted), this automatically selects the first column as the dependent variable and the remaining as explanatory variables. All we need to do then, is updating that formula to not include the intercept using update.


问:
Sending bulk email in PHP
I want to send mail to hundreds of email addresses in PHP using php mail function.
How can I do that?</p>

答:
You can use swiftmailer for it. By using batch process.</p>

```<code><?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('myfrom@domain.com' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html')
    ;

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>
</code>```

Title: Sending bulk email in PHP

Body:
You can use swiftmailer for it. By using batch process.

<?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('myfrom@domain.com' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html')
    ;

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>


问:
Sandbox User Login - Invalid Address
Basically I was trying to purchase subscription with developer mode certificates using Sandbox account details. Up to now I have used around 100 times same Sandbox user details and it was worked perfectly.

But from last 2 to 3 days its not get able to success in making purchase. At the end of purchase, I was getting following kind of dialog box then after no success in purchase.

Still application was not live in market so I can't use real apple account for making purchase so I was using sandbox user details for testing purpose.
Subscription as well normal product purchase also not working with same reason.

So what is running wrong in this? Please share some idea regarding this.

答:
For this I found ad hoc solution at present.
I belong to India and up to now I used India country sandbox user account for testing purpose but from last few days its completely stopped working.

So I have created US sandbox user account and within Settings of iPhone, I selected US as country as Apple Store also selected as US user.

Then after I can able to test with sandbox user but still Indian user sandbox account not working so not sure what is going wrong into that but temporary solution I have so adjusted with that.

Title: Sandbox User Login - Invalid Address


问:
how to include or extends a language file in laravel vendor folder
I'm trying to load a language folder inside a laravel's package called permissionmanager ,  I know that including files directly inside vendor folder isn't the recommended way, but  trying to extend it on the resources/views/vendor folder was unsuccessful.
  the problem occurs when i try to upload the folder to the server using filezilla,it's not allowed. because i suppose laravel's vendor folder is protected.

so how can I load that lang file (es/permissionmanager.php) in the right way?

答:
Use the "resources/lang" folder, not "resources/views". So it will be:

resources/lang/vendor/backpack/es/permissionmanager.php