问:
How to draw polyline similar to google map app in android?
The polyline which we will draw on the map is not similar to the polyline of google's map application.It is giving a nice 3d feel,can we draw the polyline similar to that polyline?.Is it possible to draw using 9-patch images?.Anyone please help?.</p>

答:
Hello  this would help you, it helped me.

Firstly make the google api server key from Google developer account then add a dependency for google direction.

```<code>compile 'com.akexorcist:googledirectionlibrary:1.0.4'
</code>```

then it check that feasible and shortest route between LatLongs.

use this code to check route is available or not.

```<code>GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
                    .from(SourceLatlng)
                    .to(DestinationLatlng)
                    .execute(new DirectionCallback() {
                        @Override
                        public void onDirectionSuccess(Direction direction, String message) {
                            if (direction.isOK()) {
                                DrawRoute(direction, message,SourceLatlng,DestinationLatlng);
                            } else {
                                //selectedRawLine = ERROR;
                            }

                        }

                        @Override
                        public void onDirectionFailure(Throwable t) {
                            t.printStackTrace();
                        }
                    });
</code>```

Using this we can find that route is feasible or not

```<code>private void DrawRoute(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {

        for (Route route : direction.getRouteList()) {
            PolylineOptions polyoptions = new PolylineOptions();
            polyoptions.color(getResources().getColor(R.color.blackcolor));
            polyoptions.width(5);
            polyoptions.addAll(route.getOverviewPolyline().getPointList());
            poly = googleMap.addPolyline(polyoptions);
            poly.setClickable(true);

        }
        LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
        if(sourceLatlng!=null)
        latLngBuilder.include(sourceLatlng);
        if(DestinationLng!=null)
        latLngBuilder.include(DestinationLng);

        try {
            LatLngBounds bounds = latLngBuilder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                    UiHelper.dpToPixel(getActivity(), 135));
            googleMap.animateCamera(cu);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
</code>```

Using this code we make polyline between two latLongs ...

Body:
Hello  this would help you, it helped me.

Firstly make the google api server key from Google developer account then add a dependency for google direction.

compile 'com.akexorcist:googledirectionlibrary:1.0.4'

then it check that feasible and shortest route between LatLongs.

use this code to check route is available or not.

GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
                    .from(SourceLatlng)
                    .to(DestinationLatlng)
                    .execute(new DirectionCallback() {
                        @Override
                        public void onDirectionSuccess(Direction direction, String message) {
                            if (direction.isOK()) {
                                DrawRoute(direction, message,SourceLatlng,DestinationLatlng);
                            } else {
                                //selectedRawLine = ERROR;
                            }

                        }

                        @Override
                        public void onDirectionFailure(Throwable t) {
                            t.printStackTrace();
                        }
                    });

Using this we can find that route is feasible or not

private void DrawRoute(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {

        for (Route route : direction.getRouteList()) {
            PolylineOptions polyoptions = new PolylineOptions();
            polyoptions.color(getResources().getColor(R.color.blackcolor));
            polyoptions.width(5);
            polyoptions.addAll(route.getOverviewPolyline().getPointList());
            poly = googleMap.addPolyline(polyoptions);
            poly.setClickable(true);

        }
        LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
        if(sourceLatlng!=null)
        latLngBuilder.include(sourceLatlng);
        if(DestinationLng!=null)
        latLngBuilder.include(DestinationLng);

        try {
            LatLngBounds bounds = latLngBuilder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                    UiHelper.dpToPixel(getActivity(), 135));
            googleMap.animateCamera(cu);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Using this code we make polyline between two latLongs ...


来源: stackexchange

问:
C# Override method from Collection<T>
I would like to notify to the user each time that the program add a new Item in a List.

I did this:

```<code>public class ListDemo<T> : Collection<T>
{
    protected override void InsertItem(int index, T item)
    {
        Console.WriteLine("YOU HAVE INSERTED AN ITEM");
        base.InsertItem(index, item);
    }
}
</code>```

I could inherit ListDemo from the interface IList, but I don't want to implement all the methods of this interface... So I inherited from Collection

Now I have two questions about my code:

1º  Do I have to notify to the user with an event? Or my code is good?

2º  How Can I call to the override method? Like an Interface?

```<code>         // IT WORKS!
         List<int> _list = new ListDemo<int>();
        _list.Insert(0,2);
        Console.WriteLine(_list[0]);
</code>```

This code works, and it is very strange for me, because when you call to an interface you must use this way:

```<code>        Collection<int> _list = new ListDemo<int>();
</code>```

3º Why if the override method is InsertItem, then when I call to the method from my instance this is simply Insert.

答: If you implementation does what you want, there is no problem. That being said, there is already a predefined type ObservableCollection<T>, which is documented here, which does exactly what you want, namely providing a mechanism for notifications if the content of the collections changes.

ContentLicense: CC BY-SA 3.0

Title: C# Override method from Collection<T>

Body:
I would like to notify to the user each time that the program add a new Item in a List.

I did this:

public class ListDemo<T> : Collection<T>
{
    protected override void InsertItem(int index, T item)
    {
        Console.WriteLine("YOU HAVE INSERTED AN ITEM");
        base.InsertItem(index, item);
    }
}

I could inherit ListDemo from the interface IList, but I don't want to implement all the methods of this interface... So I inherited from Collection

Now I have two questions about my code:

1º  Do I have to notify to the user with an event? Or my code is good?

2º  How Can I call to the override method? Like an Interface?

         // IT WORKS!
         List<int> _list = new ListDemo<int>();
        _list.Insert(0,2);
        Console.WriteLine(_list[0]);

This code works, and it is very strange for me, because when you call to an interface you must use this way:

        Collection<int> _list = new ListDemo<int>();

3º Why if the override method is InsertItem, then when I call to the method from my instance this is simply Insert.


问:
Is it possible to maintain a parameter table in loadrunner?
Lets assume I've defined a key/value pair in loadrunner parameters
section called mytable.dat (Parameter type: Table)

Does loadrunner have a built in function to update this table?
Can I access a value according to key?

In other words, lets say this table consists of user name which will be the key
and email address as value - I would like to ask get the address of a certain user and update his email so when I run the test again tomorrow, loadrunner will load an updated version of mytable.dat

I would like to avoid programming it in c, if there is no built in way to do it in loadrunner than I would much prefer to handle it using javascript.

答:
In LoadRunner there are 3 types of parameters:

1) Static - The parameters you define using the parameters dialog in VuGen (e.g. the Table type parameter you are talking about). These parameters are read only and can be accessed using the curly brackets notation:

```<code>lr_message(lr_eval_string("{NewParam}"));
</code>```

2) Dynamic - Parameters you define using the code within your script and can be read and written in code (and accessed via curly brackets):

```<code>lr_save_string("aaaa","bbb");
lr_message(lr_eval_string("{bbb}"));
</code>```

3) VTS - This is basically a small database which you can access from any vUser running the script and you have full control over what is going on there with appropriate API (please read the documentation on VTS)

Some other notes:
"Table" parameter is a way to access multiple values with one parameter, make sure this is the parameter type you really need.

Some protocols support JavaScript as the scripting language. To switch the language to JavaScript go to Record -> Recording Options, in the dialog General -> Script and change the language to JavaScript. Then regenerate the script (or record an empty script) and it will be regenerated in JavaScript

Body:
In LoadRunner there are 3 types of parameters:

1) Static - The parameters you define using the parameters dialog in VuGen (e.g. the Table type parameter you are talking about). These parameters are read only and can be accessed using the curly brackets notation:

lr_message(lr_eval_string("{NewParam}"));

2) Dynamic - Parameters you define using the code within your script and can be read and written in code (and accessed via curly brackets):

lr_save_string("aaaa","bbb");
lr_message(lr_eval_string("{bbb}"));

3) VTS - This is basically a small database which you can access from any vUser running the script and you have full control over what is going on there with appropriate API (please read the documentation on VTS)

Some other notes:
"Table" parameter is a way to access multiple values with one parameter, make sure this is the parameter type you really need.

Some protocols support JavaScript as the scripting language. To switch the language to JavaScript go to Record -> Recording Options, in the dialog General -> Script and change the language to JavaScript. Then regenerate the script (or record an empty script) and it will be regenerated in JavaScript


问:
Remove \x in string in python

I need get little endian random string via python.

Such as '0010' as 256 (without '\x')

Here is my code.

```<code> import random
 import struct
 str1 = struct.pack('<Q', random.randint(1, 1000))
 #Ex: str1 = '\xc9\x02\x00\x00\x00\x00\x00\x00'
</code>```

But I don't have any idea to convert this string to "C902000000000000"
Please give any advise, thanks

答:
you can remove the "\x" from "\x0034" simply using this code
if the ax variable contains the string

```<code>ax = ax.replace("\x00" , "")
</code>```

then the \x00 will removed from the string

Title: Remove \x in string in python

Body:
I need get little endian random string via python.

Such as '0010' as 256 (without '\x')

Here is my code.

 import random
 import struct
 str1 = struct.pack('<Q', random.randint(1, 1000))
 #Ex: str1 = '\xc9\x02\x00\x00\x00\x00\x00\x00'

But I don't have any idea to convert this string to "C902000000000000"
Please give any advise, thanks

Body:
you can remove the "\x" from "\x0034" simply using this code
if the ax variable contains the string

ax = ax.replace("\x00" , "")

then the \x00 will removed from the string


问:
Phonegap Build cordova-plugin-facebook4 plugin not working on iOS
I am creating a phonegap build app which contains a facebook login.
Below are some details.
- The app has a Login with facebook button

