问:
How do I remove all my mysterious "index on" and "WIP on" commits?
I was just called upon to fix a bug in my application. I stashed up my current work and checked out my newest version tag. I promptly noticed that was a mistake, as the Git message told me that my commits wouldn't be saved, so I checked out master instead. But before I did that, I had already popped my stash, the re-stashed:

```$ git checkout v1.6.0
$ git stash pop
$ # Oops, I'm not supposed to be here
$ git stash
$ git checkout master
$ git stash pop```

Then I fixed the bug, committed and created a new tag for it (v1.6.0-hotfix-1). Now my repository looks like it has been bombed. It used to be so clean, with two branches side by side with a merge and a tag now and then. Now it looks like this:

Suddenly all my tags on the master branch is squished together instead of far apart, and there are "index on" and "WIP on" commits spread around, probably due to the stashing. I'm going with the assumption that those "commits" are the reason for the mess, so I'd like to remove them.

But how do I do that? Could anybody explain what is going on?

Edit: Screenshot after restarting gitk:

All the "index on" and "WIP on" points are gone, but my repo still looks bombed. How can that be?

答: You use the 'Reload' gesture, that in some mileages is mapped by default to Ctrl-F5 and in some others to Shift-F5. Often found in the GUI menus under the File menu.

Body:
I was just called upon to fix a bug in my application. I stashed up my current work and checked out my newest version tag. I promptly noticed that was a mistake, as the Git message told me that my commits wouldn't be saved, so I checked out master instead. But before I did that, I had already popped my stash, the re-stashed:

$ git checkout v1.6.0
$ git stash pop
$ # Oops, I'm not supposed to be here
$ git stash
$ git checkout master
$ git stash pop

Then I fixed the bug, committed and created a new tag for it (v1.6.0-hotfix-1). Now my repository looks like it has been bombed. It used to be so clean, with two branches side by side with a merge and a tag now and then. Now it looks like this:

Suddenly all my tags on the master branch is squished together instead of far apart, and there are "index on" and "WIP on" commits spread around, probably due to the stashing. I'm going with the assumption that those "commits" are the reason for the mess, so I'd like to remove them.

But how do I do that? Could anybody explain what is going on?

Edit: Screenshot after restarting gitk:

All the "index on" and "WIP on" points are gone, but my repo still looks bombed. How can that be?


来源: stackexchange

问:
Custom sort Map Java
i have some troubles when i want to sort a map, when i create a map passing a string, it comes organized like

```<code>nombre=EDIFICADORA JUANA, descripcion=  LOS frst com MEJORES Estamso para servir LOS, correo1=rst008@guan.com, correo2=oipoa@gmaio.com, numero1=24602254, numero2=55655545
</code>```

When i create a map using this data it comes disordered, this is the method that creates the map:

```<code>   private HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}
</code>```

This function returns something like:

0 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

1 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

2 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

3 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

4 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso
par"

5 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

How can i sort this Map like the string value comes?

I expect:

0 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

1 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso par"

2 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

3 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

4 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

5 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

答:
Use a LinkedHashMap, this will keep the insertion order.

Simply replace

```<code>new HashMap<>();
</code>```

with

