问:
GridControl display values in new line
I have a  class wherein I am storing all the values of FileALine and FileBLine properties into a list called Changes
The code for the properties is as shown below.

```<code>public class Result
{
    public Result()
    {
        this.Changes = new List<Difference>();
    }

    public IList<Difference> Changes { get; set; }
}

public class Differences
{
    public int LineNumber { get; set; }

    public string FileALine { get; set; }

    public string FileBLine { get; set; }
}
</code>```

I am calling the Changes list from a form to populate a Synfusion GridControl. It has two Columns DataRow and Details. Right now I am only able to fill in either FileAline values or FileBLine values into the second column.

I am unable to figure out how to display both FileAline values on one line and FileBLine values in the next line as shown in the image below.

```<code>public partial class Form: Form
{
    private void DisplayValues(Result result)
    {
        if (result != null && result.Changes.Count > 0)
        {
            var differences = result.Changes;
            this.detailsGridControl.RowCount = differences.Count;
            this.detailsGridControl.ColCount = 2;

            for (var i = 0; i < differences.Count; i++)
            {
                var detailsA = differences[i];
                var row = i + 1;
                this.detailsGridControl[row, (int)FormColumns.DataRow].Text = detailsA.LineNumber.ToString();
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileALine;
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileBLine;
            }
        }
    }
}
</code>```

So the output must be something like this.

Any suggestions on how to achieve this?

Thanks in advance!

答:
Please try the below suggestions.

Suggestion 1

In the DisplayValues() method of Form, you are trying to set the FileALine and FileBLine for the same cell. So, the CellValue will be overridden and returns only FileBLine only. In order to set the CellValue from list, the PopulateValues() method can be used. Refer to the below code and sample,

```<code>Dim difference As New List(Of Differences)()
difference.Add(New Differences() With {.LineNumber = 1, .FileALine = `"FileLineA", .FileBLine = "FileLineB"})
difference.Add(New Differences() With {.LineNumber = 2, .FileALine = "FileLineB", .FileBLine = "FileLineA"})
Dim r As New Result()
For Each d As Differences In difference
r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileALine})
r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileBLine})
Next d
Me.gridControl1.PopulateHeaders(GridRangeInfo.Cells(0, 1, gridControl1.RowCount, gridControl1.ColCount), r.Changes)
Me.gridControl1.PopulateValues(GridRangeInfo.Cells(1, 1, gridControl1.RowCount, gridControl1.ColCount), r.Changes)
Me.gridControl1.Refresh()
</code>```

Suggestion 2

You can also set the CellValue by Text property of GridStyleInfo class. refer to the sample,

```<code>Dim difference As New List(Of Differences)()
difference.Add(New Differences() With {.LineNumber = 1, .FileALine = "FileLineA", .FileBLine = "FileLineB"})
difference.Add(New Differences() With {.LineNumber = 2, .FileALine = "FileLineB", .FileBLine = "FileLineA"})
Dim r As New Result()
For Each d As Differences In difference
r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileALine})
 r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileBLine})
Next d
DisplayValues(r)
Private Sub DisplayValues(ByVal result As Result)
If result IsNot Nothing AndAlso result.Changes.Count > 0 Then
   Dim differences = result.Changes
   Me.gridControl1.RowCount = result.Changes.Count
   Me.gridControl1.ColCount = 2
   For i = 0 To differences.Count - 1
      Dim detailsA = TryCast(differences(i), Data)
      Dim row = i + 1
      Me.gridControl1(row, 1).Text = detailsA.DataRow.ToString()
     'To set FileALine or FileBLine for column 2
      Me.gridControl1(row, 2).Text = detailsA.Details
      Next i
   End If
End Sub
</code>```

Note: you can create an object for the list to populate data as your convenient.

Title: GridControl display values in new line

Body:
I have a  class wherein I am storing all the values of FileALine and FileBLine properties into a list called Changes
The code for the properties is as shown below.

public class Result
{
    public Result()
    {
        this.Changes = new List<Difference>();
    }

    public IList<Difference> Changes { get; set; }
}

public class Differences
{
    public int LineNumber { get; set; }

    public string FileALine { get; set; }

    public string FileBLine { get; set; }
}

I am calling the Changes list from a form to populate a Synfusion GridControl. It has two Columns DataRow and Details. Right now I am only able to fill in either FileAline values or FileBLine values into the second column.

I am unable to figure out how to display both FileAline values on one line and FileBLine values in the next line as shown in the image below.

public partial class Form: Form
{
    private void DisplayValues(Result result)
    {
        if (result != null && result.Changes.Count > 0)
        {
            var differences = result.Changes;
            this.detailsGridControl.RowCount = differences.Count;
            this.detailsGridControl.ColCount = 2;

            for (var i = 0; i < differences.Count; i++)
            {
                var detailsA = differences[i];
                var row = i + 1;
                this.detailsGridControl[row, (int)FormColumns.DataRow].Text = detailsA.LineNumber.ToString();
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileALine;
                this.detailsGridControl[row, (int)FormColumns.Details].Text = detailsA.FileBLine;
            }
        }
    }
}

So the output must be something like this.

Any suggestions on how to achieve this?

Thanks in advance!

Body:
Please try the below suggestions.

Suggestion 1

In the DisplayValues() method of Form, you are trying to set the FileALine and FileBLine for the same cell. So, the CellValue will be overridden and returns only FileBLine only. In order to set the CellValue from list, the PopulateValues() method can be used. Refer to the below code and sample,

Dim difference As New List(Of Differences)()
difference.Add(New Differences() With {.LineNumber = 1, .FileALine = `"FileLineA", .FileBLine = "FileLineB"})
difference.Add(New Differences() With {.LineNumber = 2, .FileALine = "FileLineB", .FileBLine = "FileLineA"})
Dim r As New Result()
For Each d As Differences In difference
r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileALine})
r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileBLine})
Next d
Me.gridControl1.PopulateHeaders(GridRangeInfo.Cells(0, 1, gridControl1.RowCount, gridControl1.ColCount), r.Changes)
Me.gridControl1.PopulateValues(GridRangeInfo.Cells(1, 1, gridControl1.RowCount, gridControl1.ColCount), r.Changes)
Me.gridControl1.Refresh()

Suggestion 2

You can also set the CellValue by Text property of GridStyleInfo class. refer to the sample,

Dim difference As New List(Of Differences)()
difference.Add(New Differences() With {.LineNumber = 1, .FileALine = "FileLineA", .FileBLine = "FileLineB"})
difference.Add(New Differences() With {.LineNumber = 2, .FileALine = "FileLineB", .FileBLine = "FileLineA"})
Dim r As New Result()
For Each d As Differences In difference
r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileALine})
 r.Changes.Add(New Data() With {.DataRow = d.LineNumber, .Details = d.FileBLine})
Next d
DisplayValues(r)
Private Sub DisplayValues(ByVal result As Result)
If result IsNot Nothing AndAlso result.Changes.Count > 0 Then
   Dim differences = result.Changes
   Me.gridControl1.RowCount = result.Changes.Count
   Me.gridControl1.ColCount = 2
   For i = 0 To differences.Count - 1
      Dim detailsA = TryCast(differences(i), Data)
      Dim row = i + 1
      Me.gridControl1(row, 1).Text = detailsA.DataRow.ToString()
     'To set FileALine or FileBLine for column 2
      Me.gridControl1(row, 2).Text = detailsA.Details
      Next i
   End If
End Sub

Note: you can create an object for the list to populate data as your convenient.


来源: stackexchange

问:
Passing Id from CreateView to another function after creating the object
I am creating a Payment object using Django CreateView then I want to pass the id of this object to another view function to make and display some calculations on another template. how can i do that?

views.py:

```<code>class CreatePayment(CreateView):
    template_name = "inventory/new_payment.html"
    success_url = reverse_lazy('inventory:payments_page')
    model = Payments
    fields = ('payment_number', 'customer','agent', 'amount')
</code>```

html:

```<code><body>

<form action="{% url 'inventory:new_payment'%}" method="post">
    {% csrf_token %}
    {{form}}

    <button type="submit", value="Add">Add</button>
</form>

</body>
</code>```

urls:

```<code>url(r'newpayment/$', CreatePayment.as_view(), name='new_payment')
</code>```

答:
I did it by overriding the get_success_url in CreateView like this:

```<code>def get_success_url(self):
    return reverse('inventory:transaction', args=(self.object.id,))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a Payment object using Django CreateView then I want to pass the id of this object to another view function to make and display some calculations on another template. how can i do that?

views.py:

class CreatePayment(CreateView):
    template_name = "inventory/new_payment.html"
    success_url = reverse_lazy('inventory:payments_page')
    model = Payments
    fields = ('payment_number', 'customer','agent', 'amount')

html:

<form action="{% url 'inventory:new_payment'%}" method="post">
    {% csrf_token %}
    {{form}}

    <button type="submit", value="Add">Add</button>
</form>

urls:

url(r'newpayment/$', CreatePayment.as_view(), name='new_payment')

Body:
I did it by overriding the get_success_url in CreateView like this:

def get_success_url(self):
    return reverse('inventory:transaction', args=(self.object.id,))


问:
"too many values to unpack error" when trying to create a batch in pyglet
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

```<code>from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))
</code>```

答:
Your problem is in this line:

```<code>batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))
</code>```

I believe it should be:

```<code>batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), ('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205)))
</code>```

Notice how I changed the last argument from the format ((tuple), (tuple)) to (tuple), (tuple)). I'm not familiar with pyglet, but discovered this is the correct way of calling batch.add() from the documentation. Note that *data represents a variable list of parameters at the end of the function call, not a tuple or a list like you attempted.

Try that and let us know how it works out for you.

ContentLicense: CC BY-SA 2.5

Body:
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))

Body:
Your problem is in this line:

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))

I believe it should be:

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), ('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205)))

Notice how I changed the last argument from the format ((tuple), (tuple)) to (tuple), (tuple)). I'm not familiar with pyglet, but discovered this is the correct way of calling batch.add() from the documentation. Note that *data represents a variable list of parameters at the end of the function call, not a tuple or a list like you attempted.

Try that and let us know how it works out for you.


问:
Update App to add redirect url
I registered my app, but didn't provide a redirect url. Now my app has been approved, but I have no way to edit so I can add it.

Please let me know how I can add my redirect url to the sound cloud api settings for my app.

Thanks

答: You'll need to get in touch with SoundCloud Support to do this: support@soundcloud.com.</p>

Title: Update App to add redirect url


问:
How to upload PDF file on parse server (parse.com)
I know how to upload image file.I upload image as base 64 string.How to upload other formats like pdf,doc etc.Any idea.</p>

答:
You upload them the same way but with different content type.

For example for a PDF file in iOS SDK:

```<code>let file = PFFile(name: "file.pdf", data: fileData, contentType: "application/pdf")
</code>```

Google for content type of your file type that you want to upload.

Body:
You upload them the same way but with different content type.

For example for a PDF file in iOS SDK:

let file = PFFile(name: "file.pdf", data: fileData, contentType: "application/pdf")

Google for content type of your file type that you want to upload.


问:
Delete a row with the highest value of a specific column
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

```<code>Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL
</code>```

My Code:

```<code>if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();
</code>```

Don't work either when commandText is

```<code>@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";
</code>```

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

```<code>cmd.ExecuteNonQuery();
</code>```

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

答:
```<code>  delete from hours where [Index] = (select max([Index]) from hours)
</code>```

i guess you are missing brackets.

Body:
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL

My Code:

if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();

Don't work either when commandText is

@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

cmd.ExecuteNonQuery();

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

Body:
  delete from hours where [Index] = (select max([Index]) from hours)

i guess you are missing brackets.

ContentLicense: CC BY-SA 4.0


问:
Convert xy dataset to array
I have a dataset of time/value e.g.

```<code>> df <- data.frame(time=c(1,4,5,6), speed=c(100, 500, 600, 800))
</code>```

I want to convert it to an array with one item per time tick:

```<code>> some_func(df, speed ~ time, step=1)
[1] 100 100 100 500 600 800
</code>```

notice that a values for time == 2 and 3 were added.

Then I can use it in the cross correlation function.

答:
A possible way is by using the stepfunction to interpolate, as you wanted this in your above example.</p>

```<code>sf<-stepfun(df$time,c(df$speed[1],df$speed))
sf(1:6)
</code>```

Title: Convert xy dataset to array

Body:
I have a dataset of time/value e.g.

> df <- data.frame(time=c(1,4,5,6), speed=c(100, 500, 600, 800))

I want to convert it to an array with one item per time tick:

> some_func(df, speed ~ time, step=1)
[1] 100 100 100 500 600 800

notice that a values for time == 2 and 3 were added.

Then I can use it in the cross correlation function.

Body:
A possible way is by using the stepfunction to interpolate, as you wanted this in your above example.

sf<-stepfun(df$time,c(df$speed[1],df$speed))
sf(1:6)


问:
Know if an argument has been specified by user when using Python's argparse
Let's say I have a python test using argparse, with several arguments:

IP (default: 127.0.0.1)

enabled_features (default: [A, B, C])

Sometimes, I'd like to change the default enabled_features, let's say to [A,B,C,D]:

depending on something I need the IP to find out (so it can't really be a default value in the way argparse has default values)

only if the user hasn't specified the "enabled_features"... that's what I have trouble to know!

So is there an attribute in the argparse classes to know, after:

```<code>opts = parser.parse_args()
</code>```

...that an argument was actually specified by the user, i.e. that one has used something like:

```<code>$ python my_test.py --enabled_features A B C
</code>```

and not:

```<code>$ python my_test.py
</code>```

Thanks!

答:
The parser object itself saves some useful information we can use to check out the defaults we assigned when adding the argument.

Example script parser_ex.py:

```<code>import argparse

def specified_nondefault(opts, parser, arg):
  """
  Checks whether an argument was specified to be something other than the
  default value.

  ..Note: This doesn't actually check if the argument was specified, as it
          can be 'tricked' by the user specifying the default value.

  :param argparse.Namespace opts: Parsed arguments to check.
  :param argparse.Parser parser: The parser they were parsed with.
  :param str arg: The name of the argument in question.
  :return bool: Whether the current argument value differs from the default.
  """

  if getattr(opts, arg) == parser.get_default(arg):
    return False
  return True

parser = argparse.ArgumentParser()

parser.add_argument('enabled_features', nargs='*', default=['A', 'B', 'C', 'D'])

opts = parser.parse_args()

print specified_nondefault(opts, parser, 'enabled_features')
</code>```

In which case:

>> parser_ex.py 'B'
  True

Because we've done something non-default. While

>> parser_ex.py 'A' 'B' 'C' 'D'
  False

and

>> parser_ex.py
  False

Since this just has default input.

Note that because we're checking against an entire list, there's some somewhat undesirable behaviour that order matters and

>> parser_ex.py 'B' 'A' 'C'
  True

IMO, this is a problem with lumping all the features into a single argument, but you can certainly work around it one way or another if you care.

Then, if the user has/n't specified non-defualt enabled_features, you can change them based on IP as desired.

Body:
Let's say I have a python test using argparse, with several arguments:

IP (default: 127.0.0.1)

enabled_features (default: [A, B, C])

Sometimes, I'd like to change the default enabled_features, let's say to [A,B,C,D]:

depending on something I need the IP to find out (so it can't really be a default value in the way argparse has default values)

only if the user hasn't specified the "enabled_features"... that's what I have trouble to know!

So is there an attribute in the argparse classes to know, after:

opts = parser.parse_args()

...that an argument was actually specified by the user, i.e. that one has used something like:

$ python my_test.py --enabled_features A B C

and not:

$ python my_test.py

Thanks!

Body:
The parser object itself saves some useful information we can use to check out the defaults we assigned when adding the argument.

Example script parser_ex.py:

import argparse

def specified_nondefault(opts, parser, arg):
  """
  Checks whether an argument was specified to be something other than the
  default value.

  ..Note: This doesn't actually check if the argument was specified, as it
          can be 'tricked' by the user specifying the default value.

  :param argparse.Namespace opts: Parsed arguments to check.
  :param argparse.Parser parser: The parser they were parsed with.
  :param str arg: The name of the argument in question.
  :return bool: Whether the current argument value differs from the default.
  """

  if getattr(opts, arg) == parser.get_default(arg):
    return False
  return True

parser = argparse.ArgumentParser()

parser.add_argument('enabled_features', nargs='*', default=['A', 'B', 'C', 'D'])

opts = parser.parse_args()

print specified_nondefault(opts, parser, 'enabled_features')

In which case:

>> parser_ex.py 'B'
  True

Because we've done something non-default. While

>> parser_ex.py 'A' 'B' 'C' 'D'
  False

and

>> parser_ex.py
  False

Since this just has default input.

Note that because we're checking against an entire list, there's some somewhat undesirable behaviour that order matters and

>> parser_ex.py 'B' 'A' 'C'
  True

IMO, this is a problem with lumping all the features into a single argument, but you can certainly work around it one way or another if you care.

Then, if the user has/n't specified non-defualt enabled_features, you can change them based on IP as desired.


问:
The PHP way to properly show and export to a file the result of a sql select?
I can't get this download started, I followed what it is said here but I am not really sure I'm done things properly.

I have a DB, when I open the below page (from a link), I wish to be able to view the SQL content, and at the button click i wish to open the browser dialog box that will save the result of the SQL into a file.

From the menu, I click on "export", it opens this page (export.php):

```<code><form id="exportConf" method="POST" action="exportConf.php">
<div id="exportPanel">
  <div class="row">
    <div class="col-md-8">
      <div class="row">
<?php
$query = "SELECT * from table";
$result = mysql_query($conn, $query);
echo "<input type=\"hidden\" name=\"export\" value=\"$result\"/>";
if ($result){
    echo "<table>";
    while ($row = mysql_fetch_row($result)){
    echo "<tr>";
    echo "<td>Name: </td><td>$row[0]</td>";
    echo "<td>Surname: </td><td>$row[1]</td>";
    echo "<td>Email: </td><td>$row[2]</td>";
    echo "<td>Phone: </td><td>$row[3]</td>";
    echo "</tr>";
    }
    echo "</table>";
} else {
    echo "Can't show the sql.";
}
?>
      </div>
    </div>
    <div class="col-md-4">
      <button type="submit" name="submit" class="btn btn-danger pull-right">Export to file</button>
    </div>
  </div>

  <div class="row clearfix">
  </div>

 </div>
</form>
</code>```

The exportConf.php is this:

```<code><?php
IF(isset($_POST['exportConf'])){
    //require_once('variables.php');
    $result = addslashes(strip_tags($_POST["export"]));
    /*$exportFile = "myfile.txt";
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename=$exportFile');
    header("Content-Length: " . filesize($exportFile));

    $file = fopen($exportFile,"w+");
    echo fputs($file,$result);
    fclose($file);
    */
    echo "Test: $result";

    }
?>
</code>```

I'm trying to print the value of $result but all I see is an empty white page.

I'm writing it on notepad and I do not have the DB ready, therefore no data BUT at least I expect it goes into the ELSE condition and add the $result inside the hidden input.

I should be able to only see Test: , in my white page. But I'm not.
Someone can tell me what it is missing? And if I wrote the download part properly?

答:
```<code><button type="submit" name="exportConf" class="btn btn-danger pull-right">Export to file</button>
</code>```

<p>Thanks to the comments, the "exportConf" was missing. </p>

```<code><?php
IF(isset($_POST['exportConf'])){
    require_once('config.php');
    require_once('variables.php');

    $handle = fopen("C:/file.txt", "w");
    fwrite($handle, $result);
    fclose($handle);

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename('file.txt'));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize('file.txt'));
    readfile('file.txt');

    exit;
}