It uses cordova-plugin-facebook4 plugin (https://www.npmjs.com/package/cordova-plugin-facebook4)

The integration code is below:

```<code>facebookConnectPlugin.login( ["public_profile"],
    function ( userData ) {
        alert( "login" );
        //fetch user info using graph api
        facebookConnectPlugin.api( "me/?fields=id,name,email,gender", ["email", "public_profile"],
            function ( result ) {
                alert( "login success" );
                //store access token in local storage
                facebookConnectPlugin.getAccessToken( function ( token ) {
                    console.log( "Token: " + token );
                } );
            },
            function ( error ) {
                alert( "Failed: " + error );
            } );
    }, function ( error ) { alert( "error" ); }
);
</code>```

The above code works fine for on the android app.

- The above code does not work in iOS  app

Device used for testing: IPad mini iOS version 10.x.

On developer.facebook.com, the app settings for iOS platform are as follows:

Bundle ID: same value as widget id in config.xml for phonegap

iPhone store id: empty

url scheme suffix: empty

ipad store id: empty

Single Sign On toggle: YES

Below is the current behavior for iOS iPad:
1. User clicks on Login using Facebook in the iOS app
2. User is taken to facebook permissions page in safari browser
3. User enters user id and password
4. User is asked for permission and User clicks "Confirm"
5. Safari shows a popup asking "Open in App?"
6. User clicks Open
7. User is taken to the same app and the same page and displayed the same login link.

Note that the control is not passed back to continue the script at all, its almost that the app was relaunched from start.

Safari web inspector does not show any errors.

GapDebug on mac (i am using a virtualbox Yosemite mac version) does not show any errors.

Please help as I am not very sure at this point, what else I am missing.

答:
I know its late to answer for this question but it might help other to fix this issue. So here is the solution

```<code><meta http-equiv="Content-Security-Policy" content="default-src * gap://ready; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src * 'unsafe-inline' 'unsafe-eval'">
</code>```

add this in index.html. gap://ready is required for iOS 10

ContentLicense: CC BY-SA 4.0

Body:
I am creating a phonegap build app which contains a facebook login.
Below are some details.
- The app has a Login with facebook button

It uses cordova-plugin-facebook4 plugin (https://www.npmjs.com/package/cordova-plugin-facebook4)

The integration code is below:

facebookConnectPlugin.login( ["public_profile"],
    function ( userData ) {
        alert( "login" );
        //fetch user info using graph api
        facebookConnectPlugin.api( "me/?fields=id,name,email,gender", ["email", "public_profile"],
            function ( result ) {
                alert( "login success" );
                //store access token in local storage
                facebookConnectPlugin.getAccessToken( function ( token ) {
                    console.log( "Token: " + token );
                } );
            },
            function ( error ) {
                alert( "Failed: " + error );
            } );
    }, function ( error ) { alert( "error" ); }
);

The above code works fine for on the android app.

- The above code does not work in iOS  app

Device used for testing: IPad mini iOS version 10.x.

On developer.facebook.com, the app settings for iOS platform are as follows:

Bundle ID: same value as widget id in config.xml for phonegap

iPhone store id: empty

url scheme suffix: empty

ipad store id: empty

Single Sign On toggle: YES

Below is the current behavior for iOS iPad:
1. User clicks on Login using Facebook in the iOS app
2. User is taken to facebook permissions page in safari browser
3. User enters user id and password
4. User is asked for permission and User clicks "Confirm"
5. Safari shows a popup asking "Open in App?"
6. User clicks Open
7. User is taken to the same app and the same page and displayed the same login link.

Note that the control is not passed back to continue the script at all, its almost that the app was relaunched from start.

Safari web inspector does not show any errors.

GapDebug on mac (i am using a virtualbox Yosemite mac version) does not show any errors.

Please help as I am not very sure at this point, what else I am missing.

Body:
I know its late to answer for this question but it might help other to fix this issue. So here is the solution

<meta http-equiv="Content-Security-Policy" content="default-src * gap://ready; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src * 'unsafe-inline' 'unsafe-eval'">

add this in index.html. gap://ready is required for iOS 10


问:
How to return a flattened list from multiprocessing in Python?
I have a following piece of code.

My worker returns a list and I want a master list which is union of all the list.

```<code>from multiprocessing import Pool, Manager
manager = Manager()
another_shared_list = manager.list()

def worker2(number):
    return [x for x in xrange(number)]

numbers = [5,7,2,4]
pool1 = Pool(4)
another_shared_list.extend(pool1.map(worker2, numbers))
print another_shared_list
</code>```

It prints

```<code>[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]
</code>```

As you might have probably guessed I want another_shared_list to be

```<code>[0,1,2,3,4,0,1,2,3,4,5,6,0,1,0,1,2,3]
</code>```

How should I approach it?

edit:
I know it seems like a flattening the list question not for multiprocessing. But my preference would be to avoid itertools. I want something such that another_shared_list directly gets the flattened list from the call pool1.map or something else!!

答:
Use itertools.chain:

```<code>itertools.chain(*another_shared_list)
</code>```

Working example:

```<code>another_shared_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]
import itertools
list(itertools.chain(*another_shared_list))
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 0, 1, 0, 1, 2, 3]
</code>```

Notice that chain returns an iterator and you have to consume it to a list if you need it.

Or as commented below:

```<code>itertools.chain.from_iterable(another_shared_list) #to avoid unpacking
</code>```

Body:
I have a following piece of code.

My worker returns a list and I want a master list which is union of all the list.

from multiprocessing import Pool, Manager
manager = Manager()
another_shared_list = manager.list()

def worker2(number):
    return [x for x in xrange(number)]

numbers = [5,7,2,4]
pool1 = Pool(4)
another_shared_list.extend(pool1.map(worker2, numbers))
print another_shared_list

It prints

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]

As you might have probably guessed I want another_shared_list to be

[0,1,2,3,4,0,1,2,3,4,5,6,0,1,0,1,2,3]

How should I approach it?

edit:
I know it seems like a flattening the list question not for multiprocessing. But my preference would be to avoid itertools. I want something such that another_shared_list directly gets the flattened list from the call pool1.map or something else!!

Body:
Use itertools.chain:

itertools.chain(*another_shared_list)

Working example:

another_shared_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]
import itertools
list(itertools.chain(*another_shared_list))
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 0, 1, 0, 1, 2, 3]

Notice that chain returns an iterator and you have to consume it to a list if you need it.

Or as commented below:

itertools.chain.from_iterable(another_shared_list) #to avoid unpacking


问:
How to handle input parameters while generating dynamic html from jquery function
I am using below function to generate dynamic HTML.

```<code>function (content) {
    $('#divMessage').append('<span>'+ content+ '</span>');
}
</code>```

Here I am appending content in div with id divMessage.

Here input parameter content can be any text passed to this function.

I am facing problem when I pass data containing html elements as it distorts html. I am not aable to paste it here as its get dostorted here in stack overflow editor as well.

How can I resolve this issue, TIA.

It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput.

答:
You can pass html value like this.