```<code>new LinkedHashMap<>();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Custom sort Map Java

Body:
i have some troubles when i want to sort a map, when i create a map passing a string, it comes organized like

nombre=EDIFICADORA JUANA, descripcion=  LOS frst com MEJORES Estamso para servir LOS, correo1=rst008@guan.com, correo2=oipoa@gmaio.com, numero1=24602254, numero2=55655545

When i create a map using this data it comes disordered, this is the method that creates the map:

   private HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}

This function returns something like:

0 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

1 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

2 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

3 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

4 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso
par"

5 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

How can i sort this Map like the string value comes?

I expect:

0 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

1 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso par"

2 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

3 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

4 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

5 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

Body:
Use a LinkedHashMap, this will keep the insertion order.

Simply replace

new HashMap<>();

with

new LinkedHashMap<>();


问:
How to allign login form fields to same row?
I want to allign login fields in my form to be in the same row like is here. I tryed some CSS codes, but that dont align in way i like.

My login form:

How i want to make it:

This is CSS for that part:

```<code>.log_forms input[type=text], input[type=password] {
margin: 10px 0 20px;
width: 99%;
padding: 7px 0 7px 4px;
border: 1px solid #E3E3E3;
</code>```

答:
Your
 lacks a width. Please add this in the CSS:

.log-form-group {
  display: inline-block;
  width: 48%;
}
```

<p><strong>Preview</strong></p>

<p><img src="https://i.stack.imgur.com/x7PYJm.png" alt="preview"></p>

<p><strong>Updated</strong></p>

<p>This is the extra CSS you need:</p>

<pre class="lang-css prettyprint-override"><code>.log_forms input[type=text], input[type=password] {width: 95% !important;}
.log-form-group {width: 32%;}
</code>```

And you get this:

Body:
I want to allign login fields in my form to be in the same row like is here. I tryed some CSS codes, but that dont align in way i like.

My login form:

How i want to make it:

This is CSS for that part:

.log_forms input[type=text], input[type=password] {
margin: 10px 0 20px;
width: 99%;
padding: 7px 0 7px 4px;
border: 1px solid #E3E3E3;

Body:
Your <div> lacks a width. Please add this in the CSS:

.log-form-group {
  display: inline-block;
  width: 48%;
}

Preview

Updated

This is the extra CSS you need:

.log_forms input[type=text], input[type=password] {width: 95% !important;}
.log-form-group {width: 32%;}

And you get this:


问:
jsgrid bound with mvc data
I am trying to bind jsGrid with json data OR a list of objects..whatever is possible..

```<code>$("#mapsDiv").jsGrid({
        height: "auto",
        width: "100%",

        sorting: true,
        paging: false,
        autoload: true,
        data: students,
        controller: {
            loadData: function () {
                var d = $.Deferred();

                $.ajax({
                    url: '@Url.Action("About", "Home")',
                    dataType: "json"
                }).done(function (response) {
                    d.resolve(response.value);
                });

                return d.promise();
            }
        },

        fields: [
            { name: "firstname", type: "text" },
            { name: "surname", type: "text"},
            {
                name: "birthdate", type: "text"
            },
            {
                name: "classname", type: "text"
            }
        ]
    });
</code>```

HomeController

```<code>public ActionResult About(){
...
return Json(students, JsonRequestBehavior.AllowGet);
}
</code>```

OR

```<code>public ActionResult About(){
...
return View(students);
}
</code>```

in case of json, my web page shows a raw json string only, in case i return a list of student objects, everything else is on page but no grid.

What am i doing wrong?

On a side note, can i bind this grid with @Model as we do in markup?

答:
I recently had a similar issue with not being able to manipulate json data and being stuck passing static data from applying a key to my data dictionary.

After looking around http://js-grid.com/docs/ this is an example of how I used a custom rowRenderer (that you could easily embed logic into) to process jsGrid data

My JS jsgrid code looks something like this

```<code>$("#jsGrid").jsGrid({

data : [{ 'name' : 'Louise' , 'duties' : ['pranks', 'busing tables'] },
        { 'name' : 'Linda' , 'duties' : ['waiting tables', 'singing', 'comedic relief'] }],

rowRenderer: function(item, itemIndex) {
     var newRow = $('<tr>'); // create a new, empty HTML tr element

     let nameCell = $('<td>');
     let dutiesCell = $('<td>');
     let summaryCell = $('<td>');

     let nameCellData = item['name']
     let dutiesCellData = item['duties']
     let summaryCellData = 'This is row ' + itemIndex + ' of this grid. The name of the employee that this row is about is ' + item['name'] + ' and she has ' + item['duties'].length + ' duties at the family restaurant!';

     $(nameCell).append(document.createTextNode(nameCellData));
     $(dutiesCell).append(document.createTextNode(dutiesCellData));
     $(summaryCell).append(document.createTextNode(summaryCellData));

     $(newRow).append(nameCell);
     $(newRow).append(dutiesCell);
     $(newRow).append(summaryCell);

     return newRow;
},
</code>```

..... (insert the rest of your jsgrid config here)

The main saving grace is the overlooked rowRenderer. From the docs, the function can use item which is used to iterate through the dictionaries in my example array, itemIndex is the row number in the jsGrid (which may be helpful for formatting later on), and I took advantage of this format to call my own keys on item. I hope this helps!

Title: jsgrid bound with mvc data

Body:
I am trying to bind jsGrid with json data OR a list of objects..whatever is possible..

$("#mapsDiv").jsGrid({
        height: "auto",
        width: "100%",

        sorting: true,
        paging: false,
        autoload: true,
        data: students,
        controller: {
            loadData: function () {
                var d = $.Deferred();

                $.ajax({
                    url: '@Url.Action("About", "Home")',
                    dataType: "json"
                }).done(function (response) {
                    d.resolve(response.value);
                });

                return d.promise();
            }
        },

        fields: [
            { name: "firstname", type: "text" },
            { name: "surname", type: "text"},
            {
                name: "birthdate", type: "text"
            },
            {
                name: "classname", type: "text"
            }
        ]
    });

HomeController

public ActionResult About(){
...
return Json(students, JsonRequestBehavior.AllowGet);
}

OR

public ActionResult About(){
...
return View(students);
}

in case of json, my web page shows a raw json string only, in case i return a list of student objects, everything else is on page but no grid.

What am i doing wrong?

On a side note, can i bind this grid with @Model as we do in markup?

Body:
I recently had a similar issue with not being able to manipulate json data and being stuck passing static data from applying a key to my data dictionary.

After looking around http://js-grid.com/docs/ this is an example of how I used a custom rowRenderer (that you could easily embed logic into) to process jsGrid data

My JS jsgrid code looks something like this

$("#jsGrid").jsGrid({

data : [{ 'name' : 'Louise' , 'duties' : ['pranks', 'busing tables'] },
        { 'name' : 'Linda' , 'duties' : ['waiting tables', 'singing', 'comedic relief'] }],

rowRenderer: function(item, itemIndex) {
     var newRow = $('<tr>'); // create a new, empty HTML tr element

     let nameCell = $('<td>');
     let dutiesCell = $('<td>');
     let summaryCell = $('<td>');

     let nameCellData = item['name']
     let dutiesCellData = item['duties']
     let summaryCellData = 'This is row ' + itemIndex + ' of this grid. The name of the employee that this row is about is ' + item['name'] + ' and she has ' + item['duties'].length + ' duties at the family restaurant!';

     $(nameCell).append(document.createTextNode(nameCellData));
     $(dutiesCell).append(document.createTextNode(dutiesCellData));
     $(summaryCell).append(document.createTextNode(summaryCellData));

     $(newRow).append(nameCell);
     $(newRow).append(dutiesCell);
     $(newRow).append(summaryCell);

     return newRow;
},

..... (insert the rest of your jsgrid config here)

The main saving grace is the overlooked rowRenderer. From the docs, the function can use item which is used to iterate through the dictionaries in my example array, itemIndex is the row number in the jsGrid (which may be helpful for formatting later on), and I took advantage of this format to call my own keys on item. I hope this helps!


问:
Subset using Backtracking
The following question I was asked to solve using backtracking:
It's supposed to return the length of the longest subset of differences that replaces a sign.
For example:
for this given series [11,6,7,8,9] it returns 3.
because it includes this subset [11,8,9] and [11,6,8] .

*In this series a:[11,8,9] a[1]-a[0]<0 and a[2]-a[1]>0 .In other words the sign of the difference between each neighbor changes. *

I pretty much finished the coding but have no idea how to return the max length using backtracking.

Any note/help will be highly appreciated.

```<code>/* this function checks if we can add another number to the sequence
   and still the differences between the numbers replace a sign.It's enough
   to check the last two*/
int check_rec(int series[],int arr[],int n)
{ int count=0,c=n;
  int temp1=0,temp2=0;
    while(c>=0 && count!=2)
    {
        if (arr[c]==1 && count==0)
        { temp1=series[c];
          count++;
        }
        if (arr[c]==1 && count==1 )
        { temp1=series[c];
          count++;
        }
        c--;
    }
    if(count<2) return 1;
    if(temp1>temp2 && series[n+1] < temp1) return 1;
    if(temp1<temp2 && series[n+1]> temp1) return 1;
    return 0;
}

int count_ones(int arr[],int n)
{   int c;
    for(int i=0;i<n;i++)
    {
        if(arr[i])
            c++;
    }
    return c;
}
    // 1 in the array helper indicates that the index has been chosen.
    void max_crazy(int series[], int n,int helper[],int length,int max[])
{
    if(n==0)
         {
            int x=count_ones(helper,n);
            if(x>max[0])
                max[0]=x;
             }
    for(int i=0;i<2;i++)
    {
        if(n!=length && i==1 && !check_rec(series,helper,length-n))
           continue;

        helper[0]=i;
        max_crazy(series,n-1,helper+1,length,max);
    }

}
</code>```

答: you can send a pointer that saves the max in the recursive function , and every time you reach the if(n==0) you have to check if the count_ones bigger than max then max=count_ones </p>

Title: Subset using Backtracking

Body:
The following question I was asked to solve using backtracking:
It's supposed to return the length of the longest subset of differences that replaces a sign.
For example:
for this given series [11,6,7,8,9] it returns 3.
because it includes this subset [11,8,9] and [11,6,8] .

*In this series a:[11,8,9] a[1]-a[0]<0 and a[2]-a[1]>0 .In other words the sign of the difference between each neighbor changes. *

I pretty much finished the coding but have no idea how to return the max length using backtracking.

Any note/help will be highly appreciated.

/* this function checks if we can add another number to the sequence
   and still the differences between the numbers replace a sign.It's enough
   to check the last two*/
int check_rec(int series[],int arr[],int n)
{ int count=0,c=n;
  int temp1=0,temp2=0;
    while(c>=0 && count!=2)
    {
        if (arr[c]==1 && count==0)
        { temp1=series[c];
          count++;
        }
        if (arr[c]==1 && count==1 )
        { temp1=series[c];
          count++;
        }
        c--;
    }
    if(count<2) return 1;
    if(temp1>temp2 && series[n+1] < temp1) return 1;
    if(temp1<temp2 && series[n+1]> temp1) return 1;
    return 0;
}

int count_ones(int arr[],int n)
{   int c;
    for(int i=0;i<n;i++)
    {
        if(arr[i])
            c++;
    }
    return c;
}
    // 1 in the array helper indicates that the index has been chosen.
    void max_crazy(int series[], int n,int helper[],int length,int max[])
{
    if(n==0)
         {
            int x=count_ones(helper,n);
            if(x>max[0])
                max[0]=x;
             }
    for(int i=0;i<2;i++)
    {
        if(n!=length && i==1 && !check_rec(series,helper,length-n))
           continue;

        helper[0]=i;
        max_crazy(series,n-1,helper+1,length,max);
    }

}


问:
Python: Using class variables to keep track of all objects
I'm struggling with the best way to implement the following in python:

I have a simulation that generates a variety of shapes. At each run of the simulation code, new shapes composed of new line objects are generated, but these objects need to be persistent across multiple runs.

Each line is described by a polyline-encoded string. Each time a new line is generated I need to verify that the same line doesn't already exists. If it does, I want to return the original, if not, I want to create a new one.

I also need to keep track of all created objects so that at the end of multiple simulation runs, I can get them all back and send them to a database.

My first approach is to use the itertools.count iterator as a class variable, and get a new id on creation (I need to keep both the id and string for legacy reasons).

```<code>class Line(object):
    new_id = itertools.count(start=1).next
    lines = []

    def __init__(self, coord_string):
        self.coord_string = coord_string
        self.id = Line.new_id()
        Line.lines.append(self)

    @staticmethod
    def from_coord_string(coord_string):
        lines = [l.coord_string for l in Line.lines]
        try:
            ind = lines.index(path)
            return Line.links(ind)
        except ValueError:
            return Line(coord_string)
</code>```

I'm also keeping track of all created objects in the a class variable. This lets me check to see if a Line has been created already, or get easy access to all of them later, i.e.:

```<code>all_lines = Line.lines
dump_to_db(all_lines)
</code>```

What are the downsides to using class variables like this? Is there a better, or more efficient way to implement this?

答:
I would do something like this:</p>

```<code>from itertools import *
from multiprocessing import Lock

class Line(object):
    def __init__(self, ID, coord_string):
        self.id = ID
        self.coord_string = coord_string

class LineFactory(object):
    latestId = 0
    idLock = Lock()

    def __init__(self):
        self.lines = {} # Dict mapping coord_string to Line objects

    def make_new_id(self):
        with self.idLock:
            newId = self.latestId
            self.latestId += 1
        return newId

    def new_line(self, coord_string):
        if not coord_string in self.lines:
            self.lines[coord_string] = Line(self.make_new_id(), coord_string)

        return self.lines[coord_string]

    def get_all_lines(self):
        return self.lines.values
</code>```

Body:
I'm struggling with the best way to implement the following in python:

I have a simulation that generates a variety of shapes. At each run of the simulation code, new shapes composed of new line objects are generated, but these objects need to be persistent across multiple runs.

Each line is described by a polyline-encoded string. Each time a new line is generated I need to verify that the same line doesn't already exists. If it does, I want to return the original, if not, I want to create a new one.

I also need to keep track of all created objects so that at the end of multiple simulation runs, I can get them all back and send them to a database.

My first approach is to use the itertools.count iterator as a class variable, and get a new id on creation (I need to keep both the id and string for legacy reasons).

class Line(object):
    new_id = itertools.count(start=1).next
    lines = []

    def __init__(self, coord_string):
        self.coord_string = coord_string
        self.id = Line.new_id()
        Line.lines.append(self)

    @staticmethod
    def from_coord_string(coord_string):
        lines = [l.coord_string for l in Line.lines]
        try:
            ind = lines.index(path)
            return Line.links(ind)
        except ValueError:
            return Line(coord_string)

I'm also keeping track of all created objects in the a class variable. This lets me check to see if a Line has been created already, or get easy access to all of them later, i.e.:

all_lines = Line.lines
dump_to_db(all_lines)

What are the downsides to using class variables like this? Is there a better, or more efficient way to implement this?

Body:
I would do something like this:

from itertools import *
from multiprocessing import Lock

class Line(object):
    def __init__(self, ID, coord_string):
        self.id = ID
        self.coord_string = coord_string

class LineFactory(object):
    latestId = 0
    idLock = Lock()

    def __init__(self):
        self.lines = {} # Dict mapping coord_string to Line objects

    def make_new_id(self):
        with self.idLock:
            newId = self.latestId
            self.latestId += 1
        return newId

    def new_line(self, coord_string):
        if not coord_string in self.lines:
            self.lines[coord_string] = Line(self.make_new_id(), coord_string)

        return self.lines[coord_string]

    def get_all_lines(self):
        return self.lines.values


问:
Writing JavaScript according to SOLID
Have any one used the SOLID programming principle (or any of it's parts) while developing JavaScript?

I've just started up on reading on it but can't seem to find anyone that used it for JS. The only part I find easy to implement/use is the "Single responsibility principle".

What I'm looking for is articles or example where these principles are used. And are there any argument's why one shouldn't use some parts?

For example the "Interface segregation principle" says that "the notion that many client specific interfaces are better than one general purpose interface."

But from my knowledge there's no such thing as interfaces in JS (nice if it would be).

答:
Most of SOLID principals depend on abstraction, In other languages such as Java, we can do abstractions by using interfaces, And Javascript doesn't have interfaces, Does that means that we can't achieve SOLID principles in Javascript?
The answer is No.
This is a great article to clarify the things.

http://www.yusufaytas.com/achieving-abstraction-in-javascript/

In consequence, JavaScript is a weakly typed language and does not have classical support for abstraction. We have tried to achieve abstraction in JavaScript by defining interfaces and using them. Nevertheless, interfaces do not affect our code at all. They are nothing more than a way of documenting code for human beings. All the examples we have shown above would work exactly the same even if we completely remove the interfaces. However, it is about making roles explicit. This increases readability, understandability, and maintainability of the code.

In general, The main goal for SOLID principles is to make the code readable and easy to modify, Applying SOLID to your code is all about trying not to repeat yourself and make your code nicer and cleaner.

ContentLicense: CC BY-SA 2.5

Title: Writing JavaScript according to SOLID


问:
Read value from file, after 12 times ","
i have file, where i have separated values via "," - but it's not .csv extension.

I'm trying to get in C# sum from each row, which start from 0.

To this sum, should be taken always value after 12th of ","

```<code>0,P2CZ,1,0,400,400,802,802,18,18,1299,,5,248721,2487221,2
1,1,2487221,1,1_EG_3ST2_1/22,,0,460,18,0
0,,2,0,400,400,982,982,18,18,13999,,9,2321,248731,24878/121,24872021,,,,,,
1,1,2482021,1,1_EG_9_ST2_1/22,,0,460,18,0
1,3,2487821,1,1_EG_U9_ST2_1/22,,0,1042,18,0
1,4,248781,1,1_EG_U9_ST2_1/22,,0,1042,18,0
0,,3,0,2000,2000,80,80,18,18,14/0999,,1,,,,,,,,,,2000,80,1.3,,,,0,0,,,
</code>```

So in this style:

1st row, after 12th "," is value "5",

2nd row skipped, because of 1 on the beginning,

3rd row, after 12th "," is value "9",

4-6 rows skipped, because of 1 on the beginning,

7th row, after 12th "," is value "1"

So sum is 5 + 9 + 1 = 15.

I already input read lines with patch + data taken from label and + extension.

But what next ? How should i handle this ?

```<code>int count = File.ReadLines(patch + label97.Text + ".ext").Count(line => !line.All(char.IsWhiteSpace));
</code>```

答:
For starters, you should be doing this:

```<code>File.ReadLines(patch + label97.Text + ".ext")
    .Where(line => !line.StartsWith("1") // get lines that do not start with 1
    .ToArray();
</code>```

Then, using the loop statement of your choice:

```<code>var desiredPart = line.Split(new[] { ',' })[11]; // get whatever is at the twelveth position
int value = int.Parse(desiredPart);
</code>```

Of course, you need to check that the Split actually gives you 12 positions and whether it's a number or not.

Body:
i have file, where i have separated values via "," - but it's not .csv extension.

I'm trying to get in C# sum from each row, which start from 0.

To this sum, should be taken always value after 12th of ","

0,P2CZ,1,0,400,400,802,802,18,18,1299,,5,248721,2487221,2
1,1,2487221,1,1_EG_3ST2_1/22,,0,460,18,0
0,,2,0,400,400,982,982,18,18,13999,,9,2321,248731,24878/121,24872021,,,,,,
1,1,2482021,1,1_EG_9_ST2_1/22,,0,460,18,0
1,3,2487821,1,1_EG_U9_ST2_1/22,,0,1042,18,0
1,4,248781,1,1_EG_U9_ST2_1/22,,0,1042,18,0
0,,3,0,2000,2000,80,80,18,18,14/0999,,1,,,,,,,,,,2000,80,1.3,,,,0,0,,,

So in this style:

1st row, after 12th "," is value "5",

2nd row skipped, because of 1 on the beginning,

3rd row, after 12th "," is value "9",

4-6 rows skipped, because of 1 on the beginning,

7th row, after 12th "," is value "1"

So sum is 5 + 9 + 1 = 15.

I already input read lines with patch + data taken from label and + extension.

But what next ? How should i handle this ?

int count = File.ReadLines(patch + label97.Text + ".ext").Count(line => !line.All(char.IsWhiteSpace));

Body:
For starters, you should be doing this:

File.ReadLines(patch + label97.Text + ".ext")
    .Where(line => !line.StartsWith("1") // get lines that do not start with 1
    .ToArray();

Then, using the loop statement of your choice:

var desiredPart = line.Split(new[] { ',' })[11]; // get whatever is at the twelveth position
int value = int.Parse(desiredPart);

Of course, you need to check that the Split actually gives you 12 positions and whether it's a number or not.


问:
Error getting ArrayList Coordinates
I've been trying to solve this problem for a week, I've already tried the questions and I've already done some testing, but I still have not found the solution to this problem.

  Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get (int)' on a null object reference

It indicates this line:

```<code>Latitude = Double.parseDouble (location.get (i) .get ("Latitude"). ToString ());
</code>```

Print Error
Complete code:

```<code>public class TabFragment2 extends Fragment {

    private IFragmentToActivity mCallback;
    MapView mMapView;
    private GoogleMap googleMap;

    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.tab_fragment_2, container,
                false);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "https://192.168.0.1/geo.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                map.put("Tipo", c.getString("Tipo"));
                location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // *** Display Google Map
        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            String tipo = location.get(i).get("Tipo").toString();
            MarkerOptions marker = new MarkerOptions()
                    .position(new LatLng(Latitude, Longitude)).title(name);
            if(tipo.equals("CORTE")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }
            if(tipo.equals("RELIGACAO")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }
            if(tipo.equals("VISTORIA")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }
            googleMap.addMarker(marker);
        }

        return v;
    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 2: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    public void fragmentCommunication() {
        // mTextView1.setText("Hello from Tab Fragment 1");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}
</code>```

Code json:

```<code>[{"LocationID":"19637099","Latitude":" -5.080922","Longitude":"-42.816135","LocationName":"10032576","Tipo":"RELIGACAO"},{"LocationID":"19659563","Latitude":" -5.085750","Longitude":"-42.813892","LocationName":"518620","Tipo":"RELIGACAO"}]
</code>```

答:
Maybe you should use this condition before :

If(location.get (i) !=null)

Title: Error getting ArrayList Coordinates

Body:
I've been trying to solve this problem for a week, I've already tried the questions and I've already done some testing, but I still have not found the solution to this problem.

  Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get (int)' on a null object reference

It indicates this line:

Latitude = Double.parseDouble (location.get (i) .get ("Latitude"). ToString ());

Print Error
Complete code:

public class TabFragment2 extends Fragment {

    private IFragmentToActivity mCallback;
    MapView mMapView;
    private GoogleMap googleMap;

    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.tab_fragment_2, container,
                false);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "https://192.168.0.1/geo.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                map.put("Tipo", c.getString("Tipo"));
                location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // *** Display Google Map
        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            String tipo = location.get(i).get("Tipo").toString();
            MarkerOptions marker = new MarkerOptions()
                    .position(new LatLng(Latitude, Longitude)).title(name);
            if(tipo.equals("CORTE")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }
            if(tipo.equals("RELIGACAO")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }
            if(tipo.equals("VISTORIA")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }
            googleMap.addMarker(marker);
        }

        return v;
    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 2: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    public void fragmentCommunication() {
        // mTextView1.setText("Hello from Tab Fragment 1");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}

Code json:

[{"LocationID":"19637099","Latitude":" -5.080922","Longitude":"-42.816135","LocationName":"10032576","Tipo":"RELIGACAO"},{"LocationID":"19659563","Latitude":" -5.085750","Longitude":"-42.813892","LocationName":"518620","Tipo":"RELIGACAO"}]


问:
Video rotated after applying AVVideoComposition
After applying an AVVideoComposition to my AVPlayerItem, the filter I apply does work, but the video gets rotated in the AVPlayerLayer.

I know for a fact that the problem is not with the filtered frame because if I show the frame in a UIImageView, the frame is rendered 100% correctly.

The video shows correctly until I apply a videoComposition. Setting the videoGravity on the AVPlayerLayer does not help.

The video gets rotated 90º clockwise and gets stretched in the layer.

Essentially, the video is displayed perfectly in the AVPlayerLayer before the AVPlayerItem is fed through the AVMutableVideoComposition. Once that happens, the video is rotated -90º, and then scaled to fit the same dimensions as the video before filtering. This suggests to me that it does not realize that its transform is already correct, and so it is reapplying the transform on itself.

Why is this happening, and how can I fix it?

Here is some code:

```<code>private func filterVideo(with filter: Filter?) {
    if let player = player, let playerItem = player.currentItem {
        let composition = AVMutableComposition()
        let videoAssetTrack = playerItem.asset.tracks(withMediaType: .video).first
        let videoCompositionTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
        try? videoCompositionTrack?.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: playerItem.asset.duration), of: videoAssetTrack!, at: kCMTimeZero)
        videoCompositionTrack?.preferredTransform = videoAssetTrack!.preferredTransform

        let videoComposition = AVMutableVideoComposition(asset: composition, applyingCIFiltersWithHandler: { (request) in
            let filteredImage = <...>
            request.finish(with: filteredImage, context: nil)
        })

        playerItem.videoComposition = videoComposition
    }
}
</code>```

答:
If You are trying to play AVMutableCompostion You should set AVAssetTrack's preferredTransform to AVMutableCompositionTrack's preferredTransform.

```<code>let asset = AVAsset(url: url!)

let composition = AVMutableComposition()
let compositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)

let videoTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first

try? compositionTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), of: videoTrack!, at: kCMTimeZero)