?>
</code>```

Body:
I can't get this download started, I followed what it is said here but I am not really sure I'm done things properly.

I have a DB, when I open the below page (from a link), I wish to be able to view the SQL content, and at the button click i wish to open the browser dialog box that will save the result of the SQL into a file.

From the menu, I click on "export", it opens this page (export.php):

<form id="exportConf" method="POST" action="exportConf.php">

<?php
$query = "SELECT * from table";
$result = mysql_query($conn, $query);
echo "<input type=\"hidden\" name=\"export\" value=\"$result\"/>";
if ($result){
    echo "
";
    while ($row = mysql_fetch_row($result)){
    echo "
";
    echo "Name: 	$row[0]	";
    echo "Surname: 	$row[1]	";
    echo "Email: 	$row[2]	";
    echo "Phone: 	$row[3]	";
    echo "
";
    }
    echo "
";
} else {
    echo "Can't show the sql.";
}
?>

      <button type="submit" name="submit" class="btn btn-danger pull-right">Export to file</button>

</form>

The exportConf.php is this:

<?php
IF(isset($_POST['exportConf'])){
    //require_once('variables.php');
    $result = addslashes(strip_tags($_POST["export"]));
    /*$exportFile = "myfile.txt";
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename=$exportFile');
    header("Content-Length: " . filesize($exportFile));

    $file = fopen($exportFile,"w+");
    echo fputs($file,$result);
    fclose($file);
    */
    echo "Test: $result";

    }
?>

I'm trying to print the value of $result but all I see is an empty white page.

I'm writing it on notepad and I do not have the DB ready, therefore no data BUT at least I expect it goes into the ELSE condition and add the $result inside the hidden input.

I should be able to only see Test: , in my white page. But I'm not.
Someone can tell me what it is missing? And if I wrote the download part properly?

Body:
<button type="submit" name="exportConf" class="btn btn-danger pull-right">Export to file</button>

Thanks to the comments, the "exportConf" was missing.

<?php
IF(isset($_POST['exportConf'])){
    require_once('config.php');
    require_once('variables.php');

    $handle = fopen("C:/file.txt", "w");
    fwrite($handle, $result);
    fclose($handle);

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename('file.txt'));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize('file.txt'));
    readfile('file.txt');

    exit;
}

?>


问:
Ionic 3 block backbutton Event
I would like to intercept the back button event.
As soon as the listener is called, the back signal is already triggered.

This is what i tried:

```<code> document.addEventListener("backbutton", () => {
       console.log("[WARN] BackBtn pushed");
       console.log("TextboxVal: " + this.inputValue);
       this.showConfirm();
       document.removeEventListener("backbutton");
     });
</code>```

I dont want to lose the "this.inputValue" value.
But in the most cases its gone already.

答:
I want to show an alert before leaving the page.

You can use NavGuards for that:

In some cases, a developer should be able to control views leaving and
  entering. To allow for this, NavController has the ionViewCanEnter
  and ionViewCanLeave methods. Similar to Angular route guards, but
  are more integrated with NavController.

```<code>  // ...

  ionViewCanLeave() {

    if(this.inputValue) {
      // Show the alert
      this.presentConfirm();
    }

    // Will leave if the input is null
    return this.inputValue === null;
  }

  presentConfirm() {
    let alert = this.alertCtrl.create({
      title: 'Exit',
      message: 'Do you want to exit?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Exit',
          handler: () => {

            // Allow the user to exit this page
            this.inputValue = null;

            // Go back to the previous page
            setTimeout(() => { this.navCtrl.pop(); }, 500);

          }
        }
      ]
    });
    alert.present();
  }
</code>```

Title: Ionic 3 block backbutton Event

Body:
I would like to intercept the back button event.
As soon as the listener is called, the back signal is already triggered.

This is what i tried:

 document.addEventListener("backbutton", () => {
       console.log("[WARN] BackBtn pushed");
       console.log("TextboxVal: " + this.inputValue);
       this.showConfirm();
       document.removeEventListener("backbutton");
     });

I dont want to lose the "this.inputValue" value.
But in the most cases its gone already.

Body:
I want to show an alert before leaving the page.

You can use NavGuards for that:

In some cases, a developer should be able to control views leaving and
  entering. To allow for this, NavController has the ionViewCanEnter
  and ionViewCanLeave methods. Similar to Angular route guards, but
  are more integrated with NavController.

  // ...

  ionViewCanLeave() {

    if(this.inputValue) {
      // Show the alert
      this.presentConfirm();
    }

    // Will leave if the input is null
    return this.inputValue === null;
  }

  presentConfirm() {
    let alert = this.alertCtrl.create({
      title: 'Exit',
      message: 'Do you want to exit?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Exit',
          handler: () => {

            // Allow the user to exit this page
            this.inputValue = null;

            // Go back to the previous page
            setTimeout(() => { this.navCtrl.pop(); }, 500);

          }
        }
      ]
    });
    alert.present();
  }


问:
Magento 404 error page frontend
I noticed that Magento throw back a 404 error when trying to access the website from other locations. This only happenes on frontend. Backend can be accessible from all over the world. I don't know what's wrong.
I can access the website just normally without any problems! I can access the website even at home without no issues!
The Website is: borika.de
No restrictions have been noticed. Does anyone have an idea how to solve this issue?
Thanks</p>

答: Please check could you make a condition of your index.php or try to replace with another same version index.php may be it will help

Title: Magento 404 error page frontend


问:
Issue with IE11 multi-height TH and positioning of pseudo elements
I am trying to add few icons on the  by putting them to position: relative and then positioning the icons as ::after pseudo element using position: absolute inside the  and giving the icons as background (since they are sprites). This works perfectly in Google Chrome and Firefox, but not in Internet Explorer.

Here's the snippet that demonstrates the problem (which is reproducible only in Internet Explorer, my version 11):

* {font-family: 'Segoe UI';}
.arrow {border: 1px solid #ccc; padding: 5px; line-height: 1; background-color: #00f; color: #fff; position: relative; cursor: pointer; padding-right: 20px;}
.arrow-normal::after {width: 9px; height: 12px; margin-top: -6px;}
.arrow-up::after {width: 9px; height: 6px; margin-top: -3px;}
.arrow-down::after {width: 9px; height: 6px; margin-top: -3px; background-position: 0 -6px;}
.arrow::after {
  top: 50%;
  position: absolute;
  right: 5px;
  content: ' ';
  display: block;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAYAAABiDJ37AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAnZJREFUeNpsk99rUmEYx1/l+Hvmj8HwQgQvvHKS0LqJQCOIMnTmqOb8UTfdDjb/iYneDAaCIhgSE/NnTOZNMAapkCFYbMEIuiswaHPq5tHj6XlsR3TsCw/nfR/e9/M+vw4RCAQEDWW325+0Wq0fDofDKhKJyMLCwthYlh1btVolpVKJHB4eklgsdlur1X4LBALPCoUCSSaTJJvNkgnM6XTaz0FwkYVP2+VyPRIKhTPASqVCDg4OSCQSWZqfn/8F11h4uLe5ufk8l8v9B6JWVlacl5eXF+yUOp3OOfjHUA7YbDbJzs7Oklqt/o0wziiKotfX11fL5TIha2trL/v9Ps3eIIB2fT7fMgeMx+P35+bm/kzDpozZ2Njw8xqNxkeDwXC32+22eSByJQTKZLJbJycnn81m80P0QRneQcp2uVz+F7aTsyjIUKbX65s8t9st1Gg0gsFgwE7BCLKhvryzs7MBREajv16vU0qlUsDn81kOeHV2vO/1egxlMpkYm82GL5DrwvpBRAy3h1qNisXigGvktCAgsri4OKJgVEqwuAOOzrUzLFyUSySSL7B+jI6tra14Pp9/ClGeQmQzKUN0MqPR+JVsb2/7R6MRc1NThsNhP5FIvOCasre390ChUJze1BRMOxgMvsGRIdFodBUinOk0TdO9VCrlgBmbjA08QPb39++pVKqZTkNNmVAo9Ap+CsKXSqU4sCmYfA9ALjB8/GYymdWjo6MPYrF4khY0iFit1sru7u4yDDZCsXE0wF57vd637Xab8NGJ0Fqt9h4idcOln+l02nV8fDwDQ2HnEWqxWD7BGZtOp/seDof9Ho8niTDM4p8AAwB6jpihgDknYAAAAABJRU5ErkJggg==");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th class="arrow arrow-normal">Two Line<br />Column</th>
      <th class="arrow arrow-up">Single</th>
      <th class="arrow arrow-down">Three<br />Line<br />Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
      <td>Item 3</td>
    </tr>
  </tbody>
</table></code>```

When I run this in Google Chrome, I get the expected output:

All the icons in Google Chrome are aligned perfectly in middle.

Whereas, in Internet Explorer, the problem is, all the  elements take the right height, when they have different contents, but the positioning is messed up.

What I see is that, in Internet Explorer, the heights are calculated right, but for position, the initial heights before adjusting the tables are taken into account. Is there anything that can be done to fix this?

Note 1: I have also looked into IE vertical centering bug with table-cell parent and absolutely positioned pseudo-element, which requires me to use another element and give position: relative, but this is not possible in my case as my HTML is fixed and can't be changed. It is generated by an enterprise application, which I have no control over.

Note 2: Since I already know the heights of each element, I am using the negative margin technique.

Please let me know if this is possible.

答:
Okay, I was constantly trying out different methods to use ::after and position it correctly and it looks like none of the methods worked in Internet Explorer 11. So finally I decided using three separate images for the background and positioning it as required.

Here's my updated snippet if someone would use it.