function AddContent(content) {
    $('#divMessage').append(''+ content+ '');
}
$("#divAppendMessage").on("click", function() {
    //$('#divMessage').html(''); // If you want to clear div before append
   var html='';
   html+='
My new message
';// You can add mark up like this.Be sure for closing tag.
   AddContent('
My new message
');// Pass html without generate markup as OP say on comment.
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='divMessage'>
</div>
<button id='divAppendMessage'>Add Message</button></code>```

May be
this fiddle solve your problem. Before get input from user convert it and reset it when bind.

Body:
I am using below function to generate dynamic HTML.

function (content) {
    $('#divMessage').append(''+ content+ '');
}

Here I am appending content in div with id divMessage.

Here input parameter content can be any text passed to this function.

I am facing problem when I pass data containing html elements as it distorts html. I am not aable to paste it here as its get dostorted here in stack overflow editor as well.

How can I resolve this issue, TIA.

It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput.

Body:
You can pass html value like this.

function AddContent(content) {
    $('#divMessage').append('<span>'+ content+ '</span>');
}
$("#divAppendMessage").on("click", function() {
    //$('#divMessage').html(''); // If you want to clear div before append
   var html='';
   html+='<h1>My new message</h1>';// You can add mark up like this.Be sure for closing tag.
   AddContent('<h1>My new message</h1>');// Pass html without generate markup as OP say on comment.
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='divMessage'>
</div>
<button id='divAppendMessage'>Add Message</button>

May be
this fiddle solve your problem. Before get input from user convert it and reset it when bind.


问:
Group and count values in an array
I have an array with objects, like the following.

```<code>b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};
</code>```

I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.

```<code>a = [
  {Name: 'Backlog', count: 1},
  {Name: 'close', count: 2}
];
</code>```

I have tried the following.

```<code>b.issues.forEach(function(i) {
  var statusName = i.fields.status.name;

  if (statusName in a.Name) {
    a.count = +1;
  } else {
    a.push({
      Name: statusName,
      count: 1
    });
  }
});
</code>```

That however doesn't seem to be working. How should I implement this?

答:
This is a perfect opportunity to use Array#reduce. That function will take a function that is applied to all elements of the array in order and can be used to accumulate a value. We can use it to accumulate an object with the various counts in it.

To make things easy, we track the counts in an object as simply {name: count, otherName: otherCount}. For every element, we check if we already have an entry for name. If not, create one with count 0. Otherwise, increment the count. After the reduce, we can map the array of keys, stored as keys of the object, to be in the format described in the question. See below.

var b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};

var counts = b.issues.reduce((p, c) => {
  var name = c.fields.status.name;
  if (!p.hasOwnProperty(name)) {
    p[name] = 0;
  }
  p[name]++;
  return p;
}, {});

console.log(counts);

var countsExtended = Object.keys(counts).map(k => {
  return {name: k, count: counts[k]}; });

console.log(countsExtended);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

Notes.

Array#reduce does not modify the original array.

You can easily modify the function passed to reduce to for example not distinguish between Backlog and backlog by changing

```<code>var name = c.fields.status.name;
</code>```

into

```<code>var name = c.fields.status.name.toLowerCase();
</code>```

for example. More advanced functionality can also easily be implemented.

Title: Group and count values in an array

Body:
I have an array with objects, like the following.

b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};

I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.

a = [
  {Name: 'Backlog', count: 1},
  {Name: 'close', count: 2}
];

I have tried the following.

b.issues.forEach(function(i) {
  var statusName = i.fields.status.name;

  if (statusName in a.Name) {
    a.count = +1;
  } else {
    a.push({
      Name: statusName,
      count: 1
    });
  }
});

That however doesn't seem to be working. How should I implement this?

Body:
This is a perfect opportunity to use Array#reduce. That function will take a function that is applied to all elements of the array in order and can be used to accumulate a value. We can use it to accumulate an object with the various counts in it.

To make things easy, we track the counts in an object as simply {name: count, otherName: otherCount}. For every element, we check if we already have an entry for name. If not, create one with count 0. Otherwise, increment the count. After the reduce, we can map the array of keys, stored as keys of the object, to be in the format described in the question. See below.

var b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};

var counts = b.issues.reduce((p, c) => {
  var name = c.fields.status.name;
  if (!p.hasOwnProperty(name)) {
    p[name] = 0;
  }
  p[name]++;
  return p;
}, {});

console.log(counts);

var countsExtended = Object.keys(counts).map(k => {
  return {name: k, count: counts[k]}; });

console.log(countsExtended);

.as-console-wrapper {
  max-height: 100% !important;
}

Notes.

Array#reduce does not modify the original array.

You can easily modify the function passed to reduce to for example not distinguish between Backlog and backlog by changing

var name = c.fields.status.name;

into

var name = c.fields.status.name.toLowerCase();

for example. More advanced functionality can also easily be implemented.


问:
Spring security and @PostFilter
I have this object:

@Service
public class myBr {

    @PostFilter("filterObject.cellule.getId()==2")
    public List<Bibliotheque> getB() {
        return super.getAll();
    }

    public List<Bibliotheque> getA() {
        return getB();
    }
}
```

When I call from a test that does myBr.getB(), the @PostFilter is applied, but when I call myBr.getA(), the postfilter is not working.

Is there a way to handle this so that the filter is applied?

答:
I assume that you have already solved your problem, but in case anyone is wondering about similar stuff with his bean calls (i had the same problem with EJBs):
Method annotations are read by the container/the application context or whatever it is that handles the injection. And when, like in this case, some kind of interceptor is needed to trigger the expected behaviour, it works only for calls from 'outside' of a bean, that is, the proxy object wrapped around your bean.
What getA() does in this case is a local call, so technically your thread jumps directly to method getB(), but it doesn't regard any annotations at all.</p>

Title: Spring security and @PostFilter

Body:
I have this object:

@Service
public class myBr {

    @PostFilter("filterObject.cellule.getId()==2")
    public List<Bibliotheque> getB() {
        return super.getAll();
    }

    public List<Bibliotheque> getA() {
        return getB();
    }
}

When I call from a test that does myBr.getB(), the @PostFilter is applied, but when I call myBr.getA(), the postfilter is not working.

Is there a way to handle this so that the filter is applied?

ContentLicense: CC BY-SA 2.5


答:
The InsertItem is a virtual method of Collection<T>:

```<code>protected virtual void InsertItem(
    int index,
    T item
)
</code>```

Please have a look here. So when a type inherits a Collection<T> then it can override this method and when InsertItem is called the overriden one it would be called.

On the other hand List<T> doesn't not inherits Collection<T> so there isn't any method called InsertItem.

That being said, defining you object as below:

```<code>var listDemo = new ListDemo<int>();
listDemo.InsertItem(0,2);
</code>```

you would achieve that you want, because now the type of listDemo inherits from Collection<int> and you have overriden this method.

Title: C# Override method from Collection<T>

Body:
The InsertItem is a virtual method of Collection<T>:

protected virtual void InsertItem(
    int index,
    T item
)

Please have a look here. So when a type inherits a Collection<T> then it can override this method and when InsertItem is called the overriden one it would be called.

On the other hand List<T> doesn't not inherits Collection<T> so there isn't any method called InsertItem.

That being said, defining you object as below:

var listDemo = new ListDemo<int>();
listDemo.InsertItem(0,2);

you would achieve that you want, because now the type of listDemo inherits from Collection<int> and you have overriden this method.


问:
Android Realm for-loop - RealmResults are removed during looping
I have some code running in an IntentService, doing image uploads.  It starts by fetching posts that are "queued" for upload, then it loops through those and makes synchronous Retrofit calls to upload images.  Fairly straight-forward.  See code for reference:

```<code>final RealmResults<Post> posts = realm.where(Post.class)
            .equalTo("uniqueCode", uniqueCode)
            .equalTo("queued", true)
            .isEmpty("url")
            .findAll();

Log.d(TAG, "post count: " + posts.size());

if (posts != null && posts.size() > 0) {
    for (int i = 0; i < posts.size(); i++) {
        Log.d(TAG, "posts count now: " + posts.size());

        Post post = posts.get(i);

        Post submittedPost = api.uploadPhoto(<params>); // Retrofit call, which works fine

        if (submittedPost != null) {
            realm.beginTransaction();
            post.setQueued(false);
            post.setUrl(submittedPost.getUrl());
            realm.commitTransaction();

            sendBroadcastUpdate(); // This updates the UI in places
        }
    }
}
</code>```

Oddly enough, each time it goes through the for-loop, the size of the results ("posts" in my case above) goes down by one - this is confirmed by my Log output that decrements by one each time, so it only gets through a few of the results.  It's almost as if each time I'm committing the Realm transaction during the looping, it's updating my fetched query results, even though that array is set to be final.

I confirmed that it doesn't do this if I don't set those values ('queued' and 'url').  Which tells me it's updating the results somehow.  I've tried different things, such as a while-loop (i.e. "while (posts.size() > 0)"), but it gets through 2-3 of them, and then all of a sudden the size of "posts" is immediately 0, for no reason at all that I can see.

I've also tried doing the begin/commit before and after the loop, but it yields similar results.  Same goes for if I convert it to an array before processing.  It seems that it always gets through a few of them, and then the size is automatically set to 0, so it exits the loop.

This strikes me as very bizarre, especially since I set the results to be "final" - is this expected behavior?  Does anyone know a way around this, by chance?

For reference, we are using Realm version: 0.86.

答:
In Realm versions where version < 0.89.0 or version >= 3.0.0*, this is expected behavior (see here).

RealmResults is a view to the latest version of the database (for a given object type where given conditions are met), and a transaction is essentially "creating the latest version of the database" meaning the RealmResults starts to see the new modified data with each modification.

See following:

```<code>final RealmResults<Post> posts = realm.where(Post.class)
        .equalTo("uniqueCode", uniqueCode)
        .equalTo("queued", true) // <---- condition true
        .isEmpty("url")
        .findAll();

...

    if (submittedPost != null) {
        realm.beginTransaction();
        post.setQueued(false); // <---- condition false
        post.setUrl(submittedPost.getUrl());
        realm.commitTransaction();

        sendBroadcastUpdate(); // This updates the UI in places
    }
</code>```

As you create a transaction, you start to see the latest version, in which case the RealmResults will no longer contain elements that have queued == false.

For Realm 0.88.3 or older, you need to iterate the RealmResults in reverse, or "iterate while the results isn't empty" (I used this method a lot before the 0.89.0 breaking change killed it, but it'd work with 3.0.0+ again so that's nice)

```<code>realm.refresh(); // enforce the next RealmResults to be *definitely* up-to-date

final RealmResults<Post> posts = realm.where(Post.class)
            .equalTo("uniqueCode", uniqueCode)
            .equalTo("queued", true)
            .isEmpty("url")
            .findAll();

while(!posts.isEmpty()) {
    Post post = posts.get(0);
    Post submittedPost = api.uploadPhoto(<params>); // Retrofit call, which works fine
    if (submittedPost != null) {
        realm.beginTransaction();
        post.setQueued(false);
        post.setUrl(submittedPost.getUrl());
        realm.commitTransaction();
        sendBroadcastUpdate(); // This updates the UI in places
    }
}
</code>```

For Realm 3.0.0+, you can either use for(Post post : results) { (iterators), or you can use a collection snapshot directly.

```<code>final RealmResults<Post> results = realm.where(Post.class)
    .equalTo("uniqueCode", uniqueCode)
    .equalTo("queued", true) //
    .isEmpty("url")
    .findAll();
final OrderedRealmCollection<Post> posts = results.createSnapshot(); // <-- snapshot

for (int i = 0; i < posts.size(); i++) {
   //...
</code>```

*(and honestly, the behavior in-between was a hack, where the RealmResults was not synchronized to see the latest version, and 3.0.0 had to undo this hack)

Body:
I have some code running in an IntentService, doing image uploads.  It starts by fetching posts that are "queued" for upload, then it loops through those and makes synchronous Retrofit calls to upload images.  Fairly straight-forward.  See code for reference:

final RealmResults<Post> posts = realm.where(Post.class)
            .equalTo("uniqueCode", uniqueCode)
            .equalTo("queued", true)
            .isEmpty("url")
            .findAll();

Log.d(TAG, "post count: " + posts.size());

if (posts != null && posts.size() > 0) {
    for (int i = 0; i < posts.size(); i++) {
        Log.d(TAG, "posts count now: " + posts.size());

        Post post = posts.get(i);

        Post submittedPost = api.uploadPhoto(<params>); // Retrofit call, which works fine

        if (submittedPost != null) {
            realm.beginTransaction();
            post.setQueued(false);
            post.setUrl(submittedPost.getUrl());
            realm.commitTransaction();

            sendBroadcastUpdate(); // This updates the UI in places
        }
    }
}

Oddly enough, each time it goes through the for-loop, the size of the results ("posts" in my case above) goes down by one - this is confirmed by my Log output that decrements by one each time, so it only gets through a few of the results.  It's almost as if each time I'm committing the Realm transaction during the looping, it's updating my fetched query results, even though that array is set to be final.

I confirmed that it doesn't do this if I don't set those values ('queued' and 'url').  Which tells me it's updating the results somehow.  I've tried different things, such as a while-loop (i.e. "while (posts.size() > 0)"), but it gets through 2-3 of them, and then all of a sudden the size of "posts" is immediately 0, for no reason at all that I can see.

I've also tried doing the begin/commit before and after the loop, but it yields similar results.  Same goes for if I convert it to an array before processing.  It seems that it always gets through a few of them, and then the size is automatically set to 0, so it exits the loop.

This strikes me as very bizarre, especially since I set the results to be "final" - is this expected behavior?  Does anyone know a way around this, by chance?

For reference, we are using Realm version: 0.86.

Body:
In Realm versions where version < 0.89.0 or version >= 3.0.0*, this is expected behavior (see here).

RealmResults is a view to the latest version of the database (for a given object type where given conditions are met), and a transaction is essentially "creating the latest version of the database" meaning the RealmResults starts to see the new modified data with each modification.

See following:

final RealmResults<Post> posts = realm.where(Post.class)
        .equalTo("uniqueCode", uniqueCode)
        .equalTo("queued", true) // <---- condition true
        .isEmpty("url")
        .findAll();

...

    if (submittedPost != null) {
        realm.beginTransaction();
        post.setQueued(false); // <---- condition false
        post.setUrl(submittedPost.getUrl());
        realm.commitTransaction();

        sendBroadcastUpdate(); // This updates the UI in places
    }

As you create a transaction, you start to see the latest version, in which case the RealmResults will no longer contain elements that have queued == false.

For Realm 0.88.3 or older, you need to iterate the RealmResults in reverse, or "iterate while the results isn't empty" (I used this method a lot before the 0.89.0 breaking change killed it, but it'd work with 3.0.0+ again so that's nice)

realm.refresh(); // enforce the next RealmResults to be *definitely* up-to-date

final RealmResults<Post> posts = realm.where(Post.class)
            .equalTo("uniqueCode", uniqueCode)
            .equalTo("queued", true)
            .isEmpty("url")
            .findAll();

while(!posts.isEmpty()) {
    Post post = posts.get(0);
    Post submittedPost = api.uploadPhoto(<params>); // Retrofit call, which works fine
    if (submittedPost != null) {
        realm.beginTransaction();
        post.setQueued(false);
        post.setUrl(submittedPost.getUrl());
        realm.commitTransaction();
        sendBroadcastUpdate(); // This updates the UI in places
    }
}

For Realm 3.0.0+, you can either use for(Post post : results) { (iterators), or you can use a collection snapshot directly.

final RealmResults<Post> results = realm.where(Post.class)
    .equalTo("uniqueCode", uniqueCode)
    .equalTo("queued", true) //
    .isEmpty("url")
    .findAll();
final OrderedRealmCollection<Post> posts = results.createSnapshot(); // <-- snapshot

for (int i = 0; i < posts.size(); i++) {
   //...

*(and honestly, the behavior in-between was a hack, where the RealmResults was not synchronized to see the latest version, and 3.0.0 had to undo this hack)


问:
Three20 TTThumbsViewController
I need to show some images in my app. So, I decided to use three20 and especially the TTThumbsViewController. i have tried to put it in my tabbar application, but it doesn't work.

What I have to do?? Is there another way to make an image gallery??

Link to the project

P.S. Sorry for my English, i can't write but i understand very well.

Thanks

答:
follow below link :

http://www.raywenderlich.com/1430/how-to-use-the-three20-photo-viewer

Title: Three20 TTThumbsViewController


问:
How to disable the emoji keyboard in iOS 7?
I wanted to disable the emoji keyboard programmatically. please let me know how can i do that ?

I tried using following code,

```<code>NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/private/var/mobile/Library/Preferences/com.apple.Preferences.plist"];
[dict setObject:[NSNumber numberWithBool:NO] forKey:@"KeyboardEmojiEverywhere"];
</code>```

But no luck ... :(

答:
Though The Question is super old,
I was Facing the same problem and was able to resolve it by the time this page loaded by this small trick :

Simply Select Numbers and Punctuations in Interface Builder Xcode 8.2.1

Output is No Emoji Keyboard =D

I'm sure it'll help Someone =)

Body:
I wanted to disable the emoji keyboard programmatically. please let me know how can i do that ?

I tried using following code,

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/private/var/mobile/Library/Preferences/com.apple.Preferences.plist"];
[dict setObject:[NSNumber numberWithBool:NO] forKey:@"KeyboardEmojiEverywhere"];

But no luck ... :(


问:
PermissionError with pip3
This is the error when I try to get anything with pip3
I'm not sure what to do</p>

```<code>Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 1435, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 671, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 901, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python3.4/os.py", line 237, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist-                        packages/Django-1.7.2.dist-info'

Storing debug log for failure in /home/omega/.pip/pip.log
</code>```

答:
just install them using --user option which install the package only for the current user and not for all</p>

```<code>pip install xxxxxx --user
</code>```

Title: PermissionError with pip3

Body:
This is the error when I try to get anything with pip3
I'm not sure what to do

Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 1435, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 671, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 901, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python3.4/os.py", line 237, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist-                        packages/Django-1.7.2.dist-info'

Storing debug log for failure in /home/omega/.pip/pip.log

Body:
just install them using --user option which install the package only for the current user and not for all

pip install xxxxxx --user


问:
How can we invert hex-color code?
My Web API will send the background color for my views, Background color range is from white #ffffff to black #000000. So I can not set any fix text color for my information text.
What is the best way to set my text color?
I'm thinking to invert the background color and set it as my text color. But I don't know How can I invert Any color or Hex color code.

e.g if my web(background) color is #00ff11 then my text color will be #ff00ee.

For this, I search over stack but did not find any method for color conversion.

Thanks

答:
Try this.

This will give rgb of your hex color. Now you can invert your colors as below.

```<code>int invertColor(String myColorString) {

    int color = (int)Long.parseLong(myColorString, 16);
    int r = (color >> 16) & 0xFF;
    int g = (color >> 8) & 0xFF;
    int b = (color >> 0) & 0xFF;
    int invertedRed = 255 - r;
    int invertedGreen = 255 - g;
    int invertedBlue = 255 - b;

    int invertedColor = Color.rgb(invertedRed, invertedGreen, invertedBlue);

    return invertedColor.toString();
}
</code>```

Title: How can we invert hex-color code?

Body:
Try this.

This will give rgb of your hex color. Now you can invert your colors as below.

int invertColor(String myColorString) {

    int color = (int)Long.parseLong(myColorString, 16);
    int r = (color >> 16) & 0xFF;
    int g = (color >> 8) & 0xFF;
    int b = (color >> 0) & 0xFF;
    int invertedRed = 255 - r;
    int invertedGreen = 255 - g;
    int invertedBlue = 255 - b;

    int invertedColor = Color.rgb(invertedRed, invertedGreen, invertedBlue);

    return invertedColor.toString();
}


问:
JDBC connection URL with PHP
I have the jdbc connection string url i used in java

```<code>jdbc:sqlserver://DB-1\LDAP;databaseName=LDAPINFO
</code>```

with username and password.

how to connect it in PHP? seem like i cant use JDBC in PHP?

答:
As defined here(emphasized by me):

ODBC is an open interface which can be used by any application to communicate with any database system, while JDBC is an interface that can be used by Java applications to access databases. Therefore, unlike JDBC, ODBC is language independent.

So I don't think it is possible to use JDBC for PHP, you can use PDO or MySQLi instead to connect to database.

You can also check here for more reference.

Title: JDBC connection URL with PHP

Body:
I have the jdbc connection string url i used in java

jdbc:sqlserver://DB-1\LDAP;databaseName=LDAPINFO

with username and password.

how to connect it in PHP? seem like i cant use JDBC in PHP?


问:
Temporarily exit the MySQL command line to shell (bash)
Is it possible to temporarily exit from MySQL command line to shell (bash) and then get back to MySQL CLI again? In Vim it is possible with the help of :sh command and ^-D to get back to Vim. I'm interested if the same is possible in MySQL?

答:
Use the system (or, short, \!) MySQL client command to execute an external shell command.

If you want to spawn a shell then try:

```<code>system bash;
</code>```

or, shorter:

```<code>\! bash;
</code>```

When bash ends (with exit or Ctrl-D) the control gets back to the mysql client program.

Use the help command to see all MySQL client commands.

Body:
Use the system (or, short, \!) MySQL client command to execute an external shell command.

If you want to spawn a shell then try:

system bash;

or, shorter:

\! bash;

When bash ends (with exit or Ctrl-D) the control gets back to the mysql client program.

Use the help command to see all MySQL client commands.


问:
Ionic app takes too much time to load on android nexus 5X
I am developing an Ionic app, It works fine in other android devices even on iPhone, but on it takes too much time to load on android nexus 5X.

This is the screens showing for like 3-4 minutes

Then This screen shows up,

Then app finally loads.

Is there any solution to fix this?

答:
Taking 4-5 minutes sounds like way too long. Without any further info there's not much we can do to find out, but adding --prod flag is sure to help a lot.

ionic run android --prod


问:
Linq select self reference during creation in C#
Basically what I want is the same that is answered here but in C#:
Self-references in object literal declarations

What I have is this code:

```<code>private List<myObject> myFunction()
{
    return myList.Select(l => new myObject
    {
        propA = 6,
        propB = 3,
        propC = propA + propB
    }
    ).ToList();
}
</code>```

Of course it does not work, because I cannot reference propA and propB this way. What it the right way to do it?

Thank you

答:
If you're not working with Linq to objects, (i.e. the lambdas are required to be expressions, not method delegates as with Linq to SQL/Entity Framework) you could do this with the help of an anonymous object and two Select statements:</p>

```<code>return myList
    .Select(l => new {
        propA = 6,
        propB = 3})
    .Select(x => new myObject{
        propA = x.propA,
        propB = x.propB,
        propC = x.propA + x.propB
    })
    .ToList();
</code>```

Body:
Basically what I want is the same that is answered here but in C#:
Self-references in object literal declarations

What I have is this code:

private List<myObject> myFunction()
{
    return myList.Select(l => new myObject
    {
        propA = 6,
        propB = 3,
        propC = propA + propB
    }
    ).ToList();
}

Of course it does not work, because I cannot reference propA and propB this way. What it the right way to do it?

Thank you

Body:
If you're not working with Linq to objects, (i.e. the lambdas are required to be expressions, not method delegates as with Linq to SQL/Entity Framework) you could do this with the help of an anonymous object and two Select statements:

return myList
    .Select(l => new {
        propA = 6,
        propB = 3})
    .Select(x => new myObject{
        propA = x.propA,
        propB = x.propB,
        propC = x.propA + x.propB
    })
    .ToList();


问:
Gurobi and Python: how to query a dictionary using optimal variable solutions
I'm using Python and Gurobi and I'm having difficulty on how to optimal variable solutions to query a dictionary.

```<code>my_dict = {(i, j) : func(Z) for i in I for j in J}
</code>```

my_dict results to be like this:

```<code>{(15687, 'B'): [[7, 0, 0, 0], [0, 7, 0, 0], [0, 0, 7, 0], [0, 0, 0, 7]],
  ...
 (18906, 'C'): [[4, 0, 0, 3], [3, 0, 0, 3], [4, 0, 0, 0], [3, 0, 0, 0]}
</code>```

Moreover I have a binary variable x[i, j, z] and an assignment constraint:

```<code>assignment = m.addConstrs((quicksum(x[i, j, z]
                                   for z in range(len(my_dict[i, j]))) == 1
                                   for i in I for j in J), "assignment")
</code>```

Supposing I obtain as optimal solution variables

```<code>x[15687,'B',0] 1.000000
x[18906,'C',2] 1.000000
</code>```

Is there a way to retrieve the sublist of my_dict corresponding to the "z" index?
(For instance, if my solution is x[18906,'C',2] 1.000000  then z = 2 and I want to obtain the sublist [4, 0, 0, 0])

答:
Your code is not really a nice minimal example to work with, so it's hard to post valid code.

The general problem does not look that tough.

If your original dict looks like:

```<code>{(15687, 'B'): [[7, 0, 0, 0], [0, 7, 0, 0], [0, 0, 7, 0], [0, 0, 0, 7]],
  ...
 (18906, 'C'): [[4, 0, 0, 3], [3, 0, 0, 3], [4, 0, 0, 0], [3, 0, 0, 0]}
</code>```

and your solution is my_dict_opt, probably something like this should do (python3):

```<code>import numpy as np   # easy fp-math comparison

sublists = []
for key, val in my_dict.items():
    n_vars = len(val)  # my assumption
    for i in range(n_vars):
        if np.isclose(my_dict_opt[key + tuple([i])].X, 1.0):  # depends on your dict if .X is needed
            sublists.append(my_dict[key][i])
</code>```

Because of the dicts, the order of elements in sublists is not defined and this should only be a prototype as it's not really clear to me how those dicts are in use for you.

Body:
I'm using Python and Gurobi and I'm having difficulty on how to optimal variable solutions to query a dictionary.

my_dict = {(i, j) : func(Z) for i in I for j in J}

my_dict results to be like this:

{(15687, 'B'): [[7, 0, 0, 0], [0, 7, 0, 0], [0, 0, 7, 0], [0, 0, 0, 7]],
  ...
 (18906, 'C'): [[4, 0, 0, 3], [3, 0, 0, 3], [4, 0, 0, 0], [3, 0, 0, 0]}

Moreover I have a binary variable x[i, j, z] and an assignment constraint:

assignment = m.addConstrs((quicksum(x[i, j, z]
                                   for z in range(len(my_dict[i, j]))) == 1
                                   for i in I for j in J), "assignment")

Supposing I obtain as optimal solution variables

x[15687,'B',0] 1.000000
x[18906,'C',2] 1.000000

Is there a way to retrieve the sublist of my_dict corresponding to the "z" index?
(For instance, if my solution is x[18906,'C',2] 1.000000  then z = 2 and I want to obtain the sublist [4, 0, 0, 0])

Body:
Your code is not really a nice minimal example to work with, so it's hard to post valid code.

The general problem does not look that tough.

If your original dict looks like:

{(15687, 'B'): [[7, 0, 0, 0], [0, 7, 0, 0], [0, 0, 7, 0], [0, 0, 0, 7]],
  ...
 (18906, 'C'): [[4, 0, 0, 3], [3, 0, 0, 3], [4, 0, 0, 0], [3, 0, 0, 0]}

and your solution is my_dict_opt, probably something like this should do (python3):

import numpy as np   # easy fp-math comparison

sublists = []
for key, val in my_dict.items():
    n_vars = len(val)  # my assumption
    for i in range(n_vars):
        if np.isclose(my_dict_opt[key + tuple([i])].X, 1.0):  # depends on your dict if .X is needed
            sublists.append(my_dict[key][i])

Because of the dicts, the order of elements in sublists is not defined and this should only be a prototype as it's not really clear to me how those dicts are in use for you.


问:
Angular Looped HTTP Request Map Value to Responses
In my service class I am looping an http get request and using rxjs forkJoin to combine all the responses into an observable which I return to my component.  For each response that comes back I need to add two properties to the json (readySystem which is an object and serviceType which is a string).  The value of each of these is different for each iteration of the loop.

How do I keep/store/retain the values for both and and map/add them to the correct response?

With the way I've attempted to do it below, the values for both are the same in every response returned in the final observable.

```<code>  getServices() {

  for (var x = 0; x < this.service.items.length; x++ ){
        var num = Object.keys(this.service.items[x].links).length;

         for (var key in this.service.items[x].links) {
            var systemName = this.service.items[x].systemName;
            var environment = this.service.items[x].environment;
            var server = this.service.items[x].server;
            var port = this.service.items[x].port;
            var linkName = this.service.items[x].links[key];
            var serviceType = key;
            this.observables.push(
            this.http.get('http://localhost:3000/myapi/get/service?server=' + server + '&service=' + linkName)
            .map((res:Response) => {
                var output = res.json()
                for (var obj in output) {
                    if (output.hasOwnProperty(obj)){

                        var readySystem = new System(systemName,
                         environment,
                         server,
                         port,
                         linkName);

                    output[obj].System = readySystem;
                    output[obj].serviceType = serviceType;
                    }
                }
                return output;
        })
            );
        }
        };
        return Observable.forkJoin(this.observables);
};
</code>```

Update: With the suggested code changes provided in the answer below, I get output like:

```<code>0: Array(33)
1: System
    systemName: "my system"
    environment: "my environment"
    etc.
2: "myservice"
3: Array(35)
4: System
   etc.
5: "myotherservice"
</code>```

However, what is needed is:

```<code>0: Array(33)
 0: Object
  > System
      systemName: "my system"
      environment: "my environment"
      etc.
   serviceType: "myservice"
 1: Object
  > System
      systemName: "my system"
      environment: "my environment"
      etc.
   serviceType: "myotherservice"
 etc.
1: Array(35)
 0: Object
</code>```

答:
It's a closure problem. Based on your original code:

```<code>for (var key in this.service.items[x].links) {
    var systemName = this.service.items[x].systemName;
</code>```

here you may think that you're creating a new systemName variable each time the block is executed. Indeed, the variable is created once and it only gets assigned the new value each time the block is executed. The difference is important because below you make an asynchronous call http.get:

```<code>this.observables.push(
          this.http.get('http://localhost:3000/myapi/get/service?server=' + server + '&service=' + linkName)
            .map(res => {
              var output = res.json()
              for (var obj in output) {
                if (output.hasOwnProperty(obj)){
                  var readySystem = new System(systemName,
</code>```

here the callback inside the map is not executed immediately within the loop when systemName has the proper value. It just gets stored in memory for later execution (when http.get returns a result). The stored body of the callback doesn't carry systemName value, only a reference to the variable.

Now, each time the loop executes, it assigns a new value to systemName and stores away a callback. By the time the loop ends, the value of systemName is the last value assigned by the loop.

Sometime later, the http.get requests start completing, the stored callbacks are executed, they read systemName and they all get that same last value. This is what you're experiencing.

The easiest fix is actually creating a new systemName variable for each block execution. This can be achieved by using let instead of var. So just using let for all the relevant variables will fix the issue:

```<code>let systemName = this.service.items[x].systemName;
let environment = this.service.items[x].environment;
let server = this.service.items[x].server;
let port = this.service.items[x].port;
let linkName = this.service.items[x].links[key];
let serviceType = key;
</code>```

Body:
In my service class I am looping an http get request and using rxjs forkJoin to combine all the responses into an observable which I return to my component.  For each response that comes back I need to add two properties to the json (readySystem which is an object and serviceType which is a string).  The value of each of these is different for each iteration of the loop.

How do I keep/store/retain the values for both and and map/add them to the correct response?

With the way I've attempted to do it below, the values for both are the same in every response returned in the final observable.

  getServices() {

  for (var x = 0; x < this.service.items.length; x++ ){
        var num = Object.keys(this.service.items[x].links).length;

         for (var key in this.service.items[x].links) {
            var systemName = this.service.items[x].systemName;
            var environment = this.service.items[x].environment;
            var server = this.service.items[x].server;
            var port = this.service.items[x].port;
            var linkName = this.service.items[x].links[key];
            var serviceType = key;
            this.observables.push(
            this.http.get('http://localhost:3000/myapi/get/service?server=' + server + '&service=' + linkName)
            .map((res:Response) => {
                var output = res.json()
                for (var obj in output) {
                    if (output.hasOwnProperty(obj)){

                        var readySystem = new System(systemName,
                         environment,
                         server,
                         port,
                         linkName);

                    output[obj].System = readySystem;
                    output[obj].serviceType = serviceType;
                    }
                }
                return output;
        })
            );
        }
        };
        return Observable.forkJoin(this.observables);
};

Update: With the suggested code changes provided in the answer below, I get output like:

0: Array(33)
1: System
    systemName: "my system"
    environment: "my environment"
    etc.
2: "myservice"
3: Array(35)
4: System
   etc.
5: "myotherservice"

However, what is needed is:

0: Array(33)
 0: Object
  > System
      systemName: "my system"
      environment: "my environment"
      etc.
   serviceType: "myservice"
 1: Object
  > System
      systemName: "my system"
      environment: "my environment"
      etc.
   serviceType: "myotherservice"
 etc.
1: Array(35)
 0: Object

Body:
It's a closure problem. Based on your original code:

for (var key in this.service.items[x].links) {
    var systemName = this.service.items[x].systemName;

here you may think that you're creating a new systemName variable each time the block is executed. Indeed, the variable is created once and it only gets assigned the new value each time the block is executed. The difference is important because below you make an asynchronous call http.get:

this.observables.push(
          this.http.get('http://localhost:3000/myapi/get/service?server=' + server + '&service=' + linkName)
            .map(res => {
              var output = res.json()
              for (var obj in output) {
                if (output.hasOwnProperty(obj)){
                  var readySystem = new System(systemName,

here the callback inside the map is not executed immediately within the loop when systemName has the proper value. It just gets stored in memory for later execution (when http.get returns a result). The stored body of the callback doesn't carry systemName value, only a reference to the variable.

Now, each time the loop executes, it assigns a new value to systemName and stores away a callback. By the time the loop ends, the value of systemName is the last value assigned by the loop.

Sometime later, the http.get requests start completing, the stored callbacks are executed, they read systemName and they all get that same last value. This is what you're experiencing.

The easiest fix is actually creating a new systemName variable for each block execution. This can be achieved by using let instead of var. So just using let for all the relevant variables will fix the issue:

let systemName = this.service.items[x].systemName;
let environment = this.service.items[x].environment;
let server = this.service.items[x].server;
let port = this.service.items[x].port;
let linkName = this.service.items[x].links[key];
let serviceType = key;


答:
```<code>private PaintType getNegativePaintType(String hexa) {
    int color = Color.parseColor(hexa);
    return new SolidColor((color & 0xFF000000) | (~color & 0x00FFFFFF));
}
</code>```

getNegativePaintType("#00ff11") will return "#ff00ee"

Title: How can we invert hex-color code?

Body:
My Web API will send the background color for my views, Background color range is from white #ffffff to black #000000. So I can not set any fix text color for my information text.
What is the best way to set my text color?
I'm thinking to invert the background color and set it as my text color. But I don't know How can I invert Any color or Hex color code.

e.g if my web(background) color is #00ff11 then my text color will be #ff00ee.

For this, I search over stack but did not find any method for color conversion.

Thanks

Body:
private PaintType getNegativePaintType(String hexa) {
    int color = Color.parseColor(hexa);
    return new SolidColor((color & 0xFF000000) | (~color & 0x00FFFFFF));
}

getNegativePaintType("#00ff11") will return "#ff00ee"


问:
How to implement Java/Scala in-memory statistics database?
My need is to aggregate real time statistics of a web application server.
For example:

How many requests of content type X have been done

How long it takes to process request of type Y

And so on.

This data has to be completely in memory, not in a file, for best performance. It doesn't log each and every request but instead only stores counters of various aspects.

The most easy way I know is to store the values in a SQL-like table and do SQL-like queries. The benefit is that the indexing is coming off-the-shelf without development effort. I guess some embedded Java databases like Apache Derby would do the work.

The other way to go is to implement collection (say a list) and hash table for each "index column". This way it's all done with Java/Scala collections API, but I actually have to implement indexing mechanism myself, test it, maintain it, etc.

So my question is what way do you think is preferred, and if there are other ways to easily and quickly implement this feature?

Thanks.

答:
I would choose H2 database, I have very positive experiences with it, performance is great as well.

Are you sure that SQL database is well suited for your needs, and have you looked at javamelody, to see if it suits your needs, or if it does not suit you take a look at JRobin for a rolling database implementation.


问:
Eigen SVD Double Cast
I'm trying to use the EIGEN libs. In particular I'm using the SVD.

After the calculation of the singular values I need to perform this operation:

```<code>svd.singularValues()/svd.singularValues().row(1)
</code>```

which is a vector dived by a scalar.

My questions are:

1) Why this operation gives me:

main.cpp:149:56: error: no match for ‘operator/’ (operand types are
  ‘const SingularValuesType {aka const Eigen::Matrix}’ and
  ‘Eigen::DenseBase >::ConstRowXpr {aka
  const Eigen::Block, 1, 1, false>}’)

2) How can i copy the values contained into svd.singularValues().row(1) in standard "double" variable?

答:
Note that svd.singularValues().row(1) is not a scalar but a 1x1 matrix, which is why your code does not compile. Solution:

```<code>svd.singularValues()/svd.singularValues()(1)
</code>```

and also note that as usual in C/C++, Eigen's matrices and vectors are 0-based indexed, so if you want to normalize by the largest singular values you should do:

```<code>svd.singularValues()/svd.singularValues()(0)
</code>```

Title: Eigen SVD Double Cast

Body:
I'm trying to use the EIGEN libs. In particular I'm using the SVD.

After the calculation of the singular values I need to perform this operation:

svd.singularValues()/svd.singularValues().row(1)

which is a vector dived by a scalar.

My questions are:

1) Why this operation gives me:

main.cpp:149:56: error: no match for ‘operator/’ (operand types are
  ‘const SingularValuesType {aka const Eigen::Matrix}’ and
  ‘Eigen::DenseBase >::ConstRowXpr {aka
  const Eigen::Block, 1, 1, false>}’)

2) How can i copy the values contained into svd.singularValues().row(1) in standard "double" variable?

Body:
Note that svd.singularValues().row(1) is not a scalar but a 1x1 matrix, which is why your code does not compile. Solution:

svd.singularValues()/svd.singularValues()(1)

and also note that as usual in C/C++, Eigen's matrices and vectors are 0-based indexed, so if you want to normalize by the largest singular values you should do:

svd.singularValues()/svd.singularValues()(0)


问:
Excel conditional formatting right alignment with indent
I am searching for a way to make conditional formatting on my crosstable. For some specific lines, I want that my content must be right-aligned.

E.g.
    My crosstable

```<code>column 1   |   column 2     |
0          |left-aligned
1          |   right-aligned|
0          |left-aligned
1          |   right-aligned|
</code>```

Thanks for your help.

答:
No, finally I don't need to use VBA for this. I just added a conditional formatting with custom format, like this

https://i.stack.imgur.com/BWML4.png

Steps : add conditional Formatting: if column D<>0 then use custom format
In Custom Format : put this code : ;;;* @_)

After I can hide column D to have a beautiful crosstable.

Body:
I am searching for a way to make conditional formatting on my crosstable. For some specific lines, I want that my content must be right-aligned.

E.g.
    My crosstable

column 1   |   column 2     |
0          |left-aligned
1          |   right-aligned|
0          |left-aligned
1          |   right-aligned|

Thanks for your help.


问:
How to map specific columns in spring data jpa?
Whenever I on click submit button with some value, I want to select some columns from database and show it on my jsp page. The form is successfully submitted but I'm getting this error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.psc.Entity.CandidateappearagainstadvtcodeEntity

So I think whatever data the repository is returning is not mapped with Entity. Please suggest, how to resolve this issue?

Controller:

```<code>   @RequestMapping(value = "/getCandidateDetails", method = RequestMethod.POST)
    public String getCandidateDetails(Model model,@RequestParam("studentmasterid") String studentmasterid){
        System.out.println(studentmasterid);
        List<CandidateappearagainstadvtcodeEntity> candidates=candidateappearagainstadvtcodeEntityRepository.findBystudentmasterid(studentmasterid);

        return "payments";
    }
</code>```

Model looks like this:

```<code>@Entity
@Table(name = "CANDIDATEAPPEARAGAINSTADVTCODE", schema = "PSCNEPALCOMMERCIALDATABASEU1", catalog = "")
public class CandidateappearagainstadvtcodeEntity {
    private long id;
    private String advertisementcode;
    private Integer ageonlastdateday;
    private Integer ageonlastdatemonth;
    private Integer ageonlastdateyear;
    private String applicationnumber;
    private String attendancestatus;
    private String candidatefirstname;
    private String dateofbirthinnepali;
    private String documentverificationstatus;
    private String examinationcenterid;
    private String examresultsstatus;
    private String fathername;
    private Long firstcoding;
    private String studentmasterid;
    //getters setters//
</code>```

Repository:

```<code>public interface CandidateappearagainstadvtcodeEntityRepository extends JpaRepository<CandidateappearagainstadvtcodeEntity,Long> {

    @Query("select c.studentmasterid,c.advertisementcode,c.candidatefirstname from CandidateappearagainstadvtcodeEntity c where c.studentmasterid=?1")
    List<CandidateappearagainstadvtcodeEntity> findBystudentmasterid(String masterId);
}
</code>```

ApplicationContext.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
           http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.psc"/>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
    <value>/WEB-INF/db.properties</value>
    </property>
    </bean>

    <!-- BoneCP configuration -->
    <bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="idleConnectionTestPeriodInMinutes" value="60"/>
        <property name="idleMaxAgeInMinutes" value="240"/>
        <property name="maxConnectionsPerPartition" value="30"/>
        <property name="minConnectionsPerPartition" value="10"/>
        <property name="partitionCount" value="3"/>
        <property name="acquireIncrement" value="5"/>
        <property name="statementsCacheSize" value="100"/>
        <property name="releaseHelperThreads" value="3"/>
    </bean>

    <!-- SPRING - JPA -->
    <jpa:repositories
            base-package="com.psc" />

    <bean class="org.springframework.orm.jpa.JpaTransactionManager"
          id="transactionManager">
        <property name="entityManagerFactory"
                  ref="entityManagerFactory" />
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
    </bean>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="mainDataSource" />
        <property name="packagesToScan" value="com.psc"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true" />
                <property name="showSql" value="false"/>
                <property name="databasePlatform" value="org.hibernate.dialect.Oracle12cDialect"/>
                <property name="database" value="ORACLE"/>
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</prop>
            </props>
        </property>
    </bean>

</beans>
</code>```

答:
A JPA repository usually returns the domain model. From the docs

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.

Your repository method findBystudentmasterid will be returning a list Object[] hence the ClassCastException.If you want to get specific columns try Projections.

Chekout the docs and this answer on how to use projections.

Body:
Whenever I on click submit button with some value, I want to select some columns from database and show it on my jsp page. The form is successfully submitted but I'm getting this error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.psc.Entity.CandidateappearagainstadvtcodeEntity

So I think whatever data the repository is returning is not mapped with Entity. Please suggest, how to resolve this issue?

Controller:

   @RequestMapping(value = "/getCandidateDetails", method = RequestMethod.POST)
    public String getCandidateDetails(Model model,@RequestParam("studentmasterid") String studentmasterid){
        System.out.println(studentmasterid);
        List<CandidateappearagainstadvtcodeEntity> candidates=candidateappearagainstadvtcodeEntityRepository.findBystudentmasterid(studentmasterid);

        return "payments";
    }

Model looks like this:

@Entity
@Table(name = "CANDIDATEAPPEARAGAINSTADVTCODE", schema = "PSCNEPALCOMMERCIALDATABASEU1", catalog = "")
public class CandidateappearagainstadvtcodeEntity {
    private long id;
    private String advertisementcode;
    private Integer ageonlastdateday;
    private Integer ageonlastdatemonth;
    private Integer ageonlastdateyear;
    private String applicationnumber;
    private String attendancestatus;
    private String candidatefirstname;
    private String dateofbirthinnepali;
    private String documentverificationstatus;
    private String examinationcenterid;
    private String examresultsstatus;
    private String fathername;
    private Long firstcoding;
    private String studentmasterid;
    //getters setters//

Repository:

public interface CandidateappearagainstadvtcodeEntityRepository extends JpaRepository<CandidateappearagainstadvtcodeEntity,Long> {

    @Query("select c.studentmasterid,c.advertisementcode,c.candidatefirstname from CandidateappearagainstadvtcodeEntity c where c.studentmasterid=?1")
    List<CandidateappearagainstadvtcodeEntity> findBystudentmasterid(String masterId);
}

ApplicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
           http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.psc"/>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
    <value>/WEB-INF/db.properties</value>
    </property>
    </bean>

    <bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="idleConnectionTestPeriodInMinutes" value="60"/>
        <property name="idleMaxAgeInMinutes" value="240"/>
        <property name="maxConnectionsPerPartition" value="30"/>
        <property name="minConnectionsPerPartition" value="10"/>
        <property name="partitionCount" value="3"/>
        <property name="acquireIncrement" value="5"/>
        <property name="statementsCacheSize" value="100"/>
        <property name="releaseHelperThreads" value="3"/>
    </bean>

    <jpa:repositories
            base-package="com.psc" />

    <bean class="org.springframework.orm.jpa.JpaTransactionManager"
          id="transactionManager">
        <property name="entityManagerFactory"
                  ref="entityManagerFactory" />
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
    </bean>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="mainDataSource" />
        <property name="packagesToScan" value="com.psc"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true" />
                <property name="showSql" value="false"/>
                <property name="databasePlatform" value="org.hibernate.dialect.Oracle12cDialect"/>
                <property name="database" value="ORACLE"/>
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</prop>
            </props>
        </property>
    </bean>

</beans>


问:
taking multiple inputs in a specific format as a single input in java
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e.  07:05:45PM

The C equivalent solution for this particular solution is as follows:

```<code>scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;
</code>```

I am looking for the java equivalent of this code.

答:
The closest I could get is this but this would work only if there was some delimiter between 45 and PM in 07:05:45PM like 07:05:45 PM. Otherwise, the input needs to be taken as String and parsed.

```<code>static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
  int hh, mm, ss;
  String t12;
  scanner.useDelimiter("[:\n ]");
  hh = scanner.nextInt();
  mm = scanner.nextInt();
  ss = scanner.nextInt();
  t12 = scanner.next();
  System.out.println(hh);
  System.out.println(mm);
  System.out.println(ss);
  System.out.println(t12);
}
</code>```

Body:
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e.  07:05:45PM

The C equivalent solution for this particular solution is as follows:

scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;

I am looking for the java equivalent of this code.

Body:
The closest I could get is this but this would work only if there was some delimiter between 45 and PM in 07:05:45PM like 07:05:45 PM. Otherwise, the input needs to be taken as String and parsed.

static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
  int hh, mm, ss;
  String t12;
  scanner.useDelimiter("[:\n ]");
  hh = scanner.nextInt();
  mm = scanner.nextInt();
  ss = scanner.nextInt();
  t12 = scanner.next();
  System.out.println(hh);
  System.out.println(mm);
  System.out.println(ss);
  System.out.println(t12);
}


问:
Lambda variable names - to short name, or not to short name?
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);
</code>```

Some question this naming, and would prefer to see long typed out names, like this:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);
</code>```

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

答:
I'd say I agree with BFree.  That, for me, it will depend on the context, but I always try to make it as 'concise' as possible.  Notice I say concise, and not terse or short.

Here's two examples in the LISP dialect Clojure:

```<code>user=> (def names ["ryan" "bob" "tom" "tim"])
#'user/names

user=> (filter (fn [name] (.startsWith name "t")) names)
("tom" "tim")
</code>```

For those that don't know Lisp/Clojure, my lambda is the argument to the function 'filter'.  That is, "(fn [name] ....)".  I chose to use 'name' here because it's short but describes exactly what I'm working with.  However, I think an 'a', 'i', 'x', etc would be just as readable.

```<code>user=> (def odds (iterate (fn [n] (+ n 2)) 1))
#'user/odds

user=> (take 5 odds)
(1 3 5 7 9)
</code>```

Here, I just use 'n' to stand for 'number'.  I think 'number' would be OK too, but is slightly too verbose for my taste.

I certainly would NOT use the names 'nameOfPerson' or 'previousOddNumber'.  That's just WAY too much information.  I also try to keep types out of my names most of the time, e.g. 'nameString'.  I find stuff like that, most of the time, to be superfluous information.

Personally, I think extra verbose names like that tend to stem from the idea that it helps document the code.  It is especially prevalent in languages like Java/C# it seems.  I think this could be argued both ways, depending on the programmer's style.  However, the more verbose the name, the more tight (read brittle) the code can become.  If my name is very specific, and it's a function changes often, then chances are the name will have to change a lot too.  Eventually, the DEV might get lazy and you'll end up with a name that doesn't actually describe what the variable is used for.  This is not a problem, if and only if the programmer doesn't assume the name is correct.  Granted, this would probably be figured out quickly during compilation (because the programmer will try to divide two strings or some such thing), but it can cause wasted time and confusion in larger projects.

I would also argue for conciseness because of screen real-estate.  I still try to wrap my rows at 80 columns wide, and that's hard when 'myVaraibleNameIsAsLongAsAParagraph'.

Ultimately, I think it's always going to come down to compromise.  So they don't like 'a', but maybe they can agree that you should strive for one-word names like 'person' or 'number', and avoid that awful camel case.

Sorry for the book.

OwnerDisplayName: TheSoftwareJedi

Body:
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);

Some question this naming, and would prefer to see long typed out names, like this:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

LastEditorDisplayName: TheSoftwareJedi

Body:
I'd say I agree with BFree.  That, for me, it will depend on the context, but I always try to make it as 'concise' as possible.  Notice I say concise, and not terse or short.

Here's two examples in the LISP dialect Clojure:

user=> (def names ["ryan" "bob" "tom" "tim"])
#'user/names

user=> (filter (fn [name] (.startsWith name "t")) names)
("tom" "tim")

For those that don't know Lisp/Clojure, my lambda is the argument to the function 'filter'.  That is, "(fn [name] ....)".  I chose to use 'name' here because it's short but describes exactly what I'm working with.  However, I think an 'a', 'i', 'x', etc would be just as readable.

user=> (def odds (iterate (fn [n] (+ n 2)) 1))
#'user/odds

user=> (take 5 odds)
(1 3 5 7 9)

Here, I just use 'n' to stand for 'number'.  I think 'number' would be OK too, but is slightly too verbose for my taste.

I certainly would NOT use the names 'nameOfPerson' or 'previousOddNumber'.  That's just WAY too much information.  I also try to keep types out of my names most of the time, e.g. 'nameString'.  I find stuff like that, most of the time, to be superfluous information.

Personally, I think extra verbose names like that tend to stem from the idea that it helps document the code.  It is especially prevalent in languages like Java/C# it seems.  I think this could be argued both ways, depending on the programmer's style.  However, the more verbose the name, the more tight (read brittle) the code can become.  If my name is very specific, and it's a function changes often, then chances are the name will have to change a lot too.  Eventually, the DEV might get lazy and you'll end up with a name that doesn't actually describe what the variable is used for.  This is not a problem, if and only if the programmer doesn't assume the name is correct.  Granted, this would probably be figured out quickly during compilation (because the programmer will try to divide two strings or some such thing), but it can cause wasted time and confusion in larger projects.

I would also argue for conciseness because of screen real-estate.  I still try to wrap my rows at 80 columns wide, and that's hard when 'myVaraibleNameIsAsLongAsAParagraph'.

Ultimately, I think it's always going to come down to compromise.  So they don't like 'a', but maybe they can agree that you should strive for one-word names like 'person' or 'number', and avoid that awful camel case.

Sorry for the book.

OwnerDisplayName: rzezeski


问:
QT: Store QTextStream in QList
I'm trying to open multiple files simultaneously (random number of files) and store their textstreams in qlist for simple using in other code:

```<code>QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations

// collect qtextsrams into qlist
foreach (QString file, fnames) {
        QFile f(file);
        f.open(QIODevice::ReadOnly);
        QTextStream textStream(&f);
        files2.append(&textStream);
}

// use qtextstreams in a loop
QList<QTextStream>::iterator i;
for (i = files.begin(); i != files.end(); ++i) {
      qDebug() << i->readLine();
}
</code>```

So i have an error:

```<code>/make debug
make -f Makefile.Debug
make[1]: Entering directory `/home/pixx/Workspace/collocs'
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -o debug/main.o main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:128: error: no matching function for call to ‘QList<QTextStream>::append(QTextStream*)’
/usr/include/qt4/QtCore/qlist.h:493: note: candidates are: void QList<T>::append(const T&) [with T = QTextStream]
/usr/include/qt4/QtCore/qlist.h:819: note:                 void QList<T>::append(const QList<T>&) [with T = QTextStream]
main.cpp:117: warning: unused variable ‘cc’
In file included from /usr/include/qt4/QtCore/QList:1,
                 from main.cpp:1:
/usr/include/qt4/QtCore/qtextstream.h: In member function ‘void QList<T>::node_copy(QList<T>::Node*, QList<T>::Node*, QList<T>::Node*) [with T = QTextStream]’:
/usr/include/qt4/QtCore/qlist.h:695:   instantiated from ‘void QList<T>::detach_helper(int) [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:709:   instantiated from ‘void QList<T>::detach_helper() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:126:   instantiated from ‘void QList<T>::detach() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:254:   instantiated from ‘QList<T>::iterator QList<T>::begin() [with T = QTextStream]’
main.cpp:133:   instantiated from here
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:386: error: within this context
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:399: error: within this context
make[1]: Leaving directory `/home/pixx/Workspace/collocs'
make[1]: *** [debug/main.o] Error 1
make: *** [debug] Error 2
</code>```

What should i fix?
I understand that it's very simple question, but i can't find right query for google :(

答:
I found a solution, thanks Septagram for idea!  QList files2; // file list to merge</p>

```<code>QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations
QList<QFile *> files2; // file list to merge
QList<QTextStream *> files3;
foreach (QString file, files) {
    files2.append(new QFile(file)); // create file obj
    files2.last()->open(QIODevice::ReadOnly); // open file
    files3.append(new QTextStream(files2.last())); // create textstream
}

QList< QTextStream * >::iterator i3;
for (i3 = files3.begin(); i3 != files3.end(); ++i3) {
      qDebug() << (*i3)->readLine();
}
</code>```

Title: QT: Store QTextStream in QList

Body:
I'm trying to open multiple files simultaneously (random number of files) and store their textstreams in qlist for simple using in other code:

QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations

// collect qtextsrams into qlist
foreach (QString file, fnames) {
        QFile f(file);
        f.open(QIODevice::ReadOnly);
        QTextStream textStream(&f);
        files2.append(&textStream);
}

// use qtextstreams in a loop
QList<QTextStream>::iterator i;
for (i = files.begin(); i != files.end(); ++i) {
      qDebug() <readLine();
}

So i have an error:

/make debug
make -f Makefile.Debug
make[1]: Entering directory `/home/pixx/Workspace/collocs'
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -o debug/main.o main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:128: error: no matching function for call to ‘QList<QTextStream>::append(QTextStream*)’
/usr/include/qt4/QtCore/qlist.h:493: note: candidates are: void QList<T>::append(const T&) [with T = QTextStream]
/usr/include/qt4/QtCore/qlist.h:819: note:                 void QList<T>::append(const QList<T>&) [with T = QTextStream]
main.cpp:117: warning: unused variable ‘cc’
In file included from /usr/include/qt4/QtCore/QList:1,
                 from main.cpp:1:
/usr/include/qt4/QtCore/qtextstream.h: In member function ‘void QList<T>::node_copy(QList<T>::Node*, QList<T>::Node*, QList<T>::Node*) [with T = QTextStream]’:
/usr/include/qt4/QtCore/qlist.h:695:   instantiated from ‘void QList<T>::detach_helper(int) [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:709:   instantiated from ‘void QList<T>::detach_helper() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:126:   instantiated from ‘void QList<T>::detach() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:254:   instantiated from ‘QList<T>::iterator QList<T>::begin() [with T = QTextStream]’
main.cpp:133:   instantiated from here
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:386: error: within this context
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:399: error: within this context
make[1]: Leaving directory `/home/pixx/Workspace/collocs'
make[1]: *** [debug/main.o] Error 1
make: *** [debug] Error 2

What should i fix?
I understand that it's very simple question, but i can't find right query for google :(

Body:
I found a solution, thanks Septagram for idea!  QList files2; // file list to merge

QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations
QList<QFile *> files2; // file list to merge
QList<QTextStream *> files3;
foreach (QString file, files) {
    files2.append(new QFile(file)); // create file obj
    files2.last()->open(QIODevice::ReadOnly); // open file
    files3.append(new QTextStream(files2.last())); // create textstream
}

QList< QTextStream * >::iterator i3;
for (i3 = files3.begin(); i3 != files3.end(); ++i3) {
      qDebug() << (*i3)->readLine();
}


问:
Reading .txt in matlab cause closing the software
I want to read this txt file by Matlab. It is 19 MB. When I run

```<code>filename = 'clus.txt';
[clussiz,delimiterOut]=importdata(filename);
</code>```

After a while, Matlab is closed. And there is a message in terminal:
killed.

I think it is because .txt file is so heavy. What should I do to read and use the information of data?

This is diffrent fro the question of how to read file in Matlab because in this case, I want to read a heavy data.

答:
```<code>data = load('clus_size.txt') ;
</code>```

Should work..

Also:

```<code>data = csvread('clus_size.txt') ;
</code>```

Body:
I want to read this txt file by Matlab. It is 19 MB. When I run

filename = 'clus.txt';
[clussiz,delimiterOut]=importdata(filename);

After a while, Matlab is closed. And there is a message in terminal:
killed.

I think it is because .txt file is so heavy. What should I do to read and use the information of data?

This is diffrent fro the question of how to read file in Matlab because in this case, I want to read a heavy data.

Body:
data = load('clus_size.txt') ;

Should work..

Also:

data = csvread('clus_size.txt') ;