compositionTrack.preferredTransform = (videoTrack?.preferredTransform)!

let playerItem = AVPlayerItem(asset: composition)
let filter = CIFilter(name: "CIColorInvert")
playerItem.videoComposition = AVVideoComposition(asset: composition, applyingCIFiltersWithHandler: { (request: AVAsynchronousCIImageFilteringRequest) in
            filter?.setValue(request.sourceImage, forKey: kCIInputImageKey)
            request.finish(with: (filter?.outputImage)!, context: nil)
        })
 .... the rest of code
</code>```

Body:
After applying an AVVideoComposition to my AVPlayerItem, the filter I apply does work, but the video gets rotated in the AVPlayerLayer.

I know for a fact that the problem is not with the filtered frame because if I show the frame in a UIImageView, the frame is rendered 100% correctly.

The video shows correctly until I apply a videoComposition. Setting the videoGravity on the AVPlayerLayer does not help.

The video gets rotated 90º clockwise and gets stretched in the layer.

Essentially, the video is displayed perfectly in the AVPlayerLayer before the AVPlayerItem is fed through the AVMutableVideoComposition. Once that happens, the video is rotated -90º, and then scaled to fit the same dimensions as the video before filtering. This suggests to me that it does not realize that its transform is already correct, and so it is reapplying the transform on itself.

Why is this happening, and how can I fix it?

Here is some code:

private func filterVideo(with filter: Filter?) {
    if let player = player, let playerItem = player.currentItem {
        let composition = AVMutableComposition()
        let videoAssetTrack = playerItem.asset.tracks(withMediaType: .video).first
        let videoCompositionTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
        try? videoCompositionTrack?.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: playerItem.asset.duration), of: videoAssetTrack!, at: kCMTimeZero)
        videoCompositionTrack?.preferredTransform = videoAssetTrack!.preferredTransform

        let videoComposition = AVMutableVideoComposition(asset: composition, applyingCIFiltersWithHandler: { (request) in
            let filteredImage = <...>
            request.finish(with: filteredImage, context: nil)
        })

        playerItem.videoComposition = videoComposition
    }
}

Body:
If You are trying to play AVMutableCompostion You should set AVAssetTrack's preferredTransform to AVMutableCompositionTrack's preferredTransform.

let asset = AVAsset(url: url!)

let composition = AVMutableComposition()
let compositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)

let videoTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first

try? compositionTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), of: videoTrack!, at: kCMTimeZero)

compositionTrack.preferredTransform = (videoTrack?.preferredTransform)!

let playerItem = AVPlayerItem(asset: composition)
let filter = CIFilter(name: "CIColorInvert")
playerItem.videoComposition = AVVideoComposition(asset: composition, applyingCIFiltersWithHandler: { (request: AVAsynchronousCIImageFilteringRequest) in
            filter?.setValue(request.sourceImage, forKey: kCIInputImageKey)
            request.finish(with: (filter?.outputImage)!, context: nil)
        })
 .... the rest of code


问:
PyQt5 multi thread
why the code doesn't work?? the video work file, when i tried to show a text in 2nd label it also  show up.but If i want to change the value continuously like current time in the setText() what can i do?   I am new in multi threading.</p>

```<code>import sys
import cv2
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
import datetime

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 Video'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        # create a label
        label = QLabel(self)
        label.move(280, 120)
        label.resize(640, 480)
        label1 = QLabel(self)
        label1.move(680, 820)
        th = Thread(self)
        th.changePixmap.connect(lambda p: label.setPixmap(p))
        th.changeLabel.connect(lambda n:label1.setText("A"))
        th.start()