* {font-family: 'Segoe UI';}
.arrow {border: 1px solid #ccc; padding: 5px; line-height: 1; color: #fff; cursor: pointer; padding-right: 20px;}
.arrow-normal {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAMCAYAAACwXJejAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAA6klEQVQoU3WQzQqCQBSFB4IW9VKtosCaUKwQbOkL+CBuRHAnLlz4BG16BRci7spNgeJGysofou41jTT64DLMOefOzB3yDcMw0ziO95TSUS21AWN2AZ4ALGeO48a19YZl2cUdwEBDmqaXT1AQhFWWZUXttYATr6IoUuI4zg66zmEYHqMoOjWFe9TRJzzP92VZHkqSNOgW6ugT27Z7nuf1/xX6xHXdLVwfF0URdOqAuu/7W6IoyuYBVC/tUJZlbhjGsppQ1/U1dLYmzPP8ZlnWvAo0aJrGw1fcMIDrT6BBVVWaJElgmuaklgBCXtrc+nqGz49JAAAAAElFTkSuQmCC") right 5px center no-repeat #00f;}
.arrow-up {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAGCAYAAAARx7TFAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAfklEQVQYV2NABj4+Pp6vX7++6+/v7wAVQgVACd/PQPAfCIDUp+DgYDeoFAQEBQUFfAcCkAIY+PLly2e4wqioqPAfP378gsqhAKCJX2NjY/0Zzp07txeo69OLFy+evHz58ikMg/ggcZA8Q2hoKFtxcTF3WloaFzoGiYeGhrIBANcmc5DiPaghAAAAAElFTkSuQmCC") right 5px center no-repeat #00f;}
.arrow-down {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAGCAYAAAARx7TFAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAfUlEQVQYV2NYtWoV85UrV9hwYZA8w6VLl3b8////9a9fv+6j4Xsg8WvXru1g6O/vj/sLBEABDPD79++fCxYsCGMAgZkzZ0YAdf6CyoHBz58/vy1btswPrAAGpk2bFvrjx49vIAUgGkMBDEyZMsX/w4cP9xctWuQBFQICBgYAx8mG6/gP36QAAAAASUVORK5CYII=") right 5px center no-repeat #00f;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th class="arrow arrow-normal">Two Line<br />Column</th>
      <th class="arrow arrow-up">Single</th>
      <th class="arrow arrow-down">Three<br />Line<br />Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
      <td>Item 3</td>
    </tr>
  </tbody>
</table></code>```

Preview

Bonus: The nice part about this is, I have also used something called CSS background-position edge offsets, which helps me in achieving the following stuff, that I did using right: 5px; for ::after pseudo elements in my snippet. Well, I wanted to give a 5px padding for my arrows to not get stuck to the edge of the table, and I had the following reasons / justifications:

I am lazy to use Photoshop CS3 to give a padding right to the image and recreate the data:// URI for the same.

This is not right, as the image shouldn't have padding inbuilt. What if it is supposed to be used on left side?

By adding the extra bit of:

.class {background: url("image.png") right 5px center no-repeat;}
```

The above CSS offsets the right side of background-position for a span of 5px, which is literally like right-5px calculation. Cool, isn't it?

I covered the full experience as Challenge: Internet Explorer Table Cells & Positioning Nightmare & Alternatives in my blog post.

Note: This is just an alternative to what I wanted, and I would consider this as a hack-job. I am going to wait till I get a real solution to use the position and CSS Sprites.

Body:
I am trying to add few icons on the  by putting them to position: relative and then positioning the icons as ::after pseudo element using position: absolute inside the  and giving the icons as background (since they are sprites). This works perfectly in Google Chrome and Firefox, but not in Internet Explorer.

Here's the snippet that demonstrates the problem (which is reproducible only in Internet Explorer, my version 11):

* {font-family: 'Segoe UI';}
.arrow {border: 1px solid #ccc; padding: 5px; line-height: 1; background-color: #00f; color: #fff; position: relative; cursor: pointer; padding-right: 20px;}
.arrow-normal::after {width: 9px; height: 12px; margin-top: -6px;}
.arrow-up::after {width: 9px; height: 6px; margin-top: -3px;}
.arrow-down::after {width: 9px; height: 6px; margin-top: -3px; background-position: 0 -6px;}
.arrow::after {
  top: 50%;
  position: absolute;
  right: 5px;
  content: ' ';
  display: block;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAYAAABiDJ37AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAnZJREFUeNpsk99rUmEYx1/l+Hvmj8HwQgQvvHKS0LqJQCOIMnTmqOb8UTfdDjb/iYneDAaCIhgSE/NnTOZNMAapkCFYbMEIuiswaHPq5tHj6XlsR3TsCw/nfR/e9/M+vw4RCAQEDWW325+0Wq0fDofDKhKJyMLCwthYlh1btVolpVKJHB4eklgsdlur1X4LBALPCoUCSSaTJJvNkgnM6XTaz0FwkYVP2+VyPRIKhTPASqVCDg4OSCQSWZqfn/8F11h4uLe5ufk8l8v9B6JWVlacl5eXF+yUOp3OOfjHUA7YbDbJzs7Oklqt/o0wziiKotfX11fL5TIha2trL/v9Ps3eIIB2fT7fMgeMx+P35+bm/kzDpozZ2Njw8xqNxkeDwXC32+22eSByJQTKZLJbJycnn81m80P0QRneQcp2uVz+F7aTsyjIUKbX65s8t9st1Gg0gsFgwE7BCLKhvryzs7MBREajv16vU0qlUsDn81kOeHV2vO/1egxlMpkYm82GL5DrwvpBRAy3h1qNisXigGvktCAgsri4OKJgVEqwuAOOzrUzLFyUSySSL7B+jI6tra14Pp9/ClGeQmQzKUN0MqPR+JVsb2/7R6MRc1NThsNhP5FIvOCasre390ChUJze1BRMOxgMvsGRIdFodBUinOk0TdO9VCrlgBmbjA08QPb39++pVKqZTkNNmVAo9Ap+CsKXSqU4sCmYfA9ALjB8/GYymdWjo6MPYrF4khY0iFit1sru7u4yDDZCsXE0wF57vd637Xab8NGJ0Fqt9h4idcOln+l02nV8fDwDQ2HnEWqxWD7BGZtOp/seDof9Ho8niTDM4p8AAwB6jpihgDknYAAAAABJRU5ErkJggg==");
}

      Two Line
Column
      Single
      Three
Line
Column

      Item 1
      Item 2
      Item 3

When I run this in Google Chrome, I get the expected output:

All the icons in Google Chrome are aligned perfectly in middle.

Whereas, in Internet Explorer, the problem is, all the  elements take the right height, when they have different contents, but the positioning is messed up.

What I see is that, in Internet Explorer, the heights are calculated right, but for position, the initial heights before adjusting the tables are taken into account. Is there anything that can be done to fix this?

Note 1: I have also looked into IE vertical centering bug with table-cell parent and absolutely positioned pseudo-element, which requires me to use another element and give position: relative, but this is not possible in my case as my HTML is fixed and can't be changed. It is generated by an enterprise application, which I have no control over.

Note 2: Since I already know the heights of each element, I am using the negative margin technique.

Please let me know if this is possible.

Body:
Okay, I was constantly trying out different methods to use ::after and position it correctly and it looks like none of the methods worked in Internet Explorer 11. So finally I decided using three separate images for the background and positioning it as required.

Here's my updated snippet if someone would use it.

* {font-family: 'Segoe UI';}
.arrow {border: 1px solid #ccc; padding: 5px; line-height: 1; color: #fff; cursor: pointer; padding-right: 20px;}
.arrow-normal {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAMCAYAAACwXJejAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAA6klEQVQoU3WQzQqCQBSFB4IW9VKtosCaUKwQbOkL+CBuRHAnLlz4BG16BRci7spNgeJGysofou41jTT64DLMOefOzB3yDcMw0ziO95TSUS21AWN2AZ4ALGeO48a19YZl2cUdwEBDmqaXT1AQhFWWZUXttYATr6IoUuI4zg66zmEYHqMoOjWFe9TRJzzP92VZHkqSNOgW6ugT27Z7nuf1/xX6xHXdLVwfF0URdOqAuu/7W6IoyuYBVC/tUJZlbhjGsppQ1/U1dLYmzPP8ZlnWvAo0aJrGw1fcMIDrT6BBVVWaJElgmuaklgBCXtrc+nqGz49JAAAAAElFTkSuQmCC") right 5px center no-repeat #00f;}
.arrow-up {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAGCAYAAAARx7TFAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAfklEQVQYV2NABj4+Pp6vX7++6+/v7wAVQgVACd/PQPAfCIDUp+DgYDeoFAQEBQUFfAcCkAIY+PLly2e4wqioqPAfP378gsqhAKCJX2NjY/0Zzp07txeo69OLFy+evHz58ikMg/ggcZA8Q2hoKFtxcTF3WloaFzoGiYeGhrIBANcmc5DiPaghAAAAAElFTkSuQmCC") right 5px center no-repeat #00f;}
.arrow-down {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAGCAYAAAARx7TFAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAfUlEQVQYV2NYtWoV85UrV9hwYZA8w6VLl3b8////9a9fv+6j4Xsg8WvXru1g6O/vj/sLBEABDPD79++fCxYsCGMAgZkzZ0YAdf6CyoHBz58/vy1btswPrAAGpk2bFvrjx49vIAUgGkMBDEyZMsX/w4cP9xctWuQBFQICBgYAx8mG6/gP36QAAAAASUVORK5CYII=") right 5px center no-repeat #00f;}

<table>
  <thead>
    <tr>
      <th class="arrow arrow-normal">Two Line<br />Column</th>
      <th class="arrow arrow-up">Single</th>
      <th class="arrow arrow-down">Three<br />Line<br />Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
      <td>Item 3</td>
    </tr>
  </tbody>
</table>

Preview

Bonus: The nice part about this is, I have also used something called CSS background-position edge offsets, which helps me in achieving the following stuff, that I did using right: 5px; for ::after pseudo elements in my snippet. Well, I wanted to give a 5px padding for my arrows to not get stuck to the edge of the table, and I had the following reasons / justifications:

I am lazy to use Photoshop CS3 to give a padding right to the image and recreate the data:// URI for the same.

This is not right, as the image shouldn't have padding inbuilt. What if it is supposed to be used on left side?

By adding the extra bit of:

.class {background: url("image.png") right 5px center no-repeat;}

The above CSS offsets the right side of background-position for a span of 5px, which is literally like right-5px calculation. Cool, isn't it?

I covered the full experience as Challenge: Internet Explorer Table Cells & Positioning Nightmare & Alternatives in my blog post.

Note: This is just an alternative to what I wanted, and I would consider this as a hack-job. I am going to wait till I get a real solution to use the position and CSS Sprites.


问:
Automated Deployment of Server-Specific Configurations
I have some Java projects that use Apache Commons Configuration and they get deployed to multiple servers in multiple environments (dev/test/prod).

All code is the same, but some config items change, such as JMS URLs (dev should point to dev, etc) as well as the server name and environment (I use these config items for debugging).

Example:

```<code><config>
    <!-- environment can be dev|test|prod -->
    <environment>dev</environment>

    <serverName>myServer1</serverName>

    <jmsUrl>http://my-jms-url-dev1,http://my-jms-url-dev2</jmsUrl>
</config>
</code>```

Currently, I deploy, build, then edit the files manually to provide the server-specific configurations. I want a way to automate this when I deploy it to individual servers, but all the ways I've considered require an equal amount of pain to setup.

ANT - Check out the project with SVN and build it on each server with ANT. ANT reads the server name and the environment from two static files - .servername and .environment - and copies a server-specific config to the generic config. The problem with this is, I still have to create a config file for each server (I have 24 servers, and this may increase, so scalability is not good).

SVN - Branch each of my projects to a server-specific distribution. Here, scalability is worse and it becomes a nightmare to maintain.

Does anybody have any tips for me?

答:
I figured this out.

Step 1.

Get the host name:

```<code><target name="getHostname" description="Stores the current machines hostname in a property named 'hostname'">
    <property environment="env" />
    <condition property="hostname" value="${env.HOSTNAME}">
        <os family="unix" />
    </condition>

    <!-- Execute hostname command on Linux systems -->
    <exec executable="hostname"
          osfamily="unix"
          failifexecutionfails="false"
          outputproperty="env.COMPUTERNAME"/>

    <!-- On Windows, the hostname is an environment variable -->
    <condition property="hostname" value="${env.COMPUTERNAME}">
        <os family="windows" />
    </condition>

    <echo message="${env.COMPUTERNAME}" />

</target>
</code>```

Step two, create a template file and use  to copy the file and do a find/replace on it:

```<code>    <copy file="${scripts}/.servername.template"
          tofile="${scripts}/.servername">
        <filterchain>
            <replacetokens>
                <token key="SERVER_NAME"
                       value="${env.COMPUTERNAME}" />
            </replacetokens>
        </filterchain>
    </copy>
</code>```

The .servername.template file contains this string:

```<code>@SERVER_NAME@
</code>```

Then, I use a web service to get a JSON string to tell me what environment I'm in. And I use the  task to process the JSON and get the environment.

Pretty heavy-duty for such a simple task, but it works!

Body:
I have some Java projects that use Apache Commons Configuration and they get deployed to multiple servers in multiple environments (dev/test/prod).

All code is the same, but some config items change, such as JMS URLs (dev should point to dev, etc) as well as the server name and environment (I use these config items for debugging).

Example:

<config>

    <environment>dev</environment>

    <serverName>myServer1</serverName>

    <jmsUrl>http://my-jms-url-dev1,http://my-jms-url-dev2</jmsUrl>
</config>

Currently, I deploy, build, then edit the files manually to provide the server-specific configurations. I want a way to automate this when I deploy it to individual servers, but all the ways I've considered require an equal amount of pain to setup.

ANT - Check out the project with SVN and build it on each server with ANT. ANT reads the server name and the environment from two static files - .servername and .environment - and copies a server-specific config to the generic config. The problem with this is, I still have to create a config file for each server (I have 24 servers, and this may increase, so scalability is not good).

SVN - Branch each of my projects to a server-specific distribution. Here, scalability is worse and it becomes a nightmare to maintain.

Does anybody have any tips for me?

Body:
I figured this out.

Step 1.

Get the host name:

<target name="getHostname" description="Stores the current machines hostname in a property named 'hostname'">
    <property environment="env" />
    <condition property="hostname" value="${env.HOSTNAME}">
        <os family="unix" />
    </condition>

    <!-- Execute hostname command on Linux systems -->
    <exec executable="hostname"
          osfamily="unix"
          failifexecutionfails="false"
          outputproperty="env.COMPUTERNAME"/>

    <!-- On Windows, the hostname is an environment variable -->
    <condition property="hostname" value="${env.COMPUTERNAME}">
        <os family="windows" />
    </condition>

    <echo message="${env.COMPUTERNAME}" />

</target>

Step two, create a template file and use  to copy the file and do a find/replace on it:

    <copy file="${scripts}/.servername.template"
          tofile="${scripts}/.servername">
        <filterchain>
            <replacetokens>
                <token key="SERVER_NAME"
                       value="${env.COMPUTERNAME}" />
            </replacetokens>
        </filterchain>
    </copy>

The .servername.template file contains this string:

@SERVER_NAME@

Then, I use a web service to get a JSON string to tell me what environment I'm in. And I use the  task to process the JSON and get the environment.

Pretty heavy-duty for such a simple task, but it works!


问:
Predicate in FetchResults for Core Data has no effect
I have a Core Data app that basically works for retrieving data, but when I apply a predicate there is no filtering. In other words, the same results are returned regardless of the filter.  Any suggestions?

```<code>lazy var frc: NSFetchedResultsController<Report> =
    {
        let context = self.app.persistentContainer.viewContext

        let req: NSFetchRequest<Report> = Report.fetchRequest()
        req.fetchBatchSize = 20

        let sortDescriptor = NSSortDescriptor(key: "status", ascending:true)
        req.sortDescriptors = [sortDescriptor]

        let filter = self.app.currentFilter
        //print(filter!)
        let predicate = NSPredicate(format: "status == %@", filter)
        req.predicate = predicate

        let afrc = NSFetchedResultsController(fetchRequest: req, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: "reports")
        afrc.delegate = self
        do
        {
            try afrc.performFetch()
        }
        catch
        {
            fatalError("Abort while fetching report")
        }
        return afrc
}()
</code>```

The status attribute for the Report entity is a String.

答:
Following up to the two comments above, maybe the answer is in the Apple documentation for NSFetchedResultsController.  Read the section Modifying the Fetch Request, noting in particular that

You cannot simply change the fetch request to modify the results.

Body:
I have a Core Data app that basically works for retrieving data, but when I apply a predicate there is no filtering. In other words, the same results are returned regardless of the filter.  Any suggestions?

lazy var frc: NSFetchedResultsController<Report> =
    {
        let context = self.app.persistentContainer.viewContext

        let req: NSFetchRequest<Report> = Report.fetchRequest()
        req.fetchBatchSize = 20

        let sortDescriptor = NSSortDescriptor(key: "status", ascending:true)
        req.sortDescriptors = [sortDescriptor]

        let filter = self.app.currentFilter
        //print(filter!)
        let predicate = NSPredicate(format: "status == %@", filter)
        req.predicate = predicate

        let afrc = NSFetchedResultsController(fetchRequest: req, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: "reports")
        afrc.delegate = self
        do
        {
            try afrc.performFetch()
        }
        catch
        {
            fatalError("Abort while fetching report")
        }
        return afrc
}()

The status attribute for the Report entity is a String.


问:
Regex to split a String with 2 delimiters, 2 times
I'm trying to split a String that looks something like this -

"Tomorrow - Cloudy - -3/1 "

to

"Tomorrow", "Cloudy", "-3", "1"

I know how to do it in two takes, first string.split("-",3) then result[2].split("/") but is there a regex to do it in one line? I've tried"[-{3}/]" but it doesn't seem to work.

答:
You can use the following if it's always in that format:

```<code>Pattern: (\w+)\s\-\s(\w+)\s\-\s(\-\d+)\/(\d+)
Substitution: \1\n\2\n\3\n\4\n

Input: Tomorrow - Cloudy - -3/1
Output: Tomorrow
        Cloudy
        -3
        1
</code>```

Example seen here: https://regex101.com/r/Fhnawd/1

Body:
You can use the following if it's always in that format:

Pattern: (\w+)\s\-\s(\w+)\s\-\s(\-\d+)\/(\d+)
Substitution: \1\n\2\n\3\n\4\n

Input: Tomorrow - Cloudy - -3/1
Output: Tomorrow
        Cloudy
        -3
        1

Example seen here: https://regex101.com/r/Fhnawd/1


问:
How to input large data into python pandas using looping or parallel computing?
I have a csv file of 8gb and I am not able to run the code as it shows memory error.

```<code>file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0, dtype=str)
</code>```

I would like to split the files into 8 small files ("sorted by id") using python. And fianlly,have a loop so that the output file will have the output of all 8 files.

Or I would like to try parallel computing. Main goal is to process 8gb data in python pandas.  Thank you.

My csv file contains numerous data with '/' as the comma separator,

```<code>id    venue           time             code    value ......
AAA   Paris      28/05/2016 09:10      PAR      45   ......
111   Budapest   14/08/2016 19:00      BUD      62   ......
AAA   Tokyo      05/11/2016 23:20      TYO      56   ......
111   LA         12/12/2016 05:55      LAX      05   ......
111   New York   08/01/2016 04:25      NYC      14   ......
AAA   Sydney     04/05/2016 21:40      SYD      2    ......
ABX   HongKong   28/03/2016 17:10      HKG      5    ......
ABX   London     25/07/2016 13:02      LON      22   ......
AAA   Dubai      01/04/2016 18:45      DXB      19   ......
.
.
.
.
</code>```

答:
Use the chunksize parameter to read one chunk at the time and save the files to disk. This will split the original file in equal parts by 100000 rows each:

```<code>file = "./data.csv"
chunks = pd.read_csv(file, sep="/", header=0, dtype=str, chunksize = 100000)

for it, chunk in enumerate(chunks):
    chunk.to_csv('chunk_{}.csv'.format(it), sep="/")
</code>```

If you know the number of rows of the original file you can calculate the exact chunksize to split the file in 8 equal parts (nrows/8).

Body:
I have a csv file of 8gb and I am not able to run the code as it shows memory error.

file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0, dtype=str)

I would like to split the files into 8 small files ("sorted by id") using python. And fianlly,have a loop so that the output file will have the output of all 8 files.

Or I would like to try parallel computing. Main goal is to process 8gb data in python pandas.  Thank you.

My csv file contains numerous data with '/' as the comma separator,

id    venue           time             code    value ......
AAA   Paris      28/05/2016 09:10      PAR      45   ......
111   Budapest   14/08/2016 19:00      BUD      62   ......
AAA   Tokyo      05/11/2016 23:20      TYO      56   ......
111   LA         12/12/2016 05:55      LAX      05   ......
111   New York   08/01/2016 04:25      NYC      14   ......
AAA   Sydney     04/05/2016 21:40      SYD      2    ......
ABX   HongKong   28/03/2016 17:10      HKG      5    ......
ABX   London     25/07/2016 13:02      LON      22   ......
AAA   Dubai      01/04/2016 18:45      DXB      19   ......
.
.
.
.

Body:
Use the chunksize parameter to read one chunk at the time and save the files to disk. This will split the original file in equal parts by 100000 rows each:

file = "./data.csv"
chunks = pd.read_csv(file, sep="/", header=0, dtype=str, chunksize = 100000)

for it, chunk in enumerate(chunks):
    chunk.to_csv('chunk_{}.csv'.format(it), sep="/")

If you know the number of rows of the original file you can calculate the exact chunksize to split the file in 8 equal parts (nrows/8).


问:
How to fix the last element of LineLayout that it does not go beyond the boundaries of the screen?
I try make layout with two TextView and one Linear Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>
</code>```

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

答:
Try this :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:layout_weight="1"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:ellipsize="end"
        android:layout_weight="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>
</code>```

Now both textViews will occupy half the width of screen. Adjust the weight to increase decrease the width.

Hope it helps!!!

Body:
I try make layout with two TextView and one Linear Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

Body:
Try this :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:layout_weight="1"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:ellipsize="end"
        android:layout_weight="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>

Now both textViews will occupy half the width of screen. Adjust the weight to increase decrease the width.

Hope it helps!!!


问:
Change data type of elements in a nested list
Is it possible to scan a list of lists for elements with a certain name and change their datatype but retain their value?

As an example, the following list containing elements 'N' of class 'character' or 'numeric'

```<code>x = list(list(N=as.character(1)),
         list(a=1,b=2,c="another element",N=as.character(5)),
         list(a=2,b=2,N=as.character(7),c=NULL),
         list(a=2,b=2,list(N=as.character(3))))
</code>```

should then become:

```<code>x = list(list(N=as.numeric(1)),
         list(a=1,b=2,c="another element",N=as.numeric(5)),
         list(a=2,b=2,N=as.numeric(7),c=NULL),
         list(a=2,b=2,list(N=as.numeric(3))))
</code>```

To be clear, the solution should allow for deeper nesting, and respect the data type of fields with names other than "N". I have not been able to find a general solution that works for lists with an arbitrary structure.

I have tried something along the lines of the solution given in this post:

```<code>a <- as.relistable(x)
u <- unlist(a)
u[names(u) == "N"] <- as.numeric(u[names(u) == "N"])
relist(u, a)
</code>```

Unfortunately the substitution does not work in it's current form. In addition, relist does not seem to work in case the list contains NULL elements.

答:
The answer provided by marco sandri can be further generalised to:

```<code>is_num <- function(x) grepl("^[-]?[0-9]+[.]?[0-9]*|^[-]?[0-9]+[L]?|^[-]?[0-9]+[.]?[0-9]*[eE][0-9]+",x)

as_num <- function(x) {
if (is.null(x)||length(x) == 0) return(x)
if (class(x)=="list") return(lapply(x, as_num))
if (is.character(x) & is_num(x)) return(as.numeric(x))
return(x)
}
y <- as_num(z)
identical(y,z)
</code>```

This solution also allows for list elements to contain numerical(0) and mixed datatypes such as 'data2005'.

Body:
Is it possible to scan a list of lists for elements with a certain name and change their datatype but retain their value?

As an example, the following list containing elements 'N' of class 'character' or 'numeric'

x = list(list(N=as.character(1)),
         list(a=1,b=2,c="another element",N=as.character(5)),
         list(a=2,b=2,N=as.character(7),c=NULL),
         list(a=2,b=2,list(N=as.character(3))))

should then become:

x = list(list(N=as.numeric(1)),
         list(a=1,b=2,c="another element",N=as.numeric(5)),
         list(a=2,b=2,N=as.numeric(7),c=NULL),
         list(a=2,b=2,list(N=as.numeric(3))))

To be clear, the solution should allow for deeper nesting, and respect the data type of fields with names other than "N". I have not been able to find a general solution that works for lists with an arbitrary structure.

I have tried something along the lines of the solution given in this post:

a <- as.relistable(x)
u <- unlist(a)
u[names(u) == "N"] <- as.numeric(u[names(u) == "N"])
relist(u, a)

Unfortunately the substitution does not work in it's current form. In addition, relist does not seem to work in case the list contains NULL elements.

Body:
The answer provided by marco sandri can be further generalised to:

is_num <- function(x) grepl("^[-]?[0-9]+[.]?[0-9]*|^[-]?[0-9]+[L]?|^[-]?[0-9]+[.]?[0-9]*[eE][0-9]+",x)

as_num <- function(x) {
if (is.null(x)||length(x) == 0) return(x)
if (class(x)=="list") return(lapply(x, as_num))
if (is.character(x) & is_num(x)) return(as.numeric(x))
return(x)
}
y <- as_num(z)
identical(y,z)

This solution also allows for list elements to contain numerical(0) and mixed datatypes such as 'data2005'.


问:
Segmentation error and free memory though no pointer used
I was trying a question to print nearest prime ASCII but no output is coming. What is the problem and how to solve it?

Code:

```<code>#include <iostream>
using namespace std;

bool isPrime(int p) {
    bool result = true;
    for (int i = 2; i <= p / 2; i++) {
        if (p%i == 0) {
            result = false;
            break;
        }
    }
    return result;
}

int goLeft(int l) {
    if (l != 65) {
        for (int i = l; i>65; i--) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int goRight(int r) {
    if (r != 122) {
        for (int i = r; i<122; i++) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int performAll(int l, int r, int p) {
    int diffLeft = 0, diffRight = 0;

    if (l == 0 && r != 0) {
        diffLeft = diffRight = r;
    }
    else if (l != 0 && r == 0) {
        diffRight = diffLeft = l;
    }
    else if (l == 0 && r == 0) {
        diffRight = diffLeft = 0;
    }
    else {
        diffLeft = p - l;
        diffRight = r - p;
    }

    if (diffLeft > diffRight) {
        return r;
    }
    else if (diffLeft < diffRight) {
        return l;
    }
    else {
        if (l<r) {
            if (l != 0) {
                return l;
            }
            else {
                return r;
            }
        }
        else if (l>r) {
            if (r != 0) {
                return r;
            }
            else {
                return l;
            }
        }
    }
return 0;
}

int main()
{
    int T, N;
    int left = 0, right = 0, ss = 0;
    cin >> T;
    string S, R;
    while (T>0) {
        cin >> N;
        cin >> S[j];

        for (int i = 0; i<N; i++) {
            cout << "i-" << i << endl;
            ss = S[i];
            if ((ss >= 65 && ss <= 90) || (ss >= 97 && ss <= 122)) {
                if (isPrime(ss)) {
                    R[i] = S[i];
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                    R[i] = performAll(left, right, ss);
                }
            }
            else {
                if (ss<65) {
                    left = 0;
                    right = 67;
                }
                else if (ss>122) {
                    left = 113;
                    right = 0;
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                }
                R[i] = performAll(left, right, ss);
            }
            cout << R[i];
        }
        T--;
    }

    return 0;
}
</code>```

Input:

```<code>1
</code>```

375
AvfmaLgLRpQadLyThsxVzkUqbFOdxfbLGdpBWOwmAnflENlYFbdhNHerHVtZkaPLgMtNQovVHpwGfHJdXXWAhYrhwXKPxtnpxCIsaXVAkcxTpVprFNeOVcnSEsgIvfqXPRSUASSDCvAGrFJCDbzGLFhrMYWALElChmurLrEeQttIWctyhQXzZUVAYuCIZecBJbXMxlMHFbZxJRTSZJmZAwCggGabVsovqBrdmmbCTaIHDfUunLFntfGzodKqoAKwCassKMDybethRaQgegsOawfNCNrIAkECEKpbwElhvWtlZBEZqJQpEkzpiSjrqZZIHbszUxwuWreXkxFKxSAiKoemIqETGVxcCjweKhbyXxhVKCbNTQBKgHD

```<code>Your Code's Output
</code>```

"Your code didn't print anything."

答:
You are trampling over the memory std::string allocates.  When you get to

```<code>cin>>S[j];
</code>```

S is empty as it was default constructed.  Trying to add data to it with operator[] is undefined behavior if the index is not valid for writing and with an empty string there is no valid writable index.

Body:
I was trying a question to print nearest prime ASCII but no output is coming. What is the problem and how to solve it?

Code:

#include <iostream>
using namespace std;

bool isPrime(int p) {
    bool result = true;
    for (int i = 2; i <= p / 2; i++) {
        if (p%i == 0) {
            result = false;
            break;
        }
    }
    return result;
}

int goLeft(int l) {
    if (l != 65) {
        for (int i = l; i>65; i--) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int goRight(int r) {
    if (r != 122) {
        for (int i = r; i<122; i++) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int performAll(int l, int r, int p) {
    int diffLeft = 0, diffRight = 0;

    if (l == 0 && r != 0) {
        diffLeft = diffRight = r;
    }
    else if (l != 0 && r == 0) {
        diffRight = diffLeft = l;
    }
    else if (l == 0 && r == 0) {
        diffRight = diffLeft = 0;
    }
    else {
        diffLeft = p - l;
        diffRight = r - p;
    }

    if (diffLeft > diffRight) {
        return r;
    }
    else if (diffLeft < diffRight) {
        return l;
    }
    else {
        if (l<r) {
            if (l != 0) {
                return l;
            }
            else {
                return r;
            }
        }
        else if (l>r) {
            if (r != 0) {
                return r;
            }
            else {
                return l;
            }
        }
    }
return 0;
}

int main()
{
    int T, N;
    int left = 0, right = 0, ss = 0;
    cin >> T;
    string S, R;
    while (T>0) {
        cin >> N;
        cin >> S[j];

        for (int i = 0; i<N; i++) {
            cout << "i-" << i << endl;
            ss = S[i];
            if ((ss >= 65 && ss <= 90) || (ss >= 97 && ss <= 122)) {
                if (isPrime(ss)) {
                    R[i] = S[i];
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                    R[i] = performAll(left, right, ss);
                }
            }
            else {
                if (ss<65) {
                    left = 0;
                    right = 67;
                }
                else if (ss>122) {
                    left = 113;
                    right = 0;
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                }
                R[i] = performAll(left, right, ss);
            }
            cout << R[i];
        }
        T--;
    }

    return 0;
}

Input:

1

375
AvfmaLgLRpQadLyThsxVzkUqbFOdxfbLGdpBWOwmAnflENlYFbdhNHerHVtZkaPLgMtNQovVHpwGfHJdXXWAhYrhwXKPxtnpxCIsaXVAkcxTpVprFNeOVcnSEsgIvfqXPRSUASSDCvAGrFJCDbzGLFhrMYWALElChmurLrEeQttIWctyhQXzZUVAYuCIZecBJbXMxlMHFbZxJRTSZJmZAwCggGabVsovqBrdmmbCTaIHDfUunLFntfGzodKqoAKwCassKMDybethRaQgegsOawfNCNrIAkECEKpbwElhvWtlZBEZqJQpEkzpiSjrqZZIHbszUxwuWreXkxFKxSAiKoemIqETGVxcCjweKhbyXxhVKCbNTQBKgHD

Your Code's Output

"Your code didn't print anything."

Body:
You are trampling over the memory std::string allocates.  When you get to

cin>>S[j];

S is empty as it was default constructed.  Trying to add data to it with operator[] is undefined behavior if the index is not valid for writing and with an empty string there is no valid writable index.


问:
What is the npm's "false" option in package.json
I noticed recently that npm sets a "false" : {} field in package.json after npm prune and npm update.

What is its purpose?

There is no such option in the npm manual https://docs.npmjs.com/misc/config

The environment is nodejs v 8.1.3 and npm v 5.0.1 under Ubuntu 17.04 and Windows Server 2012 R2.

答:
I think it was bug and you can find fix for this here in new release.

Here is fix commit.


问:
How to create modules in C
I have an interface with which I want to be able to statically link modules. For example, I want to be able to call all functions (albeit in seperate files) called FOO or that match a certain prototype, ultimately make a call into a function in the file without a header in the other files. Dont say that it is impossible since I found a hack that can do it, but I want a non hacked method. (The hack is to use nm to get functions and their prototypes then I can dynamically call the function). Also, I know you can do this with dynamic linking, however, I want to statically link the files. Any ideas?</p>

答:
This is somewhat common in writing test code.  e.g., you want to call all functions that start with test_.  So you have a shell script that grep's through all your .C files and pulls out the function names that match test_.*.  Then that script generates a test.c file that contains a function that calls all the test functions.

e.g., generated program would look like:

```<code>int main() {
   initTestCode();
   testA();
   testB();
   testC();
}
</code>```

Another way to do it would be to use some linker tricks.  This is what the Linux kernel does for its initialization.  Functions that are init code are marked with the qualifier __init.  This is defined in linux/init.h as follows:

```<code>#define __init          __section(.init.text) __cold notrace
</code>```

This causes the linker to put that function in the section .init.text.  The kernel will reclaim memory from that section after the system boots.

For calling the functions, each module will declare an initcall function with some other macros core_initcall(func), arch_initcall(func), et cetera (also defined in linux/init.h).  These macros put a pointer to the function into a linker section called .initcall.

At boot-time, the kernel will "walk" through the .initcall section calling all of the pointers there.  The code that walks through looks like this:

```<code>extern initcall_t __initcall_start[], __initcall_end[], __early_initcall_end[];

static void __init do_initcalls(void)
{
        initcall_t *fn;

        for (fn = __early_initcall_end; fn < __initcall_end; fn++)
                do_one_initcall(*fn);

        /* Make sure there is no pending stuff from the initcall sequence */
        flush_scheduled_work();
}
</code>```

The symbols __initcall_start, __initcall_end, etc. get defined in the linker script.

In general, the Linux kernel does some of the cleverest tricks with the GCC pre-processor, compiler and linker that are possible.  It's always been a great reference for C tricks.

Title: How to create modules in C

Body:
This is somewhat common in writing test code.  e.g., you want to call all functions that start with test_.  So you have a shell script that grep's through all your .C files and pulls out the function names that match test_.*.  Then that script generates a test.c file that contains a function that calls all the test functions.

e.g., generated program would look like:

int main() {
   initTestCode();
   testA();
   testB();
   testC();
}

Another way to do it would be to use some linker tricks.  This is what the Linux kernel does for its initialization.  Functions that are init code are marked with the qualifier __init.  This is defined in linux/init.h as follows:

#define __init          __section(.init.text) __cold notrace

This causes the linker to put that function in the section .init.text.  The kernel will reclaim memory from that section after the system boots.

For calling the functions, each module will declare an initcall function with some other macros core_initcall(func), arch_initcall(func), et cetera (also defined in linux/init.h).  These macros put a pointer to the function into a linker section called .initcall.

At boot-time, the kernel will "walk" through the .initcall section calling all of the pointers there.  The code that walks through looks like this:

extern initcall_t __initcall_start[], __initcall_end[], __early_initcall_end[];

static void __init do_initcalls(void)
{
        initcall_t *fn;

        for (fn = __early_initcall_end; fn < __initcall_end; fn++)
                do_one_initcall(*fn);

        /* Make sure there is no pending stuff from the initcall sequence */
        flush_scheduled_work();
}

The symbols __initcall_start, __initcall_end, etc. get defined in the linker script.

In general, the Linux kernel does some of the cleverest tricks with the GCC pre-processor, compiler and linker that are possible.  It's always been a great reference for C tricks.


问:
How to change redirect url on soundcloud?
I want to know how i can change my app' redirect url on soundcloud please.
I have been using the api for just 3 months so i'm not very familiar with all this...

Thanks for your time.

答: You'll have to get in touch with SoundCloud Support to have this changed: support@soundcloud.com.</p>


问:
Multiple if-else if statement twig
So I have an application and I want to display a planning for several users. User can select a day in a form before i display the planning.
For the week day Monday = 1 and friday = 5. I store that in my DB, user have a planning day.
So in my controller i do like this to retrieve all the users that share the same planning

```<code>$planningRepo = $this->getDoctrine()->getManager()->getRepository('OCPediBundle:Planning');
        $user = $this->getUser();
        $planningID = $user->getPlanning()->getId();
        $planning = $planningRepo->find($planningID);
        $userRepo = $this->getDoctrine()->getManager()->getRepository('OCUserBundle:User');
        $users = $userRepo->findByPlanning($planningID);
        var_dump($users);
        if (null === $planning) {
            throw new NotFoundHttpException("Le planning d'id ". $id. " n'existe pas.");
        }
        return $this->render('::planning.html.twig', array('planning' => $planning,
                                                           'users' => $users));
    }
</code>```

in my twig view :

```<code><table class="table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Lundi</th>
                        <th>Mardi</th>
                        <th>Mercredi</th>
                        <th>Jeudi</th>
                        <th>Vendredi</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th scope="row">Responsable</th>
                        {% for user in users %}
                        {{dump(user.planningday)}}
                        {% if user.planningday == 1 %}
                        <td>{{user.name}} {{user.lastname}}</td>
                        {% elseif user.planningday == 2 %}
                        <td>{{user.name}} {{user.lastname}}</td>
                        {% elseif user.planningday == 3 %}
                        <td>{{user.name}} {{user.lastname}}</td>
                        {% elseif user.planningday == 4 %}
                        <td>{{user.name}} {{user.lastname}}</td>
                        {% else %}
                        <td>{{user.name}} {{user.lastname}}</td>
                        {% endif %}
                        {% endfor %}
                    </tr>
                    <tr>
                        <th scope="row">Description</th>
                        {% for user in users %}
                        {% if user.planningday == 1%}
                        <td>{{user.planningcontent}}</td>
                       {% elseif user.planningday == 2 %}
                        <td>{{user.planningcontent}}}</td>
                        {% elseif user.planningday == 3 %}
                        <td>{{user.planningcontent}}}</td>
                        {% elseif user.planningday == 4 %}
                        <td>{{user.planningcontent}}}</td>
                        {% else %}
                        <td>{{user.planningcontent}}}</td>

                        {% endif %}
                        {% endfor %}
                    </tr>
                </tbody>
            </table>
</div>
</code>```

But there's my problem, my if statement isn't working. Example i have an user who choose the day 2 so Tuesday and the name, lastname and content are display in the monday td.
Anybody can help me ? Thanks

答:
The problem is that you print only a column inside your if.

You can divide It and print always the column

try this:

```<code>{% for user in users %}
      {{dump(user.planningday)}}
      <td>
      {% if user.planningday == 1 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 2 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 3 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 4 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 5 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
{% endfor %}
</code>```

You can use the same strategy for description row

Title: Multiple if-else if statement twig

Body:
So I have an application and I want to display a planning for several users. User can select a day in a form before i display the planning.
For the week day Monday = 1 and friday = 5. I store that in my DB, user have a planning day.
So in my controller i do like this to retrieve all the users that share the same planning

$planningRepo = $this->getDoctrine()->getManager()->getRepository('OCPediBundle:Planning');
        $user = $this->getUser();
        $planningID = $user->getPlanning()->getId();
        $planning = $planningRepo->find($planningID);
        $userRepo = $this->getDoctrine()->getManager()->getRepository('OCUserBundle:User');
        $users = $userRepo->findByPlanning($planningID);
        var_dump($users);
        if (null === $planning) {
            throw new NotFoundHttpException("Le planning d'id ". $id. " n'existe pas.");
        }
        return $this->render('::planning.html.twig', array('planning' => $planning,
                                                           'users' => $users));
    }

in my twig view :

                        #
                        Lundi
                        Mardi
                        Mercredi
                        Jeudi
                        Vendredi

                        Responsable
                        {% for user in users %}
                        {{dump(user.planningday)}}
                        {% if user.planningday == 1 %}
                        {{user.name}} {{user.lastname}}
                        {% elseif user.planningday == 2 %}
                        {{user.name}} {{user.lastname}}
                        {% elseif user.planningday == 3 %}
                        {{user.name}} {{user.lastname}}
                        {% elseif user.planningday == 4 %}
                        {{user.name}} {{user.lastname}}
                        {% else %}
                        {{user.name}} {{user.lastname}}
                        {% endif %}
                        {% endfor %}

                        Description
                        {% for user in users %}
                        {% if user.planningday == 1%}
                        {{user.planningcontent}}
                       {% elseif user.planningday == 2 %}
                        {{user.planningcontent}}}
                        {% elseif user.planningday == 3 %}
                        {{user.planningcontent}}}
                        {% elseif user.planningday == 4 %}
                        {{user.planningcontent}}}
                        {% else %}
                        {{user.planningcontent}}}

                        {% endif %}
                        {% endfor %}

But there's my problem, my if statement isn't working. Example i have an user who choose the day 2 so Tuesday and the name, lastname and content are display in the monday td.
Anybody can help me ? Thanks

Body:
The problem is that you print only a column inside your if.

You can divide It and print always the column

try this:

{% for user in users %}
      {{dump(user.planningday)}}
      <td>
      {% if user.planningday == 1 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 2 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 3 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 4 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
      <td>
      {% if user.planningday == 5 %}
          {{user.name}} {{user.lastname}}
      {% endif %}
      </td>
{% endfor %}

You can use the same strategy for description row


问:
window.alert occuring twice with canvas collision
For a canvas game I am in the process of making,

the collision condition I currently have means that a window.alert will be displayed in the browser window. However, due to the nature of the collision (too quick?) this window.alert appears twice, requiring 'OK' to be pressed a total of two times with the two alerts.

I have tried delaying the alert function using setTimeout/setInterval but this results in no change. This must be due to how much the sprites overlap when colliding?

Below is my collision condition, and my window alert I wish to be displayed only once after it occurs (so the game can be reset). How could I alter this to prevent more than one window.alert each time?

```<code>         if (x < object.x && x + width > object.x &&
         y < object.y + 60 && height + y > object.y + 60) {

        setTimeout(function() {
        window.alert("You lose");
        location.reload();
        }, 100);
    }
</code>```

答:
Use setTimeout instead of setInterval.

setTimeout occurs only once, setInterval is infinite.

Body:
For a canvas game I am in the process of making,

the collision condition I currently have means that a window.alert will be displayed in the browser window. However, due to the nature of the collision (too quick?) this window.alert appears twice, requiring 'OK' to be pressed a total of two times with the two alerts.

I have tried delaying the alert function using setTimeout/setInterval but this results in no change. This must be due to how much the sprites overlap when colliding?

Below is my collision condition, and my window alert I wish to be displayed only once after it occurs (so the game can be reset). How could I alter this to prevent more than one window.alert each time?

         if (x < object.x && x + width > object.x &&
         y < object.y + 60 && height + y > object.y + 60) {

        setTimeout(function() {
        window.alert("You lose");
        location.reload();
        }, 100);
    }


问:
pymysql incorrect writes to the database the Russian text
I had the following problem: is There a site encoded in windows-1251. I'm using the library BeautifulSoup to get the data you need in Russian language. For testing recorded the values in the file, they are displayed correctly. Then I tried to record this data to the database, but got this error: Warning: (1366, "Incorrect string value: '\\x98\\xD0\\xBD\\xD1\\x82\\xD0...' for column 'description' at row 1")
The database encoding is utf-8.
Below code demonstrates how to read html file:

```<code>def get_html(url):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
return response.read()
</code>```

The code below demonstrates how to write values to the database:

```<code>def write_to_db(chars, desc):
    conn = pymysql.connect(host='localhost',
        port=3307,
        user='****',
        password='****',
        db='****',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)

global _id
with conn.cursor() as cursor:
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)"
    cursor.execute(sql, (_id, chars, desc))
conn.commit()
</code>```

In the end we get in the database the following characters:РњРѕРґРµР»СЊ

How can I overcome this problem?

答:
When I tried to change the encoding of the whole html file to utf8, I got an error that some characters can not be decoded. And in the way presented below, we have already received the Russian text without unnecessary symbols and can calmly decode it</p>

```<code>with conn.cursor() as cursor:
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)"
    cursor.execute(sql, (_id, chars.encode('utf8'), desc.encode('utf8')))
conn.commit()
</code>```

Body:
I had the following problem: is There a site encoded in windows-1251. I'm using the library BeautifulSoup to get the data you need in Russian language. For testing recorded the values in the file, they are displayed correctly. Then I tried to record this data to the database, but got this error: Warning: (1366, "Incorrect string value: '\\x98\\xD0\\xBD\\xD1\\x82\\xD0...' for column 'description' at row 1")
The database encoding is utf-8.
Below code demonstrates how to read html file:

def get_html(url):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
return response.read()

The code below demonstrates how to write values to the database:

def write_to_db(chars, desc):
    conn = pymysql.connect(host='localhost',
        port=3307,
        user='****',
        password='****',
        db='****',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)

global _id
with conn.cursor() as cursor:
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)"
    cursor.execute(sql, (_id, chars, desc))
conn.commit()

In the end we get in the database the following characters:РњРѕРґРµР»СЊ

How can I overcome this problem?

Body:
When I tried to change the encoding of the whole html file to utf8, I got an error that some characters can not be decoded. And in the way presented below, we have already received the Russian text without unnecessary symbols and can calmly decode it

with conn.cursor() as cursor:
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)"
    cursor.execute(sql, (_id, chars.encode('utf8'), desc.encode('utf8')))
conn.commit()


问:
Get selected subcommand with argparse
When I use subcommands with python argparse, I can get the selected arguments.

```<code>parser = argparse.ArgumentParser()
parser.add_argument('-g', '--global')
subparsers = parser.add_subparsers()
foo_parser = subparsers.add_parser('foo')
foo_parser.add_argument('-c', '--count')
bar_parser = subparsers.add_parser('bar')
args = parser.parse_args(['-g', 'xyz', 'foo', '--count', '42'])
# args => Namespace(global='xyz', count='42')
</code>```

So args doesn't contain 'foo'.  Simply writing sys.argv[1] doesn't work because of the possible global args. How can I get the subcommand itself?

答:
ArgumentParser.add_subparsers has dest formal argument described as:

dest - name of the attribute under which sub-command name will be stored; by default None and no value is stored

In the example below of a simple task function layout using subparsers, the selected subparser is in parser.parse_args().subparser.

```<code>import argparse

def task_a(alpha):
    print('task a', alpha)

def task_b(beta, gamma):
    print('task b', beta, gamma)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subparser')

    parser_a = subparsers.add_parser('task_a')
    parser_a.add_argument(
        '-a', '--alpha', dest='alpha', help='Alpha description')

    parser_b = subparsers.add_parser('task_b')
    parser_b.add_argument(
        '-b', '--beta', dest='beta', help='Beta description')
    parser_b.add_argument(
        '-g', '--gamma', dest='gamma', default=42, help='Gamma description')

    kwargs = vars(parser.parse_args())
    globals()[kwargs.pop('subparser')](**kwargs)
</code>```

Title: Get selected subcommand with argparse

Body:
When I use subcommands with python argparse, I can get the selected arguments.

parser = argparse.ArgumentParser()
parser.add_argument('-g', '--global')
subparsers = parser.add_subparsers()
foo_parser = subparsers.add_parser('foo')
foo_parser.add_argument('-c', '--count')
bar_parser = subparsers.add_parser('bar')
args = parser.parse_args(['-g', 'xyz', 'foo', '--count', '42'])
# args => Namespace(global='xyz', count='42')

So args doesn't contain 'foo'.  Simply writing sys.argv[1] doesn't work because of the possible global args. How can I get the subcommand itself?

Body:
ArgumentParser.add_subparsers has dest formal argument described as:

dest - name of the attribute under which sub-command name will be stored; by default None and no value is stored

In the example below of a simple task function layout using subparsers, the selected subparser is in parser.parse_args().subparser.

import argparse

def task_a(alpha):
    print('task a', alpha)

def task_b(beta, gamma):
    print('task b', beta, gamma)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subparser')

    parser_a = subparsers.add_parser('task_a')
    parser_a.add_argument(
        '-a', '--alpha', dest='alpha', help='Alpha description')

    parser_b = subparsers.add_parser('task_b')
    parser_b.add_argument(
        '-b', '--beta', dest='beta', help='Beta description')
    parser_b.add_argument(
        '-g', '--gamma', dest='gamma', default=42, help='Gamma description')

    kwargs = vars(parser.parse_args())
    globals()[kwargs.pop('subparser')](**kwargs)