class Thread(QThread):
    changePixmap = pyqtSignal(QPixmap)
    changeLabel = pyqtSignal(QLabel)

    def __init__(self, parent=None):
        QThread.__init__(self, parent=parent)

    def run(self):
        cap = cv2.VideoCapture(0)
        n=QLabel()
        while True:
            ret, frame = cap.read()
            rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888)
            convertToQtFormat = QPixmap.fromImage(convertToQtFormat)
            p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
            self.changePixmap.emit(p)
            now = datetime.datetime.now()
            sec = now.second
            try:
                self.changeLabel.emit(n)
            except Exception as e:
                print(str(e))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())
</code>```

答:
You should not send a new widget (QLabel) to the main view since that will be a new label, and not the original label, you should send the text that is of type str.

```<code>class Thread(QThread):
    changePixmap = pyqtSignal(QPixmap)
    changeLabel = pyqtSignal(str)

    def run(self):
        [...]
        now = datetime.datetime.now()
        sec = now.second
        self.changeLabel.emit(str(sec))
</code>```

And then connect it to the setText function:

```<code>th.changeLabel.connect(label1.setText)
</code>```

Complete code:

```<code>import sys
import cv2
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
import datetime

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 Video'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        # create a label
        # create a label
        label = QLabel(self)
        label.move(280, 120)
        label.resize(640, 480)
        label1 = QLabel(self)
        label1.move(580, 620)
        self.th = Thread(self)
        self.th.changePixmap.connect(label.setPixmap)
        self.th.changeLabel.connect(label1.setText)
        self.th.start()

    def closeEvent(self, event):
        self.th.stop()
        QWidget.closeEvent(self, event)

class Thread(QThread):
    changePixmap = pyqtSignal(QPixmap)
    changeLabel = pyqtSignal(str)

    def __init__(self, parent=None):
        QThread.__init__(self, parent=parent)
        self.isRunning = True

    def run(self):
        cap = cv2.VideoCapture(0)
        while self.isRunning:
            ret, frame = cap.read()
            rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888)
            convertToQtFormat = QPixmap.fromImage(convertToQtFormat)
            p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
            self.changePixmap.emit(p)
            now = datetime.datetime.now()
            sec = now.second
            self.changeLabel.emit(str(sec))

    def stop(self):
        self.isRunning = False
        self.quit()
        self.wait()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())
</code>```

Note: I have added stop method to be able to stop the thread and close properly, for this I also overwritten the closeEvent method. Another change, I moved label1 since my screen is not that big.

Title: PyQt5 multi thread

Body:
why the code doesn't work?? the video work file, when i tried to show a text in 2nd label it also  show up.but If i want to change the value continuously like current time in the setText() what can i do?   I am new in multi threading.

import sys
import cv2
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
import datetime

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 Video'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        # create a label
        label = QLabel(self)
        label.move(280, 120)
        label.resize(640, 480)
        label1 = QLabel(self)
        label1.move(680, 820)
        th = Thread(self)
        th.changePixmap.connect(lambda p: label.setPixmap(p))
        th.changeLabel.connect(lambda n:label1.setText("A"))
        th.start()

class Thread(QThread):
    changePixmap = pyqtSignal(QPixmap)
    changeLabel = pyqtSignal(QLabel)

    def __init__(self, parent=None):
        QThread.__init__(self, parent=parent)

    def run(self):
        cap = cv2.VideoCapture(0)
        n=QLabel()
        while True:
            ret, frame = cap.read()
            rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888)
            convertToQtFormat = QPixmap.fromImage(convertToQtFormat)
            p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
            self.changePixmap.emit(p)
            now = datetime.datetime.now()
            sec = now.second
            try:
                self.changeLabel.emit(n)
            except Exception as e:
                print(str(e))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())

Body:
You should not send a new widget (QLabel) to the main view since that will be a new label, and not the original label, you should send the text that is of type str.

class Thread(QThread):
    changePixmap = pyqtSignal(QPixmap)
    changeLabel = pyqtSignal(str)

    def run(self):
        [...]
        now = datetime.datetime.now()
        sec = now.second
        self.changeLabel.emit(str(sec))

And then connect it to the setText function:

th.changeLabel.connect(label1.setText)

Complete code:

import sys
import cv2
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
import datetime

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 Video'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.resize(1800, 1200)
        # create a label
        # create a label
        label = QLabel(self)
        label.move(280, 120)
        label.resize(640, 480)
        label1 = QLabel(self)
        label1.move(580, 620)
        self.th = Thread(self)
        self.th.changePixmap.connect(label.setPixmap)
        self.th.changeLabel.connect(label1.setText)
        self.th.start()

    def closeEvent(self, event):
        self.th.stop()
        QWidget.closeEvent(self, event)

class Thread(QThread):
    changePixmap = pyqtSignal(QPixmap)
    changeLabel = pyqtSignal(str)

    def __init__(self, parent=None):
        QThread.__init__(self, parent=parent)
        self.isRunning = True

    def run(self):
        cap = cv2.VideoCapture(0)
        while self.isRunning:
            ret, frame = cap.read()
            rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888)
            convertToQtFormat = QPixmap.fromImage(convertToQtFormat)
            p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
            self.changePixmap.emit(p)
            now = datetime.datetime.now()
            sec = now.second
            self.changeLabel.emit(str(sec))

    def stop(self):
        self.isRunning = False
        self.quit()
        self.wait()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())

Note: I have added stop method to be able to stop the thread and close properly, for this I also overwritten the closeEvent method. Another change, I moved label1 since my screen is not that big.


问:
ASP.NET: Why is FormsAuthenticationTicket null after authentication timeout?
I'm implementing an authentication timeout detection mechanism per a previous question and answer of mine here. I've implemented an HTTP module that uses the AuthenticateRequest event to run code to capture whether the authentication period has expired. The code to do this is below:

```<code>public class AuthenticationModule : IHttpModule
{
    #region IHttpModule Members
    void IHttpModule.Dispose() { }
    void IHttpModule.Init(HttpApplication application)
    {
        application.AuthenticateRequest += new EventHandler(this.context_AuthenticateRequest);
    }
    #endregion

    /// <summary>
    /// Inspect the auth request...
    /// </summary>
    /// <remarks>See "How To Implement IPrincipal" in MSDN</remarks>
    private void context_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication a = (HttpApplication)sender;
        HttpContext context = a.Context;

        // Extract the forms authentication cookie
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = context.Request.Cookies[cookieName]; // no longer a forms cookie in this array once timeout has expired

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            DateTime expirationTime = authTicket.Expiration;
            // check if previously authenticated session is now dead
            if (authTicket != null && authTicket.Expired)
            {
                // send them a Response indicating that they've expired.
            }
        }
    }
}
</code>```

The problem is that, once the authentication period has expired (I set it to 1 min to test), there is no longer a forms cookie (see comment in code). This means that the authentication cookie will be null, and I won't make it past the null check in my code. But there's a convenient "Expired" property for a FormsAuthenticationTicket that I feel like I should be checking to see if the period is expired. But how do I get that far if the cookie is no longer there? Is it reasonable to assume the authentication period has expired if there's no longer a forms cookie?

Any help would be appreciated on this.

答:
You might want to try something like this:

```<code>if (User != null)
        {
            FormsIdentity id = (FormsIdentity)User.Identity;
            FormsAuthenticationTicket ticket = id.Ticket;
            if (ticket.Expired)
            {
               //do something
            }
        }
</code>```

More info

Edit:

1: I see the User will be null. So using User.Identity is out of question.

2: How about trying the code you have in your original question in the BeginRequest event instead of AuthenticateRequest.

Body:
I'm implementing an authentication timeout detection mechanism per a previous question and answer of mine here. I've implemented an HTTP module that uses the AuthenticateRequest event to run code to capture whether the authentication period has expired. The code to do this is below:

public class AuthenticationModule : IHttpModule
{
    #region IHttpModule Members
    void IHttpModule.Dispose() { }
    void IHttpModule.Init(HttpApplication application)
    {
        application.AuthenticateRequest += new EventHandler(this.context_AuthenticateRequest);
    }
    #endregion

    ///
    /// Inspect the auth request...
    ///
    /// <remarks>See "How To Implement IPrincipal" in MSDN</remarks>
    private void context_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication a = (HttpApplication)sender;
        HttpContext context = a.Context;

        // Extract the forms authentication cookie
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = context.Request.Cookies[cookieName]; // no longer a forms cookie in this array once timeout has expired

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            DateTime expirationTime = authTicket.Expiration;
            // check if previously authenticated session is now dead
            if (authTicket != null && authTicket.Expired)
            {
                // send them a Response indicating that they've expired.
            }
        }
    }
}

The problem is that, once the authentication period has expired (I set it to 1 min to test), there is no longer a forms cookie (see comment in code). This means that the authentication cookie will be null, and I won't make it past the null check in my code. But there's a convenient "Expired" property for a FormsAuthenticationTicket that I feel like I should be checking to see if the period is expired. But how do I get that far if the cookie is no longer there? Is it reasonable to assume the authentication period has expired if there's no longer a forms cookie?

Any help would be appreciated on this.

Body:
You might want to try something like this:

if (User != null)
        {
            FormsIdentity id = (FormsIdentity)User.Identity;
            FormsAuthenticationTicket ticket = id.Ticket;
            if (ticket.Expired)
            {
               //do something
            }
        }

More info

Edit:

1: I see the User will be null. So using User.Identity is out of question.

2: How about trying the code you have in your original question in the BeginRequest event instead of AuthenticateRequest.


答:
If we assume file is in correct format and that on every 12th position you will find whole number, you can do it with just one line (quick and dirty)

```<code>var sum = File.ReadLines(patch + label97.Text + ".ext")
    .Where(l =>!l.StartsWith("1"))
    .Sum(l => int.Parse(l.Split(',')[11]);
</code>```

bear in mind that this will throw an exception if just one thing is not as expected (wrong filename, wrong position, string on 12th position instead of number etc).

Title: Read value from file, after 12 times ","

Body:
If we assume file is in correct format and that on every 12th position you will find whole number, you can do it with just one line (quick and dirty)

var sum = File.ReadLines(patch + label97.Text + ".ext")
    .Where(l =>!l.StartsWith("1"))
    .Sum(l => int.Parse(l.Split(',')[11]);

bear in mind that this will throw an exception if just one thing is not as expected (wrong filename, wrong position, string on 12th position instead of number etc).


问:
Push Notification due to an event in a HomeKit accessory
I want my app to be aware of events triggered by HomeKit accessories (HMAccessory). Such that, when my HomeKit powered motion detector detects motion, my app gets to know about this somehow (preferably via a push notification). The preinstalled Home app seems to have this feature. Is there a way I can get this done using the HomeKit framework?

The nearest I found was this on HMCharacteristic:

```<code>func enableNotification(Bool, completionHandler: (Error?) -> Void)
</code>```

But this doesn't result in a Push Notification and delivers updates via a delegate callback (and works only when app is foregrounded).

答: I have wanted to do this too but I don’t think there is a way to do it.</p>

Body:
I want my app to be aware of events triggered by HomeKit accessories (HMAccessory). Such that, when my HomeKit powered motion detector detects motion, my app gets to know about this somehow (preferably via a push notification). The preinstalled Home app seems to have this feature. Is there a way I can get this done using the HomeKit framework?

The nearest I found was this on HMCharacteristic:

func enableNotification(Bool, completionHandler: (Error?) -> Void)

But this doesn't result in a Push Notification and delivers updates via a delegate callback (and works only when app is foregrounded).


问:
Add Separator In Collapsed Nav Bootstrap
I am trying to add a separator in the collapsed nav when viewed on mobile. Ideally the nav would look exactly the same as it does not when not collapsed, but when collapsed would have a separator between "About" and "Log In".

Here is the code for the nav:

```<code><nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Company</a>
    </div>
    <div class="collapse navbar-collapse" id="main-navbar">
      <ul class="nav navbar-nav">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Log In</a></li>
        <li><a href="#">Sign Up</a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

JSFiddle

I have tried adding

 where I want the separator, but it does not show up:

```<code><nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Company</a>
    </div>
    <div class="collapse navbar-collapse" id="main-navbar">
      <ul class="nav navbar-nav">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li role="separator" class="divider"></li>
        <li><a href="#">Log In</a></li>
        <li><a href="#">Sign Up</a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

JSFiddle

How can I add a separator for the collapsed nav?

This separator would hopefully look very similar to that of a dropdown in a nav:

答:
If you don't want to touch css there is little hack for it :D.
Instead of

```<code><li role="separator" class="divider"></li>
</code>```

use this

```<code><form class="navbar-form navbar-left" style="padding:0px; border-top-width:0px;"></form>
</code>```

Bootstrap gives forms 1px borders on top and bottom when collapsed. You can use this and insert empty form which is invisible while expanded but with one border while collapsed.

Body:
I am trying to add a separator in the collapsed nav when viewed on mobile. Ideally the nav would look exactly the same as it does not when not collapsed, but when collapsed would have a separator between "About" and "Log In".

Here is the code for the nav:

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navbar" aria-expanded="false">
        Toggle navigation

      </button>
      Company

Home

About

Log In

Sign Up

JSFiddle

I have tried adding

 where I want the separator, but it does not show up:

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navbar" aria-expanded="false">
        Toggle navigation

      </button>
      Company

Home

About

Log In

Sign Up

JSFiddle

How can I add a separator for the collapsed nav?

This separator would hopefully look very similar to that of a dropdown in a nav:

Body:
If you don't want to touch css there is little hack for it :D.
Instead of

<li role="separator" class="divider"></li>

use this

<form class="navbar-form navbar-left" style="padding:0px; border-top-width:0px;"></form>

Bootstrap gives forms 1px borders on top and bottom when collapsed. You can use this and insert empty form which is invisible while expanded but with one border while collapsed.


问:
Ionic add has-header and has-tabs-top automatically into <ion-content>?
I'm creating a project using Ionic 1.3.2 and building to Android 5.1.1. The problem is after buiding the classes has-header and has-tabs-top are added into <ion-content> automatically and because this a space is beeing showing. I don't know why this happens and I don't know how to remove these classes or if there's another solution.

How could I solve this ?

View

```<code><ion-view>

  <div class="item item-input-inset">
      <label class="item-input-wrapper">
        <i class="icon ion-ios-search placeholder-icon"></i>
        <input type="text" ng-model="pesquisar" placeholder="O que procura ?">
      </label>
  </div>

  <ion-content>

    <ion-list>
        <ion-item class="item item-thumbnail-left"
                  ng-repeat="empresa in empresas | filter:pesquisar"
                      ng-click="getEmpresa({{empresa.id}})" >

              <img ng-src='{{empresa.imagem}}'>
              <h2 class="customTitle">{{empresa.razaoSocial}}</h2>

              <div style="margin-bottom:20px">
                <ul>
                  <li ng-repeat="ce in empresa.categorias | filter:pesquisar"
                      class="customListInline customCategoriaEmpresa">{{ce.descricao}}</li>
                </ul>
              </div>

              <div class="row row-bottom">
                  <div class="col col-25"><a href="#"><i class="icon ion-thumbsup icon-24px"></i></a></div>
                  <div class="col col-25"><a href="#"><i class="icon ion-chatbox icon-24px"></i></a></div>
                  <div class="col col-25">
                      <a href="tel:{{item.telefone}}"><i class="icon ion-ios-telephone icon-24px"></i></a>
                  </div>
              </div>

        </ion-item>
        <ion-infinite-scroll on-infinite="loadMore();" distance="1%" ng-if='!moreData'></ion-infinite-scroll>
   </ion-list>

  </ion-content>
</ion-view>
</code>```

答:
As per @MikeT's comment, but i think you want:</p>

```<code><ion-content style="top:0px">
</code>```

Body:
I'm creating a project using Ionic 1.3.2 and building to Android 5.1.1. The problem is after buiding the classes has-header and has-tabs-top are added into <ion-content> automatically and because this a space is beeing showing. I don't know why this happens and I don't know how to remove these classes or if there's another solution.

How could I solve this ?

View

<ion-view>

        <input type="text" ng-model="pesquisar" placeholder="O que procura ?">

  <ion-content>

    <ion-list>
        <ion-item class="item item-thumbnail-left"
                  ng-repeat="empresa in empresas | filter:pesquisar"
                      ng-click="getEmpresa({{empresa.id}})" >

{{empresa.razaoSocial}}

{{ce.descricao}}

        </ion-item>
        <ion-infinite-scroll on-infinite="loadMore();" distance="1%" ng-if='!moreData'></ion-infinite-scroll>
   </ion-list>

  </ion-content>
</ion-view>

Body:
As per @MikeT's comment, but i think you want:

<ion-content style="top:0px">


问:
Push a subroutine with argument into a stack in Perl
I would like to push a subroutine with arguments into a stack, but I can't figure out the syntax. Consider a working example with no arguments:

#!/usr/bin/perl -w
use strict;
use warnings;

sub hi    { print "hi\n";    }
sub hello { print "hello\n"; }
sub world { print "world\n"; }

my @stack;
push (@stack, \&hi   );
push (@stack, \&hello);
push (@stack, \&world);

while (@stack) {
    my $proc = pop @stack;
    $proc->();
}
```

<p>when I run the code:</p>

<pre class="lang-sh prettyprint-override"><code>% ./pop-proc.pl
world
hello
hi
</code>```

Now my question is, what if the subroutine looked like this:

sub mysub
{
    chomp( my( $arg ) = @_ );
    print "$arg\n";
}
```

<p>and I'd like to push subroutines with arguments, such as:</p>

<pre class="lang-perl prettyprint-override"><code>mysub("hello");
mysub("world");
</code>```

your input is highly appreciated.

答:
I might do something like this where I create a tuple to hold the code reference and its arguments:

```<code>use v5.24;

sub hi    { print "Hi @_\n";    }
sub hello { print "Hello @_\n"; }

my @stack;
push @stack, [ \&hi,    'Perl'     ];
push @stack, [ \&hello, 'Amelia'   ];
push @stack, [ \&hello, $ENV{USER} ];

while (@stack) {
    my( $proc, @args ) = pop( @stack )->@*;
    $proc->( @args );
}
</code>```

I use the v5.24 postfix dereference there, but that's because I can't help myself. This works too but now I think it's very ugly:

```<code>    my( $proc, @args ) = @{ pop( @stack ) };
</code>```

Body:
I would like to push a subroutine with arguments into a stack, but I can't figure out the syntax. Consider a working example with no arguments:

#!/usr/bin/perl -w
use strict;
use warnings;

sub hi    { print "hi\n";    }
sub hello { print "hello\n"; }
sub world { print "world\n"; }

my @stack;
push (@stack, \&hi   );
push (@stack, \&hello);
push (@stack, \&world);

while (@stack) {
    my $proc = pop @stack;
    $proc->();
}

when I run the code:

% ./pop-proc.pl
world
hello
hi

Now my question is, what if the subroutine looked like this:

sub mysub
{
    chomp( my( $arg ) = @_ );
    print "$arg\n";
}

and I'd like to push subroutines with arguments, such as:

mysub("hello");
mysub("world");

your input is highly appreciated.

Body:
I might do something like this where I create a tuple to hold the code reference and its arguments:

use v5.24;

sub hi    { print "Hi @_\n";    }
sub hello { print "Hello @_\n"; }

my @stack;
push @stack, [ \&hi,    'Perl'     ];
push @stack, [ \&hello, 'Amelia'   ];
push @stack, [ \&hello, $ENV{USER} ];

while (@stack) {
    my( $proc, @args ) = pop( @stack )->@*;
    $proc->( @args );
}

I use the v5.24 postfix dereference there, but that's because I can't help myself. This works too but now I think it's very ugly:

    my( $proc, @args ) = @{ pop( @stack ) };


问:
yahoo_finance python api `get_historical` not working
I would like to gather historical stock prices using the yahoo_finance get_historical feature.  The test below is fine, but test2 is printed as an empty array.  Any ideas?

```<code>from yahoo_finance import Share
test = (Share('AAPL').get_open())
print test
test2 = (Share('AAPL').get_historical('2017-01-30', '2017-02-15'))
print test2
</code>```

答:
Yes, it seems that Yahoo finance recently [shut down historical_data of their API (link)

I have found this SO topic talking about it.

And this Quora question about what to use after Yahoo finance

Body:
I would like to gather historical stock prices using the yahoo_finance get_historical feature.  The test below is fine, but test2 is printed as an empty array.  Any ideas?

from yahoo_finance import Share
test = (Share('AAPL').get_open())
print test
test2 = (Share('AAPL').get_historical('2017-01-30', '2017-02-15'))
print test2


问:
Is it safe to source system-wide environment variables in apache envvars?
I am trying to set an environment variable on Linux which should be available in shell as well as Apache.

I added the variable to /etc/environment, so the file looks something like this:

```<code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
MY_VAR="foo"
</code>```

To have MY_VAR available in apache, this is what I added in /etc/apache2/envvars:

```<code>. /etc/environment
export MY_VAR=$MY_VAR
</code>```

After doing a lot of research, this is the only way I was able to get the same environment variable work system-wide and in Apache without having to declare them twice.

Are there any security concerns with this approach?

答:
I was able to solve my own problem. I removed MY_VAR from /etc/environment and created a separate file /etc/profile.d/apache.sh which looks like this:

```<code>export MY_VAR="foo"
</code>```

Then I sourced this file in /etc/apache2/envvars like so:

```<code>. /etc/profile.d/apache.sh
</code>```

Any variable set in apache.sh is available system-wide as well as in Apache

Because apache.sh is a script, unlike /etc/environment, the variables do not have to be "export"ed again in envvars

There is no security risk because no unwanted variables are passed magically to Apache

Whatever variables you want to be available system-wide as well as Apache, you add it to apache.sh and if you want it only in Apache then you add it in envvars

Body:
I am trying to set an environment variable on Linux which should be available in shell as well as Apache.

I added the variable to /etc/environment, so the file looks something like this:

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
MY_VAR="foo"

To have MY_VAR available in apache, this is what I added in /etc/apache2/envvars:

. /etc/environment
export MY_VAR=$MY_VAR

After doing a lot of research, this is the only way I was able to get the same environment variable work system-wide and in Apache without having to declare them twice.

Are there any security concerns with this approach?

Body:
I was able to solve my own problem. I removed MY_VAR from /etc/environment and created a separate file /etc/profile.d/apache.sh which looks like this:

export MY_VAR="foo"

Then I sourced this file in /etc/apache2/envvars like so:

. /etc/profile.d/apache.sh

Any variable set in apache.sh is available system-wide as well as in Apache

Because apache.sh is a script, unlike /etc/environment, the variables do not have to be "export"ed again in envvars

There is no security risk because no unwanted variables are passed magically to Apache

Whatever variables you want to be available system-wide as well as Apache, you add it to apache.sh and if you want it only in Apache then you add it in envvars


问:
Are tf.layers.dense() and tf.contrib.layers.fully_connected() interchangeable?
I am used to using tf.contrib.layers.fully_connected to build a fully connected layer. Recently I ran into tf.layers.dense apparently used where the first functioned could be used. Are the interchangeable, producing the same output?</p>

答:
They are essentially the same, the later calling the former.

However tf.contrib.fully_connected adds a few functionalities on top of dense, in particular the possibility to pass a normalization and an activation in the parameters, à la Keras. As noted by @wordforthewise, mind that the later defaults to tf.nn.relu.

More generally, the TF API proposes (and mixes somewhat confusingly) low- and hi-level APIs; more on that here.


问:
How to make BufferedWriter not overwrite a text file
I am currently making an application where the user can add multiple accounts. The login information is being stored in a text file. I need a way for the user to add a new account without BufferedWriter overwriting the other accounts' information. Any suggestions? </p>

```<code>package mainFiles.fileManagers;

import java.io.*;

public class NewTXT {

 public static void nFile( String a , String b ) throws IOException {

     File f = new File("mainFiles\\storage\\accountinfo.txt");
     FileWriter writer = new  FileWriter("mainFiles\\storage\\accountinfo.txt");
     BufferedWriter bWriter = new BufferedWriter(writer);

     f.createNewFile();
     f.canWrite();
     bWriter.newLine();
     bWriter.write(a + "?" + b );
     bWriter.newLine();
     bWriter.close();

 }

}
</code>```

答:
There is nothing wrong with the BufferedWriter. You have to construct the FileWriter in append mode:

FileWriter writer = new  FileWriter("mainFiles\\storage\\accountinfo.txt", true);

Check the FileWriter documentation:
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

Body:
I am currently making an application where the user can add multiple accounts. The login information is being stored in a text file. I need a way for the user to add a new account without BufferedWriter overwriting the other accounts' information. Any suggestions?

package mainFiles.fileManagers;

import java.io.*;

public class NewTXT {

 public static void nFile( String a , String b ) throws IOException {

     File f = new File("mainFiles\\storage\\accountinfo.txt");
     FileWriter writer = new  FileWriter("mainFiles\\storage\\accountinfo.txt");
     BufferedWriter bWriter = new BufferedWriter(writer);

     f.createNewFile();
     f.canWrite();
     bWriter.newLine();
     bWriter.write(a + "?" + b );
     bWriter.newLine();
     bWriter.close();

 }

}


问:
Merging two various MySQL tables, order and limit it for a combined result
I need to combine various MySQL tables for a common result. The needed and expected result is a list of last X comments on a website but the tables are individuals, like: news_comments, pages_comments, etc. Individually, this tables has JOINS to users database.

The structure of 3 of this comments table are:

```<code>news_comments, pages_comments, other_comments
id int ai
id_new/id_page/id_other int
id_user int
comment text
created int (timestamp)
</code>```

The table for users:

```<code>id int ai
login int
password varchar
...
</code>```

I don't complete this last because we only need id and login.

The normal use of this queries (individuals) are:

```<code>SELECT users.id, users.login, news_comments.*, news_comments.id AS id_comment
FROM users, news_comments
WHERE users.id=news_comments.id_user AND news_comments.id_new=$id
ORDER BY created DESC
LIMIT $offset,$rows
</code>```

And works fine!

But in the backend i want to have a list of all the comments on the website to moderate and control it. I need to combine all the comments tables, order it by created desc and limit the result to make a pagination.

I use MySQL and PHP, so if I need to use PHP there is no problem with that.

How I can do it?

Thanks in advance!

答:
```<code>SELECT  *
FROM    (
        SELECT  *
        FROM    (
                SELECT  *
                FROM    news_comments
                WHERE   id_new = $id
                ORDER BY
                        created DESC
                LIMIT $rows
                ) q
        UNION ALL
        SELECT  *
        FROM    (
                SELECT  *
                FROM    pages_comments
                WHERE   id_new = $id
                ORDER BY
                        created DESC
                LIMIT $rows
                ) q
        UNION ALL
        SELECT  *
        FROM    (
                SELECT  *
                FROM    other_comments
                WHERE   id_new = $id
                ORDER BY
                        created DESC
                LIMIT $rows
                ) q
        ) q
JOIN    users u
ON      u.id = q.id_user
ORDER BY
        created DESC
LIMIT   $offset, $rows
</code>```

Note that limits are applied to each of the inner queries as well so that they could benefit from the indexes.

Create the following indexes:

```<code>CREATE INDEX ix_newscomments_new_created ON news_comments (id_new, created)
CREATE INDEX ix_pagescomments_new_created ON pages_comments (id_new, created)
CREATE INDEX ix_othercomments_new_created ON other_comments (id_new, created)
</code>```

for this to work fast

Body:
I need to combine various MySQL tables for a common result. The needed and expected result is a list of last X comments on a website but the tables are individuals, like: news_comments, pages_comments, etc. Individually, this tables has JOINS to users database.

The structure of 3 of this comments table are:

news_comments, pages_comments, other_comments
id int ai
id_new/id_page/id_other int
id_user int
comment text
created int (timestamp)

The table for users:

id int ai
login int
password varchar
...

I don't complete this last because we only need id and login.

The normal use of this queries (individuals) are:

SELECT users.id, users.login, news_comments.*, news_comments.id AS id_comment
FROM users, news_comments
WHERE users.id=news_comments.id_user AND news_comments.id_new=$id
ORDER BY created DESC
LIMIT $offset,$rows

And works fine!

But in the backend i want to have a list of all the comments on the website to moderate and control it. I need to combine all the comments tables, order it by created desc and limit the result to make a pagination.

I use MySQL and PHP, so if I need to use PHP there is no problem with that.

How I can do it?

Thanks in advance!

Body:
SELECT  *
FROM    (
        SELECT  *
        FROM    (
                SELECT  *
                FROM    news_comments
                WHERE   id_new = $id
                ORDER BY
                        created DESC
                LIMIT $rows
                ) q
        UNION ALL
        SELECT  *
        FROM    (
                SELECT  *
                FROM    pages_comments
                WHERE   id_new = $id
                ORDER BY
                        created DESC
                LIMIT $rows
                ) q
        UNION ALL
        SELECT  *
        FROM    (
                SELECT  *
                FROM    other_comments
                WHERE   id_new = $id
                ORDER BY
                        created DESC
                LIMIT $rows
                ) q
        ) q
JOIN    users u
ON      u.id = q.id_user
ORDER BY
        created DESC
LIMIT   $offset, $rows

Note that limits are applied to each of the inner queries as well so that they could benefit from the indexes.

Create the following indexes:

CREATE INDEX ix_newscomments_new_created ON news_comments (id_new, created)
CREATE INDEX ix_pagescomments_new_created ON pages_comments (id_new, created)
CREATE INDEX ix_othercomments_new_created ON other_comments (id_new, created)

for this to work fast


问:
How do I delete the current git remote add origin link I typed?
A word is missspelled and I noticed when I tried to push something to my GitHub. Im trying to make a markdown file and push it to my GitHub but I keep getting errors. The username is right and so is the email. I entered git pull remote master and then I saw the misspelling in the error. How do I fix it or delete it and enter a new one?</p>

答:
I want to change my remote origin. GitHub is spelled wrong

Simply type the right origin url with:

```<code>git remote set-url origin https://github.com/<yourName>/<yourRepo>.git
</code>```

That avoid having to edit manually the .git/config (local config of the Git repo)

Body:
I want to change my remote origin. GitHub is spelled wrong

Simply type the right origin url with:

git remote set-url origin https://github.com/<yourName>/<yourRepo>.git

That avoid having to edit manually the .git/config (local config of the Git repo)


问:
Custom date format in Excel VBA
I am trying to use the custom format to change the date from English to French. The custom code in regular Excel is [$-C0C]d mmmm;@ and yields the output as 20 juillet.

When using the following VBA code:

Format(Range("B2"), "[$-C0C]d mmmm;@")

The output is 20 July

[$-C0C] is supposed to be the code for French Canada

答:
This did it for me:</p>

```<code>Sheet1.Range("B2").NumberFormat = "[$-C0C]d mmmm;@"
</code>```

Title: Custom date format in Excel VBA

Body:
This did it for me:

Sheet1.Range("B2").NumberFormat = "[$-C0C]d mmmm;@"


问:
How can I rearrange an array in MATLAB by a specific rule?
Suppose that I have this array:

```<code>a = [1,2,3,4,5];
</code>```

The output should be something like this:

```<code>1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4
</code>```

how Can I do this? This function should be valid for different lengths of a.

Body:
Suppose that I have this array:

a = [1,2,3,4,5];

The output should be something like this:

1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4

how Can I do this? This function should be valid for different lengths of a.

Body:
And another way:

n = numel(a)-1;
b = [a(:) flipud(reshape(ndgrid(a,1:n).',[],n))];

b =

     1     2     3     4     5
     2     1     3     4     5
     3     1     2     4     5
     4     1     2     3     5
     5     1     2     3     4


问:
Reference collapsing and const
Consider this program:

```<code>template<typename T>
struct Foo
{
    void foo(const T&) {}
    void foo(T&) {}
};

int main()
{
    Foo<double&> f;
    double d = 3.14;
    f.foo(d);   //complains that foo() is ambigous
}
</code>```

In the above, if Foo is instantiated as Foo<double> , then things are fine, but if it is instantiated as Foo<double&>, then the call to foo becomes ambiguous. Is ref collapsing at play here when deducing the param types for foo and if so why is constness being ignored?

答:
Lets see what happens if we try to instatiate the Foo class template:

```<code>template<typename T>
struct Foo {
  void foo(T const&) {}
  void foo(T&) {}
};
</code>```

with template parameter double&. Substituting T with double& and according to reference collapsing rules you would get:

```<code>struct Foo {
  void foo(double& const) {}
  void foo(double&) {}
};
</code>```

Since references are inherently constant double& const is equivalent to double&. Thus, you get the following instatiation:

```<code>struct Foo {
  void foo(double&) {}
  void foo(double&) {}
};
</code>```

Here comes the compiler shouting "Dude you can't overload foo with the same signature".

A more consise error is given by CLANG:

error: multiple overloads of 'foo' instantiate to the same signature
  'void (double &&)'   void foo(T&) { }

Live Demo

Title: Reference collapsing and const

Body:
Consider this program:

template<typename T>
struct Foo
{
    void foo(const T&) {}
    void foo(T&) {}
};

int main()
{
    Foo<double&> f;
    double d = 3.14;
    f.foo(d);   //complains that foo() is ambigous
}

In the above, if Foo is instantiated as Foo<double> , then things are fine, but if it is instantiated as Foo<double&>, then the call to foo becomes ambiguous. Is ref collapsing at play here when deducing the param types for foo and if so why is constness being ignored?

Body:
Lets see what happens if we try to instatiate the Foo class template:

template<typename T>
struct Foo {
  void foo(T const&) {}
  void foo(T&) {}
};

with template parameter double&. Substituting T with double& and according to reference collapsing rules you would get:

struct Foo {
  void foo(double& const) {}
  void foo(double&) {}
};

Since references are inherently constant double& const is equivalent to double&. Thus, you get the following instatiation:

struct Foo {
  void foo(double&) {}
  void foo(double&) {}
};

Here comes the compiler shouting "Dude you can't overload foo with the same signature".

A more consise error is given by CLANG:

error: multiple overloads of 'foo' instantiate to the same signature
  'void (double &&)'   void foo(T&) { }

Live Demo


问:
Django: ID Null after Save
I Got this Models in models.py:

```<code>class Boats(models.Model):
    id = models.BigIntegerField(primary_key=True)
    created = models.DateTimeField(default=timezone.now, blank=True)
    name = models.CharField(max_length=30)

    class Meta:
       managed = True
       db_table = 'boats'
       ordering = ['name']

class Clients(models.Model):
    id = models.BigIntegerField(primary_key=True)
    created = models.DateTimeField(default=timezone.now, blank=True)
    code = models.CharField(max_length=100)

    class Meta:
       managed = True
       db_table = 'clients'
       ordering = ['name']
</code>```

==========================

In the views.py; my function do it like that:

```<code>  f = NewBoatForm(request.POST)
  if f.is_valid():
        nBoat = f.save()
        print 'ID:'+str(nBoat.id)
        cBoat = ClientsBoats()
        cBoat.client = client
        cBoat.boat = nBoat
        cBoat.save()
</code>```

But django fails with this error:

```<code>       ValueError: save() prohibited to prevent data loss due to unsaved related object 'boat'.
</code>```

I print the ID but it's Null. Can someOne help me.

答:
You've overridden the primary key field, id, to be something other than an AutoField. Don't do that.

Normally you wouldn't define it at all, and let Django do it automatically. If you are really really sure that a standard integer field is not big enough, you can use BigAutoField. But I doubt you will have more than 2147483647 boats in your database.

Title: Django: ID Null after Save

Body:
I Got this Models in models.py:

class Boats(models.Model):
    id = models.BigIntegerField(primary_key=True)
    created = models.DateTimeField(default=timezone.now, blank=True)
    name = models.CharField(max_length=30)

    class Meta:
       managed = True
       db_table = 'boats'
       ordering = ['name']

class Clients(models.Model):
    id = models.BigIntegerField(primary_key=True)
    created = models.DateTimeField(default=timezone.now, blank=True)
    code = models.CharField(max_length=100)

    class Meta:
       managed = True
       db_table = 'clients'
       ordering = ['name']

==========================

In the views.py; my function do it like that:

  f = NewBoatForm(request.POST)
  if f.is_valid():
        nBoat = f.save()
        print 'ID:'+str(nBoat.id)
        cBoat = ClientsBoats()
        cBoat.client = client
        cBoat.boat = nBoat
        cBoat.save()

But django fails with this error:

       ValueError: save() prohibited to prevent data loss due to unsaved related object 'boat'.

I print the ID but it's Null. Can someOne help me.


问:
Javascript reassign variable and not break reference
Assuming the following:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

let newvar = window.somevar;

// Is it possible to keep the window.somevar reference so that is always uses the setters/getters?
// obviously this actually reassigns newvar instead of using the window.somevar setter.
newvar = { hi: 'senica' }

// These are different now.
console.log(newvar, window.somevar);

// Object.assign won't work because getters/setters are not enumerable.

// A proxy would work, but that's not my question.```

Not super important...was just curious.

Thanks!

答:
Like I said in the comment, can be done with Object.defineProperty, just not with =:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

Object.defineProperty(window, 'newvar', Object.getOwnPropertyDescriptor(window, 'somevar'))

newvar = { hi: 'senica' }

console.log(newvar === window.somevar);```

Body:
Assuming the following:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

let newvar = window.somevar;

// Is it possible to keep the window.somevar reference so that is always uses the setters/getters?
// obviously this actually reassigns newvar instead of using the window.somevar setter.
newvar = { hi: 'senica' }

// These are different now.
console.log(newvar, window.somevar);

// Object.assign won't work because getters/setters are not enumerable.

// A proxy would work, but that's not my question.

Not super important...was just curious.

Thanks!


问:
Modal Window with MVVM pattern
I am trying to make modal dialog window for let user know some error messages, or let user edit some values.
I am using MVVM pattern, so my mainwindow has some control part and workspace part. In workspace part, i am opening viewmodels tight with datatemplate to views (defined as usercontrols). From one of these views i want to open modal dialog window. I was following this answer Error window show modal in MVVM WPF. As described in that answer, i have implemented the DialogClass in an InvoiceViewModel. But i have problem with showing the content of the modal window. If I set the content of the window to ViewModel class, output is simple text with namespace path to that ViewModel. (ViewModel attached to the View with datatemplate.) If I set content to the View - it is working - view is showed but, i am disobeing MVVM pattern (opening View from ViewModel as ViewModel has no reference to View).

```<code>        ErrorViewModel newErrorViewModel = new ErrorViewModel();
        ErrorView newErrorView = new ErrorView();
        DialogWindow dialogWindow = new DialogWindow();
        //Not Working
        //dialogWindow.Content = newErrorViewModel;

        //Working But, breaking MVVM
        dialogWindow.Content = newErrorView;
        dialogWindow.ShowDialog();
</code>```

In ErrorView.xaml i have attached ErrorViewModel like this.

```<code><DataTemplate DataType="{x:Type vm:ErrorViewModel}">
    <vw:ErrorView/>
</DataTemplate>
</code>```

What am i doing wrong?

Thanks.

答: You are assigning newErrorView to the dialog's content, instead of newErrorViewModel</p>

Title: Modal Window with MVVM pattern

Body:
I am trying to make modal dialog window for let user know some error messages, or let user edit some values.
I am using MVVM pattern, so my mainwindow has some control part and workspace part. In workspace part, i am opening viewmodels tight with datatemplate to views (defined as usercontrols). From one of these views i want to open modal dialog window. I was following this answer Error window show modal in MVVM WPF. As described in that answer, i have implemented the DialogClass in an InvoiceViewModel. But i have problem with showing the content of the modal window. If I set the content of the window to ViewModel class, output is simple text with namespace path to that ViewModel. (ViewModel attached to the View with datatemplate.) If I set content to the View - it is working - view is showed but, i am disobeing MVVM pattern (opening View from ViewModel as ViewModel has no reference to View).

        ErrorViewModel newErrorViewModel = new ErrorViewModel();
        ErrorView newErrorView = new ErrorView();
        DialogWindow dialogWindow = new DialogWindow();
        //Not Working
        //dialogWindow.Content = newErrorViewModel;

        //Working But, breaking MVVM
        dialogWindow.Content = newErrorView;
        dialogWindow.ShowDialog();

In ErrorView.xaml i have attached ErrorViewModel like this.

<DataTemplate DataType="{x:Type vm:ErrorViewModel}">
    <vw:ErrorView/>
</DataTemplate>

What am i doing wrong?

Thanks.