问:
Removing selected node from xml file
I am trying to make some music library app for my classes. I've done pretty much everything i had to but there is one thing left. I don't know how to access data from data template generated item to delete both this item form app and xml node from xml file.

I have found this bit of code that should delete the node i want but i still don't know how to access data from item that i selected.

```<code>private void DeleteFromFile_Click(object sender, RoutedEventArgs e)
    {
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(@"musicLibrary.xml");
        foreach(XmlNode xNode in xDoc.SelectNodes("musicLibrary"))
        {
            if(xNode.SelectSingleNode("title").InnerText == "")
            {
                xNode.ParentNode.RemoveChild(xNode);
            }
        }
    }
</code>```

the nodes looks like this:

```<code>  <musicLibrary>
<title>I Still Haven't Found What I'm Looking For</title>
<albumName>The Joshua Tree</albumName>
<artist>U2</artist>
<releaseDate>1987</releaseDate>
<tempo>101</tempo>
<duration>4:37</duration>
<genre>Rock</genre>
  </musicLibrary>
  <musicLibrary>
<title>Magnificent</title>
<albumName>No Line on the Horizon</albumName>
<artist>U2</artist>
<releaseDate>2009</releaseDate>
<tempo>115</tempo>
<duration>5:24</duration>
<genre>Rock</genre>
  </musicLibrary>
</code>```

data templates that i use:

```<code><Page.Resources>
    <CollectionViewSource x:Key="listDataView"/>
    <DataTemplate x:Key="mDataTamplate">
        <StackPanel>
            <TextBlock FontSize="12" Margin="5" Text="{Binding title}" />
            <TextBlock FontSize="10" Margin="5" Text="{Binding artist}"/>
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="detailedDataTamplate">
        <Grid  Grid.Row="3" Margin="20,0,20,0">
            <!-- Row/Column Definition-->
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.7*"/>
                <ColumnDefinition Width="1.5*"/>
                <ColumnDefinition Width="0.7*"/>
                <ColumnDefinition Width="0.7*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <!-- First Column -->
            <TextBlock Grid.Column="0" Grid.Row="0" Text="Title" Style="{StaticResource textBlockStyle}" />
            <TextBlock         Text="{Binding title}"
                               Grid.Column="1" Grid.Row="0"
                               Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="0" Grid.Row="1" Text="Album name" Style="{StaticResource textBlockStyle}"/>
            <TextBlock         Text="{Binding albumName}"
                               Grid.Column="1" Grid.Row="1"
                               Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="0" Grid.Row="2" Text="Artist" Style="{StaticResource textBlockStyle}"/>
            <TextBlock         Text="{Binding artist}"
                               Grid.Column="1" Grid.Row="2"
                               Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="0" Grid.Row="3" Text="Release Date" Style="{StaticResource textBlockStyle}"/>
            <TextBlock         Text="{Binding releaseDate}"
                               Grid.Column="1" Grid.Row="3"
                               Style="{StaticResource textBlockStyle}"/>
            <!-- Second Column -->
            <TextBlock Grid.Column="2" Grid.Row="0" Text="Tempo" Style="{StaticResource textBlockStyle}" />
            <TextBlock Text="{Binding tempo}"
                                Grid.Column="3" Grid.Row="0"
                                Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="2" Grid.Row="1" Text="Duration" Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="3" Grid.Row="1"
                       Text="{Binding duration}"
                       Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="2" Grid.Row="2" Text="Genre" Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="3" Grid.Row="2"
                       Text="{Binding genre}"
                       Style="{StaticResource textBlockStyle}"/>

            <Button x:Name="saveToFile" Click="saveToFile_Click" Content="Save to file"  Grid.Column="2" Grid.Row="3" Grid.ColumnSpan="1" VerticalAlignment="Center"  Height="31"/>
            <Button x:Name="deleteFromFile" Click="DeleteFromFile_Click" Content="Delete" Grid.Column="3" Grid.Row="3"/>
        </Grid>
    </DataTemplate>
</Page.Resources>
</code>```

And class that i bind data from:

```<code>namespace MLUI
 {
[XmlRoot("dataSet")]
public class DataSet
{
    [XmlElement("musicLibrary")]
    public List<Song> Songs { get; set; }
}
public class Song
{
    [XmlElement("title")]
    public string title { get; set; }
    [XmlElement("artist")]
    public string artist { get; set; }
    [XmlElement("albumName")]
    public string albumName { get; set; }
    [XmlElement("releaseDate")]
    public string releaseDate { get; set; }
    [XmlElement("tempo")]
    public int tempo { get; set; }
    [XmlElement("duration")]
    public string duration { get; set; }
    [XmlElement("genre")]
    public string genre { get; set; }
    public override string ToString()
    {
        return "Title:  " + title +"\r\nArtist:  "+ artist +"\r\nAlbum Name:  "+ albumName + "\r\nRelease Date:  " + releaseDate +
            "\r\nTempo  "+ tempo + "\r\nDuration  " + duration + "\r\nGenre  " + genre ;
    }
}
}
</code>```

答:
I like using Xml Linq with a dictionary :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement dataSet = doc.Root;

            Dictionary<string, XElement> dictionary = dataSet.Elements("musicLibrary")
                .GroupBy(x => (string)x.Element("title"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            XElement Magnificent = dictionary["Magnificent"];

            Magnificent.Remove();
        }
    }
}
</code>```

Title: Removing selected node from xml file

Body:
I am trying to make some music library app for my classes. I've done pretty much everything i had to but there is one thing left. I don't know how to access data from data template generated item to delete both this item form app and xml node from xml file.

I have found this bit of code that should delete the node i want but i still don't know how to access data from item that i selected.

private void DeleteFromFile_Click(object sender, RoutedEventArgs e)
    {
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(@"musicLibrary.xml");
        foreach(XmlNode xNode in xDoc.SelectNodes("musicLibrary"))
        {
            if(xNode.SelectSingleNode("title").InnerText == "")
            {
                xNode.ParentNode.RemoveChild(xNode);
            }
        }
    }

the nodes looks like this:

  <musicLibrary>
<title>I Still Haven't Found What I'm Looking For</title>
<albumName>The Joshua Tree</albumName>
<artist>U2</artist>
<releaseDate>1987</releaseDate>
<tempo>101</tempo>
<duration>4:37</duration>
<genre>Rock</genre>
  </musicLibrary>
  <musicLibrary>
<title>Magnificent</title>
<albumName>No Line on the Horizon</albumName>
<artist>U2</artist>
<releaseDate>2009</releaseDate>
<tempo>115</tempo>
<duration>5:24</duration>
<genre>Rock</genre>
  </musicLibrary>

data templates that i use:

<Page.Resources>
    <CollectionViewSource x:Key="listDataView"/>
    <DataTemplate x:Key="mDataTamplate">
        <StackPanel>
            <TextBlock FontSize="12" Margin="5" Text="{Binding title}" />
            <TextBlock FontSize="10" Margin="5" Text="{Binding artist}"/>
        </StackPanel>
    </DataTemplate>
    <DataTemplate x:Key="detailedDataTamplate">
        <Grid  Grid.Row="3" Margin="20,0,20,0">

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.7*"/>
                <ColumnDefinition Width="1.5*"/>
                <ColumnDefinition Width="0.7*"/>
                <ColumnDefinition Width="0.7*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Column="0" Grid.Row="0" Text="Title" Style="{StaticResource textBlockStyle}" />
            <TextBlock         Text="{Binding title}"
                               Grid.Column="1" Grid.Row="0"
                               Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="0" Grid.Row="1" Text="Album name" Style="{StaticResource textBlockStyle}"/>
            <TextBlock         Text="{Binding albumName}"
                               Grid.Column="1" Grid.Row="1"
                               Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="0" Grid.Row="2" Text="Artist" Style="{StaticResource textBlockStyle}"/>
            <TextBlock         Text="{Binding artist}"
                               Grid.Column="1" Grid.Row="2"
                               Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="0" Grid.Row="3" Text="Release Date" Style="{StaticResource textBlockStyle}"/>
            <TextBlock         Text="{Binding releaseDate}"
                               Grid.Column="1" Grid.Row="3"
                               Style="{StaticResource textBlockStyle}"/>

            <TextBlock Grid.Column="2" Grid.Row="0" Text="Tempo" Style="{StaticResource textBlockStyle}" />
            <TextBlock Text="{Binding tempo}"
                                Grid.Column="3" Grid.Row="0"
                                Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="2" Grid.Row="1" Text="Duration" Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="3" Grid.Row="1"
                       Text="{Binding duration}"
                       Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="2" Grid.Row="2" Text="Genre" Style="{StaticResource textBlockStyle}"/>
            <TextBlock Grid.Column="3" Grid.Row="2"
                       Text="{Binding genre}"
                       Style="{StaticResource textBlockStyle}"/>

            <Button x:Name="saveToFile" Click="saveToFile_Click" Content="Save to file"  Grid.Column="2" Grid.Row="3" Grid.ColumnSpan="1" VerticalAlignment="Center"  Height="31"/>
            <Button x:Name="deleteFromFile" Click="DeleteFromFile_Click" Content="Delete" Grid.Column="3" Grid.Row="3"/>
        </Grid>
    </DataTemplate>
</Page.Resources>

And class that i bind data from:

namespace MLUI
 {
[XmlRoot("dataSet")]
public class DataSet
{
    [XmlElement("musicLibrary")]
    public List<Song> Songs { get; set; }
}
public class Song
{
    [XmlElement("title")]
    public string title { get; set; }
    [XmlElement("artist")]
    public string artist { get; set; }
    [XmlElement("albumName")]
    public string albumName { get; set; }
    [XmlElement("releaseDate")]
    public string releaseDate { get; set; }
    [XmlElement("tempo")]
    public int tempo { get; set; }
    [XmlElement("duration")]
    public string duration { get; set; }
    [XmlElement("genre")]
    public string genre { get; set; }
    public override string ToString()
    {
        return "Title:  " + title +"\r\nArtist:  "+ artist +"\r\nAlbum Name:  "+ albumName + "\r\nRelease Date:  " + releaseDate +
            "\r\nTempo  "+ tempo + "\r\nDuration  " + duration + "\r\nGenre  " + genre ;
    }
}
}

Body:
I like using Xml Linq with a dictionary :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement dataSet = doc.Root;

            Dictionary<string, XElement> dictionary = dataSet.Elements("musicLibrary")
                .GroupBy(x => (string)x.Element("title"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            XElement Magnificent = dictionary["Magnificent"];

            Magnificent.Remove();
        }
    }
}


来源: stackexchange

问:
Cocoa-Touch internals: How does the view know its controller?
If you add a subview to a view or add a view to a window, how does iOS know which controller this view belongs too?

Easy example:
Have a UIView without UIViewController and add it to the window [window addSubView:myView] --> it will not rotate.
Now use a UIViewController, have it implement shouldAutoRotateToInterfaceOrientation: and add the controller's view to the window: [window addSubView:myController.view] --> magically, the view will adjust to interface orientation.

But look at the code: in both cases a UIView was added. How can iOS possibly be aware that in the second case a UIViewController was involved?

I'm interested in how this is done internally. My best guess is that UIViewController.view is a setter which adds the controller to an internal array of controllers or assigns itself to some internal variable which holds the currently active controller.

答:
Dave DeLong is correct (and gets +1) as it is clearly defined UIView.h as @package so anything in UIKit can access it.

Here is an example of accessing that variable for educational purposes only (obviously you will not do this in a real application).

SomeAppDelegate.m

```<code>@synthesize navigationController=_navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Add the navigation controller's view to the window and display.
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];

    //DO NOT TRY THIS AT HOME
    UIView *mynavview = self.navigationController.view;
    //Guaranteed _viewDelegate atleast in iOS 4.3
    Ivar ivar = class_getInstanceVariable([UIView class], "_viewDelegate");
    UIViewController *controller = object_getIvar(mynavview, ivar);
    NSLog(@"controller = self.navigationController? %@", controller == self.navigationController ? @"Yes" : @"No");

    return YES;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Dave DeLong is correct (and gets +1) as it is clearly defined UIView.h as @package so anything in UIKit can access it.

Here is an example of accessing that variable for educational purposes only (obviously you will not do this in a real application).

SomeAppDelegate.m

@synthesize navigationController=_navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Add the navigation controller's view to the window and display.
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];

    //DO NOT TRY THIS AT HOME
    UIView *mynavview = self.navigationController.view;
    //Guaranteed _viewDelegate atleast in iOS 4.3
    Ivar ivar = class_getInstanceVariable([UIView class], "_viewDelegate");
    UIViewController *controller = object_getIvar(mynavview, ivar);
    NSLog(@"controller = self.navigationController? %@", controller == self.navigationController ? @"Yes" : @"No");

    return YES;
}


问:
Can you tell me what's wrong in the query I'm using to retrieve info on when a customer last placed an order?
I'm trying to write a query on MySQL workbench that shows me when a customer last ordered from my client's website. I'm using two tables for this purpose. One is called "orders", which is updated with order time whenever a new order is placed and assigns a unique id to each new order. The other table is called "orders_customers_details", which is also updated whenever a new order is placed and contains the unique id (based on a combination of customer's email address and phone number) of the customer placing the order, as well as a key which corresponds to the orders table's id.

My problem is that the query I'm using is not returning every customer's most recent order. In the case of some customers, I'm being given the date of their fourth or fifth most recent order.

I'm left joining orders on orders_customer_details:

```<code>left join orders o
on ocd.id = o.customer_details_id
</code>```

I've also tried using a left outer join, and the following join:

```<code>from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
</code>```

In order to retrieve the most recent order only, I'm grouping by customer_id HAVING max(order.id). FYI, order.id increases with the placement of each new order, so the order with the highest id is the most recent order.

I've also tried

```<code> SELECT customer_id, MAX(order.id)
</code>```

and then grouped by customer_id, but to no avail.

Here's the entire code:

```<code>select customer_id, o.id as id_of_last_order, date(order_date) as
last_ordered, timestampdiff(day, order_date, now()) as
days_since_last_ordered
from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
group by customer_id having max(o.id)
order by customer_id;
</code>```

答:
A typical method in MySQL is to use a correlated subquery to get the most recent order:

```<code>select ocd.customer_id, o.id as id_of_last_order,
       date(o.order_date) as last_ordered,
       timestampdiff(day, o.order_date, now()) as days_since_last_ordered
from orders o join
     orders_customers_details ocd
     on o.customer_details_id = ocd.id
where o.order_date = (select max(o2.order_date)
                      from orders o2 join
                           orders_customers_details ocd2
                           on o2.customer_details_id = ocd2.id
                      where oc2.customer_id = ocd.customer_id
                     )
order by ocd.customer_id;
</code>```

Of course, if o.id is an auto-incrementing column, then the largest value is from the most recent date.  If this is the case, then you can just use aggregation:

```<code>select ocd.customer_id,
       max(o.id) as id_of_last_order,
       date(max(o.order_date)) as last_ordered,
       timestampdiff(day, max(o.order_date), now()) as days_since_last_ordered
from orders o join
     orders_customers_details ocd
     on o.customer_details_id = ocd.id
group by ocd.customer_id
order by ocd.customer_id;
</code>```

In MySQL 8+, you would simply use window functions:

```<code>select *
from (select ocd.customer_id, o.id as id_of_last_order,
             date(o.order_date) as last_ordered,
             timestampdiff(day, o.order_date, now()) as days_since_last_ordered,
             row_number() over (partition by ocd.customer_id order by o.order_date desc) as seqnum
      from orders o join
           orders_customers_details ocd
           on o.customer_details_id = ocd.id
     ) ocd
where seqnum = 1
order by ocd.customer_id;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a query on MySQL workbench that shows me when a customer last ordered from my client's website. I'm using two tables for this purpose. One is called "orders", which is updated with order time whenever a new order is placed and assigns a unique id to each new order. The other table is called "orders_customers_details", which is also updated whenever a new order is placed and contains the unique id (based on a combination of customer's email address and phone number) of the customer placing the order, as well as a key which corresponds to the orders table's id.

My problem is that the query I'm using is not returning every customer's most recent order. In the case of some customers, I'm being given the date of their fourth or fifth most recent order.

I'm left joining orders on orders_customer_details:

left join orders o
on ocd.id = o.customer_details_id

I've also tried using a left outer join, and the following join:

from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id

In order to retrieve the most recent order only, I'm grouping by customer_id HAVING max(order.id). FYI, order.id increases with the placement of each new order, so the order with the highest id is the most recent order.

I've also tried

 SELECT customer_id, MAX(order.id)

and then grouped by customer_id, but to no avail.

Here's the entire code:

select customer_id, o.id as id_of_last_order, date(order_date) as
last_ordered, timestampdiff(day, order_date, now()) as
days_since_last_ordered
from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
group by customer_id having max(o.id)
order by customer_id;

Body:
A typical method in MySQL is to use a correlated subquery to get the most recent order:

select ocd.customer_id, o.id as id_of_last_order,
       date(o.order_date) as last_ordered,
       timestampdiff(day, o.order_date, now()) as days_since_last_ordered
from orders o join
     orders_customers_details ocd
     on o.customer_details_id = ocd.id
where o.order_date = (select max(o2.order_date)
                      from orders o2 join
                           orders_customers_details ocd2
                           on o2.customer_details_id = ocd2.id
                      where oc2.customer_id = ocd.customer_id
                     )
order by ocd.customer_id;

Of course, if o.id is an auto-incrementing column, then the largest value is from the most recent date.  If this is the case, then you can just use aggregation:

select ocd.customer_id,
       max(o.id) as id_of_last_order,
       date(max(o.order_date)) as last_ordered,
       timestampdiff(day, max(o.order_date), now()) as days_since_last_ordered
from orders o join
     orders_customers_details ocd
     on o.customer_details_id = ocd.id
group by ocd.customer_id
order by ocd.customer_id;

In MySQL 8+, you would simply use window functions:

select *
from (select ocd.customer_id, o.id as id_of_last_order,
             date(o.order_date) as last_ordered,
             timestampdiff(day, o.order_date, now()) as days_since_last_ordered,
             row_number() over (partition by ocd.customer_id order by o.order_date desc) as seqnum
      from orders o join
           orders_customers_details ocd
           on o.customer_details_id = ocd.id
     ) ocd
where seqnum = 1
order by ocd.customer_id;


问:
Python: Getting all pairs and frequency of pairs in multi-dimensional list
my multi-dimensional list looks as follows:

```<code>    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]
</code>```

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

```<code>    fr_list = [[12,13],[12,13],[28,29],[34,35]]
</code>```

I wrote the following code to find the pairs

```<code>    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]
</code>```

Then, I tried this:

```<code>    fr_list = [find_pairs(mylist,1) for x in mylist]
</code>```

However, I get the following error message:

```<code>    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'
</code>```

Can anybody help me out? Thanks.

答:
You probably should use sorting to avoid comparing each pair with all other pairs, and collections Counter to aggregate the results:

Maybe something like this:

```<code>from collections import Counter

def find_pairs(seq):
    s = sorted(seq)
    all_pairs = []
    for first, second in zip(s[:-1], s[1:]):
        if second - first == 1:
            all_pairs.append((first, second))
    return all_pairs

mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]

all_pairs = []
for seq in mylist:
    all_pairs += find_pairs(seq)
res = []
for pair, qtty in sorted([(k, v) for k, v in Counter(all_pairs).items()], key=lambda x: x[1])[::-1]:
    for _ in range(qtty):
        res.append(pair)

res
</code>```

output:

```<code>[(12, 13), (12, 13), (5, 6), (28, 29), (34, 35)]
</code>```

Body:
my multi-dimensional list looks as follows:

    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

    fr_list = [[12,13],[12,13],[28,29],[34,35]]

I wrote the following code to find the pairs

    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]

Then, I tried this:

    fr_list = [find_pairs(mylist,1) for x in mylist]

However, I get the following error message:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'

Can anybody help me out? Thanks.

Body:
You probably should use sorting to avoid comparing each pair with all other pairs, and collections Counter to aggregate the results:

Maybe something like this:

from collections import Counter

def find_pairs(seq):
    s = sorted(seq)
    all_pairs = []
    for first, second in zip(s[:-1], s[1:]):
        if second - first == 1:
            all_pairs.append((first, second))
    return all_pairs

mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]

all_pairs = []
for seq in mylist:
    all_pairs += find_pairs(seq)
res = []
for pair, qtty in sorted([(k, v) for k, v in Counter(all_pairs).items()], key=lambda x: x[1])[::-1]:
    for _ in range(qtty):
        res.append(pair)

res

output:

[(12, 13), (12, 13), (5, 6), (28, 29), (34, 35)]


问:
Laravel Routing to controller actions
I've been trying for a while now to get laravel to route to my controller actions.
I'm not sure of the best way to do this in the laravel framework.

How im picturing it in my head is like this.

I have a route setup to link to my controllers actions. so when i type domain.com/Home/Profile
It will call the HomeController's profile action. which will do some processing and display the view on the page. ( like mvc4)

I may be going about this the wrong way but im just trying to avoid making a route for every view. I'm more after the correct method to this problem or whatever laravel devs do as a standard practice because it just feels strange to have a route for every view.

So far this is my code: routes.php

```<code>Route::get('/', 'HomeController@index');

Route::any('/{controller}/{action?}', function ($controller, $action = 'index')
{
    $class = $controller.'Controller';
    $controller = new $class()

    return $controller->{$action}();

});
</code>```

HomeController:

```<code>class HomeController extends BaseController
{
    protected $layout = 'layouts.master';

    public function index()
    {
        $this->layout->content = View::make('index');
        return View::make('index');
    }

    public function profile()
    {
        $this->layout->content = View::make('profile');
    }
}
</code>```

Thanks for any help in advance.

答:
this code worked for me

$api->any('order_manage/{action?}', function ($action = 'index'){
        $app = app();
        $namespace = 'App\Http\Controllers';
        $controller = $app->make($namespace.'\ProjectOrderController');
        return $controller->callAction($action,[request()]);
    });```

Title: Laravel Routing to controller actions

Body:
I've been trying for a while now to get laravel to route to my controller actions.
I'm not sure of the best way to do this in the laravel framework.

How im picturing it in my head is like this.

I have a route setup to link to my controllers actions. so when i type domain.com/Home/Profile
It will call the HomeController's profile action. which will do some processing and display the view on the page. ( like mvc4)

I may be going about this the wrong way but im just trying to avoid making a route for every view. I'm more after the correct method to this problem or whatever laravel devs do as a standard practice because it just feels strange to have a route for every view.

So far this is my code: routes.php

Route::get('/', 'HomeController@index');

Route::any('/{controller}/{action?}', function ($controller, $action = 'index')
{
    $class = $controller.'Controller';
    $controller = new $class()

    return $controller->{$action}();

});

HomeController:

class HomeController extends BaseController
{
    protected $layout = 'layouts.master';

    public function index()
    {
        $this->layout->content = View::make('index');
        return View::make('index');
    }

    public function profile()
    {
        $this->layout->content = View::make('profile');
    }
}

Thanks for any help in advance.


问:
How to multiply the model coefficients by a number?
Hello I would like to scale the coefficients of my model. That's why I have prepared this little example.
I would like to multiply the coefficients of MPG.city, MPG.highway, Horsepower with the "correction factor". Any Ideas how to multiply or correct the coefficients?

```<code>library(MASS)
data("Cars93")

Cars_new = Cars93[,c(4,5,6,7,8,13,14)]
fit<-lm(Price~.,data=Cars_new)

#model output should be list
fit<-list(fit)

#correction factor for MPG.city, MPG.highway,Horsepower
correction<-c(1.2,1.23,1.6)
</code>```

EDIT
model output is a list!

答:
You can select the coefficients by name</p>

```<code>fit[[1]]$coefficients[c("MPG.city", "MPG.highway", "Horsepower")] <-
   fit[[1]]$coefficients[c("MPG.city", "MPG.highway", "Horsepower")] * correction

#[[1]]

#Call:
#lm(formula = Price ~ ., data = Cars_new)

#Coefficients:
#(Intercept)    Min.Price    Max.Price     MPG.city  MPG.highway   Horsepower      RPM
# -2.424e-02    5.010e-01    4.999e-01   -1.639e-04    1.029e-03   -1.504e-04   -1.293e-07
</code>```

Body:
Hello I would like to scale the coefficients of my model. That's why I have prepared this little example.
I would like to multiply the coefficients of MPG.city, MPG.highway, Horsepower with the "correction factor". Any Ideas how to multiply or correct the coefficients?

library(MASS)
data("Cars93")

Cars_new = Cars93[,c(4,5,6,7,8,13,14)]
fit<-lm(Price~.,data=Cars_new)

#model output should be list
fit<-list(fit)

#correction factor for MPG.city, MPG.highway,Horsepower
correction<-c(1.2,1.23,1.6)

EDIT
model output is a list!

Body:
You can select the coefficients by name

fit[[1]]$coefficients[c("MPG.city", "MPG.highway", "Horsepower")] <-
   fit[[1]]$coefficients[c("MPG.city", "MPG.highway", "Horsepower")] * correction

#[[1]]

#Call:
#lm(formula = Price ~ ., data = Cars_new)

#Coefficients:
#(Intercept)    Min.Price    Max.Price     MPG.city  MPG.highway   Horsepower      RPM
# -2.424e-02    5.010e-01    4.999e-01   -1.639e-04    1.029e-03   -1.504e-04   -1.293e-07


问:
How to change the objects of an array based on objects of another array
I encountered the following problem. I want to do the following, there is an array of 5 elements, I want to add a property and isExist to the elements of the array that are contained in the second, otherwise leave the object unchanged.

I tried to use the map method, but it returns an array of arrays to me, and I need to return the same array, only with the additional property of the first 2 objects.

```<code>const arr1 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}, {id: 3, title:'test3'},{id: 4, title:'test4'} ,{id: 5, title:'test5'}];
const arr2 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}];

const filteredArr = arr1.filter(item => {
    return arr2.filter(item2 => {
        if (item2.id === item.id) {
            return {...item, isExist: true}
        } else {
            return {...item}
        }
    })
})
</code>```

Expected result: in the first array the objects with ID 1 and 2 should contain additionally the isExist property, the rest should remain in the array, but without the isExist property.

答:
One option is to use Set to get all the ids on arr2. Use map to loop thru the arr1

const arr1 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"},{"id":3,"title":"test3"},{"id":4,"title":"test4"},{"id":5,"title":"test5"}]
const arr2 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"}]

const ids = new Set(arr2.map(o => o.id));
const filteredArr = arr1.map(item => {
  if (ids.has(item.id)) return { ...item,isExist: true}
  else return item;
})

console.log(filteredArr)```
</div>
</div>
</p>

<p><strong>Shorter version:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr1 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"},{"id":3,"title":"test3"},{"id":4,"title":"test4"},{"id":5,"title":"test5"}];
const arr2 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"}];

const ids = new Set(arr2.map(o => o.id));
const filteredArr = arr1.map(item => ids.has(item.id) ? {...item,isExist: true} : item);

console.log(filteredArr)</code>```

Body:
I encountered the following problem. I want to do the following, there is an array of 5 elements, I want to add a property and isExist to the elements of the array that are contained in the second, otherwise leave the object unchanged.

I tried to use the map method, but it returns an array of arrays to me, and I need to return the same array, only with the additional property of the first 2 objects.

const arr1 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}, {id: 3, title:'test3'},{id: 4, title:'test4'} ,{id: 5, title:'test5'}];
const arr2 = [{id: 1, title:'test1'}, {id: 2, title:'test2'}];

const filteredArr = arr1.filter(item => {
    return arr2.filter(item2 => {
        if (item2.id === item.id) {
            return {...item, isExist: true}
        } else {
            return {...item}
        }
    })
})

Expected result: in the first array the objects with ID 1 and 2 should contain additionally the isExist property, the rest should remain in the array, but without the isExist property.

Body:
One option is to use Set to get all the ids on arr2. Use map to loop thru the arr1

const arr1 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"},{"id":3,"title":"test3"},{"id":4,"title":"test4"},{"id":5,"title":"test5"}]
const arr2 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"}]

const ids = new Set(arr2.map(o => o.id));
const filteredArr = arr1.map(item => {
  if (ids.has(item.id)) return { ...item,isExist: true}
  else return item;
})

console.log(filteredArr)

Shorter version:

const arr1 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"},{"id":3,"title":"test3"},{"id":4,"title":"test4"},{"id":5,"title":"test5"}];
const arr2 = [{"id":1,"title":"test1"},{"id":2,"title":"test2"}];

const ids = new Set(arr2.map(o => o.id));
const filteredArr = arr1.map(item => ids.has(item.id) ? {...item,isExist: true} : item);

console.log(filteredArr)


问:
Table does not render (Yajra Datatables)
So, this is my controller:

```<code>use Yajra\DataTables\Facades\DataTables;
class CategoriasController extends Controller
{
    public function index()
    {
        return Datatables::collection(Categoria::all())->make(true);
    }
 [...]
}
</code>```

this is my route:

```<code>Route::group(['middleware' => 'auth'], function () {
    Route::group(['middleware' => 'admin'], function () {
        Route::prefix('admin')->namespace('Admin')->group(function () {
            Route::prefix('categorias')->group(function(){
                Route::get('/', 'CategoriasController@index')->name('curso.index');
[...]
             });
         });
     });
});
</code>```

and this is my blade:

```<code>[...]
<div class="container">
    <table class="table border" id="myTable">
        <thead>
            <tr>
                <th>id</th>
                <th>Nome</th>
                <th>Criado</th>
                <th>Modificado</th>
            </tr>
        </thead>
    </table>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready( function () {
    $('#myTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{!! route('categoria.index') !!}',
        columns: [
                { data: 'id', name:'id'},
                { data: 'nome', name:'nome'},
                { data: 'created_at', name:'created_at'},
                { data: 'updated_at', name:'updated_at'},
            ]
    });
} );
</script>
[...]
</code>```

And I got this as a return:

I'm using Laravel 5.8.19

composer.json

```<code>[...]
"require":{
        "yajra/laravel-datatables": "^1.5",
        "yajra/laravel-datatables-oracle": "~9.0"
}
</code>```

So why is not a table rendering? Is it something I'm doing wrong?
I ran the internet and I did not find a solution, I hope you will help me

答:
You should create a datatable class for category and use it on controller

On your datatable class :

```<code>namespace App\DataTables;

use Illuminate\Support\Facades\App;
use Yajra\DataTables\Services\DataTable;

class CategoriasDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     *
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables($query);
    }

    /**
     * Get query source of dataTable.
     *
     * @param App\Models\Category $model
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Category $model)
    {
        return $model
            ->newQuery()
            ->select('*');
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->addAction(['width' => '100px'])
                    ->parameters($this->getBuilderParameters());
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            [
                'data'  => 'id',
                'name'  => 'id',
                'title' => 'Id',
            ],
            [
                'data'  => 'name',
                'name'  => 'name',
                'title' => 'Name',
            ],
            [
                'data'  => 'created_at',
                'name'  => 'created_at',
                'title' => 'Created At',
            ],
            [
                'data'  => 'updated_at',
                'name'  => 'updated_at',
                'title' => 'Updated At',
            ],
        ];
    }
}
</code>```

On you Controller :

```<code>use App\DataTables\UsersDataTable;
class CategoriasController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @param App\DataTables\CategoriasDataTable $datatable
     *
     * @return \Illuminate\Http\Response
     */
    public function index(CategoriasDataTable $datatable)
    {
        return $datatable->render('admin.categorias.index');
    }
 .......
</code>```

I hope this will help you

Body:
So, this is my controller:

use Yajra\DataTables\Facades\DataTables;
class CategoriasController extends Controller
{
    public function index()
    {
        return Datatables::collection(Categoria::all())->make(true);
    }
 [...]
}

this is my route:

Route::group(['middleware' => 'auth'], function () {
    Route::group(['middleware' => 'admin'], function () {
        Route::prefix('admin')->namespace('Admin')->group(function () {
            Route::prefix('categorias')->group(function(){
                Route::get('/', 'CategoriasController@index')->name('curso.index');
[...]
             });
         });
     });
});

and this is my blade:

[...]

                id
                Nome
                Criado
                Modificado

[...]

And I got this as a return:

I'm using Laravel 5.8.19

composer.json

[...]
"require":{
        "yajra/laravel-datatables": "^1.5",
        "yajra/laravel-datatables-oracle": "~9.0"
}

So why is not a table rendering? Is it something I'm doing wrong?
I ran the internet and I did not find a solution, I hope you will help me

Body:
You should create a datatable class for category and use it on controller

On your datatable class :

namespace App\DataTables;

use Illuminate\Support\Facades\App;
use Yajra\DataTables\Services\DataTable;

class CategoriasDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     *
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables($query);
    }

    /**
     * Get query source of dataTable.
     *
     * @param App\Models\Category $model
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Category $model)
    {
        return $model
            ->newQuery()
            ->select('*');
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->addAction(['width' => '100px'])
                    ->parameters($this->getBuilderParameters());
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            [
                'data'  => 'id',
                'name'  => 'id',
                'title' => 'Id',
            ],
            [
                'data'  => 'name',
                'name'  => 'name',
                'title' => 'Name',
            ],
            [
                'data'  => 'created_at',
                'name'  => 'created_at',
                'title' => 'Created At',
            ],
            [
                'data'  => 'updated_at',
                'name'  => 'updated_at',
                'title' => 'Updated At',
            ],
        ];
    }
}

On you Controller :

use App\DataTables\UsersDataTable;
class CategoriasController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @param App\DataTables\CategoriasDataTable $datatable
     *
     * @return \Illuminate\Http\Response
     */
    public function index(CategoriasDataTable $datatable)
    {
        return $datatable->render('admin.categorias.index');
    }
 .......

I hope this will help you


问:
How to destructure defaults from a string
I'm wondering how I can destructure default values from a string. For instance, take the following code:

function f({length, valueOf}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf()); // Expected: "The string is: foo"
}

f("foo");```
</div>
</div>
</p>

<p>Above, I am trying to get the <code>length</code> of the passed in string, as well as the string itself (ie: by calling <code>valueOf</code>), however, I get an error:</p>

<blockquote>
  <p>Uncaught TypeError: String.prototype.valueOf requires that 'this' be a
  String</p>
</blockquote>

<p>I was thinking that this was because I can't destructure methods from objects but my testing tells me otherwise:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
  id: 1,
  foo: function() {
    return "bar";
  }
}

const {id, foo} = obj;
console.log(id, foo());</code>```

So, I would like to know two things:

How can I get the original string passed into my function f while destructuing its arguments (is it even possible?)

Why do I get an error with my first bit of code, but not the other?

答:
This has nothing todo with destructuring, destructuring is just sugar around variable assignments:</p>

```<code>  const valueOf = "foo".valueOf;
  valueOf(); // same error

  valueOf.call("other"); // works
</code>```

Body:
I'm wondering how I can destructure default values from a string. For instance, take the following code:

function f({length, valueOf}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf()); // Expected: "The string is: foo"
}

f("foo");

Above, I am trying to get the length of the passed in string, as well as the string itself (ie: by calling valueOf), however, I get an error:

Uncaught TypeError: String.prototype.valueOf requires that 'this' be a
  String

I was thinking that this was because I can't destructure methods from objects but my testing tells me otherwise:

const obj = {
  id: 1,
  foo: function() {
    return "bar";
  }
}

const {id, foo} = obj;
console.log(id, foo());

So, I would like to know two things:

How can I get the original string passed into my function f while destructuing its arguments (is it even possible?)

Why do I get an error with my first bit of code, but not the other?

Body:
This has nothing todo with destructuring, destructuring is just sugar around variable assignments:

  const valueOf = "foo".valueOf;
  valueOf(); // same error

  valueOf.call("other"); // works


问:
Android layout clipping
I am trying to make a layout as described below. I don't understand how to exactly implement the layout.

The layout and the above hexagon will have some text that i need to change dynamically from code.

I have tried a similar way mentioned here

But the hexagon is still clipping. I'm using the following code.

```<code>  <RelativeLayout
        android:id="@+id/Llfirstamount"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:background="@color/layoutcolor1"
        android:clickable="true"
        android:clipChildren="false" >

        <TextView
            android:id="@+id/my_first_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:android:layout_alignParentBottom="true"
            android:android:layout_alignParentLeft="true"
            android:padding="15dp"
            android:text="Amount"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/my_second_text"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="-20dp"
            android:background="@drawable/hexagon"
            android:clipToPadding="false"
            android:contentDescription="@string/contentdesc_peso_logo"
            android:gravity="center"
            android:text="x5" />
    </RelativeLayout>
</code>```

I don't know is this the only way or the right way or there is a much better way to implement this.I'm very confused.
Please Help!!! thank you..

EDIT:

Ok thanks for your answers using two text views with custom background is is a good and clean idea. Now I'm using the edited code but the hexagon is clipping like below..

Am i missing something i have also added

```<code>android:clipToPadding="false"
</code>```

and

```<code>android:clipChildren="false"
</code>```

in my code.

答: Adding android:clipToPadding="false" and android:clipChildren="false" to the top-most layout view will do the trick, if you can bear all sub-views having the same effect.

Title: Android layout clipping

Body:
I am trying to make a layout as described below. I don't understand how to exactly implement the layout.

The layout and the above hexagon will have some text that i need to change dynamically from code.

I have tried a similar way mentioned here

But the hexagon is still clipping. I'm using the following code.

  <RelativeLayout
        android:id="@+id/Llfirstamount"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:background="@color/layoutcolor1"
        android:clickable="true"
        android:clipChildren="false" >

        <TextView
            android:id="@+id/my_first_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:android:layout_alignParentBottom="true"
            android:android:layout_alignParentLeft="true"
            android:padding="15dp"
            android:text="Amount"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/my_second_text"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="-20dp"
            android:background="@drawable/hexagon"
            android:clipToPadding="false"
            android:contentDescription="@string/contentdesc_peso_logo"
            android:gravity="center"
            android:text="x5" />
    </RelativeLayout>

I don't know is this the only way or the right way or there is a much better way to implement this.I'm very confused.
Please Help!!! thank you..

EDIT:

Ok thanks for your answers using two text views with custom background is is a good and clean idea. Now I'm using the edited code but the hexagon is clipping like below..

Am i missing something i have also added

android:clipToPadding="false"

and

android:clipChildren="false"

in my code.


问:
How can I call functions in PHP depending of their position?
I'm currently trying to build a sorting function for some div's in PHP. First I've put each section into one function so that when I call this function, the section get's printed.

Now I've the problem that I don't know how I can call each section depending on their position? This is my code:

```<code>    $elements = array(
        'section_one'   => 6,
        'section_two'   => 1,
        'section_three' => 0,
        'section_four'  => 3,
        'section_five'  => 2,
        'section_six'   => 5,
        'section_seven' => 4
    );

    foreach ( $elements as $element => $position ) {

    }

    get_section_one( $a, $b, $c );
    get_section_two( $a, $b, $c, $d );
    get_section_three( $a, $b );
    get_section_four( $a );
    get_section_five( $a, $b, $c, $d, $e );
    get_section_six( $a, $b, $c );
    get_section_seven( $a, $b, $c );
</code>```

Each function has different parameters which are not defined. The $elements array has a key which is the name of the section and a value which defines the position.

So has anyone an idea how I can call each function depending on their position from the lowest number to the highest?

In my example section_three must be the first element which should be called...

答:
For order you need to sort your array (for now asort() is what you need), but before doing that I'd rework the array and make function position a key, not the value as you have now (assuming position is unique of course). Once sorted you can iterate using usual foreach($elements as $func_name) and the helper method you are looking for is call_user_func():

```<code>foreach ( $elements as $func_name ) {
    call_user_func($func_name, ....)
}
</code>```

There's one issue though, that you have different number of arguments for each of these functions, so this may get tricky. You may want to rework your functions to accept i.e. array of arguments instead. This could be additionally beneficial, as arguments array could be ten part of your $elements array, so no additional "builder" logic would be needed, i.e.:

$elements = [
  0 => [ 'name' => 'section_three',
         'args' => [$a, $b],
       ],
  ...
  2 => [ 'name' => 'get_section_five',
         'args' => [$a, $b, $c, $d, $e],
       ],
  ...
];

ksort($elements);

foreach($elements as $el) {
    call_user_func($el['name'], $el['args']);
}

```

Body:
I'm currently trying to build a sorting function for some div's in PHP. First I've put each section into one function so that when I call this function, the section get's printed.

Now I've the problem that I don't know how I can call each section depending on their position? This is my code:

    $elements = array(
        'section_one'   => 6,
        'section_two'   => 1,
        'section_three' => 0,
        'section_four'  => 3,
        'section_five'  => 2,
        'section_six'   => 5,
        'section_seven' => 4
    );

    foreach ( $elements as $element => $position ) {

    }

    get_section_one( $a, $b, $c );
    get_section_two( $a, $b, $c, $d );
    get_section_three( $a, $b );
    get_section_four( $a );
    get_section_five( $a, $b, $c, $d, $e );
    get_section_six( $a, $b, $c );
    get_section_seven( $a, $b, $c );

Each function has different parameters which are not defined. The $elements array has a key which is the name of the section and a value which defines the position.

So has anyone an idea how I can call each function depending on their position from the lowest number to the highest?

In my example section_three must be the first element which should be called...

Body:
For order you need to sort your array (for now asort() is what you need), but before doing that I'd rework the array and make function position a key, not the value as you have now (assuming position is unique of course). Once sorted you can iterate using usual foreach($elements as $func_name) and the helper method you are looking for is call_user_func():

foreach ( $elements as $func_name ) {
    call_user_func($func_name, ....)
}

There's one issue though, that you have different number of arguments for each of these functions, so this may get tricky. You may want to rework your functions to accept i.e. array of arguments instead. This could be additionally beneficial, as arguments array could be ten part of your $elements array, so no additional "builder" logic would be needed, i.e.:

$elements = [
  0 => [ 'name' => 'section_three',
         'args' => [$a, $b],
       ],
  ...
  2 => [ 'name' => 'get_section_five',
         'args' => [$a, $b, $c, $d, $e],
       ],
  ...
];

ksort($elements);

foreach($elements as $el) {
    call_user_func($el['name'], $el['args']);
}


问:
Date range between two dates with given time
I need to calculate the count of days between two given dates with time. For example the dates between '06/01/2019 09:00' and '06/02/2019 22:00' should count as 2 days for me. I tried the below code, but I don't get the result I need.

Any ideas on how to calculate the result?

```<code>$to = $_GET['end_date'];
$dteStart = new DateTime($from);
$dteEnd   = new DateTime($to);
$diff  = $dteStart->diff($dteEnd);
print $diff->format("%H:%I");
</code>```

答:
You can count total days as:</p>

```<code>print $diff->format('%D') + (0 < $diff->format('%H') ? 1 : 0);
// %D - gives you number of days between dates
// and if there're more hours between dates - add one day

// probably you also want to consider minutes,
// so as "1 day 10 minutes" diff should also be
// considered as 2 days, then:
print $diff->format('%D') + ((0 < $diff->format('%H') || 0 < $diff->format('%I')) ? 1 : 0);
</code>```

Body:
I need to calculate the count of days between two given dates with time. For example the dates between '06/01/2019 09:00' and '06/02/2019 22:00' should count as 2 days for me. I tried the below code, but I don't get the result I need.

Any ideas on how to calculate the result?

$to = $_GET['end_date'];
$dteStart = new DateTime($from);
$dteEnd   = new DateTime($to);
$diff  = $dteStart->diff($dteEnd);
print $diff->format("%H:%I");

Body:
You can count total days as:

print $diff->format('%D') + (0 < $diff->format('%H') ? 1 : 0);
// %D - gives you number of days between dates
// and if there're more hours between dates - add one day

// probably you also want to consider minutes,
// so as "1 day 10 minutes" diff should also be
// considered as 2 days, then:
print $diff->format('%D') + ((0 < $diff->format('%H') || 0 < $diff->format('%I')) ? 1 : 0);


问:
Java Error: cannot resolve method split()
I am trying to get user input into a String array and wanted to use the string.split() method but for some reason, my IntelliJ is telling me, that it cannot resolve the method 'split()'.

package com.Practice;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String[] splittedString = input.split();
    }
}
```

<p>I dont think, that there is a problem with my code, mayby with my IDE or Java version, but im no expert at this stuff.
When I try to run the program it throws me this error:</p>

```Error:(10, 40) java: no suitable method found for split(no arguments)
    method java.lang.String.split(java.lang.String,int) is not applicable
      (actual and formal argument lists differ in length)
    method java.lang.String.split(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)
```

答:
Java really doesn't have a String#split method that takes no arguments. You need to split the string by a regex, such as \\s (which mean splitting by a whitespace):

```<code>String[] splittedString = input.split("\\s");
</code>```

Body:
I am trying to get user input into a String array and wanted to use the string.split() method but for some reason, my IntelliJ is telling me, that it cannot resolve the method 'split()'.

package com.Practice;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String[] splittedString = input.split();
    }
}

I dont think, that there is a problem with my code, mayby with my IDE or Java version, but im no expert at this stuff.
When I try to run the program it throws me this error:

Error:(10, 40) java: no suitable method found for split(no arguments)
    method java.lang.String.split(java.lang.String,int) is not applicable
      (actual and formal argument lists differ in length)
    method java.lang.String.split(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)

Body:
Java really doesn't have a String#split method that takes no arguments. You need to split the string by a regex, such as \\s (which mean splitting by a whitespace):

String[] splittedString = input.split("\\s");


问:
Can a Ruby app call Java code?
This is probably really simple, but all my Google results came back with JRuby, which isn't what I want to know.  I'm curious if a regular Ruby app (e.g. a Rails app or a Sinatra app) could somehow be made to reference and call a Java library that's in the classpath?  Ideally one that works on Heroku.</p>

答:
http://rjb.rubyforge.org/

another option would be if the jar is executable and do something like
 execute system command and run it in a 'session'/terminal

Title: Can a Ruby app call Java code?


答:
```<code>$diff  = $dteStart->diff($dteEnd)->days + 1;
echo $diff;
</code>```

There is one day difference, but I guess you also want to calculate the current day.

Title: Date range between two dates with given time

Body:
$diff  = $dteStart->diff($dteEnd)->days + 1;
echo $diff;

There is one day difference, but I guess you also want to calculate the current day.


问:
Is there a way to turn off specific built-in tokenization rules in Spacy?
Spacy automatically tokenizes word contractions such as "dont" and "don't" into "do" and "nt"/"n't".  For instance, a sentence like "I dont understand" would be tokenized into: ["I", "do", "nt", "understand"].

I understand this is usually helpful in many NLP tasks, but is there a way to suppress this special tokenization rule in Spacy such that the result is ["I", "dont", "understand"] instead?

This is because I am trying to evaluate the performance (f1-score for BIO tagging scheme) of my custom Spacy NER model, and the mismatch in the number of tokens in the input sentence and the number of predicated token tags is causing problems for my evaluation code down the line:

Input (3 tokens): [("I", "O"), ("dont", "O"), ("understand", "O")]

Predicted (4 tokens): [("I", "O"), ("do", "O"), ("nt", "O"), ("understand", "O")]

Of course, if anyone has any suggestions for a better way to perform evaluation on sequential tagging tasks in Spacy (perhaps like the seqeval package but more compatible with Spacy's token format), that would be greatly appreciated as well.

答:
The special-case tokenization rules are defined in the tokenizer_exceptions.py in the respective language data (see here for the English "nt" contractions). When you create a new Tokenizer, those special case rules can be passed in via the rules argument.

Approach 1: Custom tokenizer with different special case rules

So one thing you could do for your use case is to reconstruct the English Tokenizer with the same prefix, suffix and infix rules, but with only a filtered set of tokenizer exceptions. Tokenizer exceptions are keyed by the string, so you could remove the entries for "dont" and whatever else you need. However, the code is quite verbose, since you're reconstructing the whole tokenizer:

from spacy.lang.en import English
from spacy.lang.punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES, TOKENIZER_INFIXES
from spacy.lang.en import TOKENIZER_EXCEPTIONS
from spacy.tokenizer import Tokenizer
from spacy.util import compile_prefix_regex, compile_suffix_regex, compile_infix_regex

prefix_re = compile_prefix_regex(TOKENIZER_PREFIXES).search
suffix_re = compile_suffix_regex(TOKENIZER_SUFFIXES).search
infix_re = compile_infix_regex(TOKENIZER_INFIXES).finditer
filtered_exc = {key: value for key, value in TOKENIZER_EXCEPTIONS.items() if key not in ["dont"]}

nlp = English()
tokenizer = Tokenizer(
    nlp.vocab,
    prefix_search=prefix_re,
    suffix_search=suffix_re,
    infix_finditer=infix_re,
    rules=filtered_exc
)
nlp.tokenizer = tokenizer
doc = nlp("I dont understand")
```

<h2>Approach 2: Merge (or split) tokens afterwards</h2>

<p>An alternative aproach would be to keep the tokenization as it is, but add rules on top that <em>merge</em> certain tokens back together aftwards to match the desired tokenization. This is obviously going to be slower at runtime, but it might be easier to implement and reason about, because you can approach it from the perspective of "Which tokens are currently separated but should be one?". For this, you could use the rule-based <code>Matcher</code> and the retokenizer to merge the matched tokens back together. As of spaCy v2.1, it also supports splitting, in case that's relevant.</p>

<pre class="lang-py prettyprint-override"><code>from spacy.lang.en import English
from spacy.matcher import Matcher

nlp = English()
matcher = Matcher(nlp.vocab)
patterns = [[{"LOWER": "do"}, {"LOWER": "nt"}]]
matcher.add("TO_MERGE", None, *patterns)

doc = nlp("I dont understand")
matches = matcher(doc)
with doc.retokenize() as retokenizer:
    for match_id, start, end in matches:
        span = doc[start:end]
        retokenizer.merge(span)
</code>```

The above pattern would match two tokens (one dict per token), whose lowercase forms are "do" and "nt" (e.g. "DONT", "dont", "DoNt"). You can add more lists of dicts to the patterns to describe other sequences of tokens. For each match, you can then create a Span and merge it into one token. To make this logic more elegant, you could also wrap it as a custom pipeline component, so it's applied automatically when you call nlp on a text.

Body:
The special-case tokenization rules are defined in the tokenizer_exceptions.py in the respective language data (see here for the English "nt" contractions). When you create a new Tokenizer, those special case rules can be passed in via the rules argument.

Approach 1: Custom tokenizer with different special case rules

So one thing you could do for your use case is to reconstruct the English Tokenizer with the same prefix, suffix and infix rules, but with only a filtered set of tokenizer exceptions. Tokenizer exceptions are keyed by the string, so you could remove the entries for "dont" and whatever else you need. However, the code is quite verbose, since you're reconstructing the whole tokenizer:

from spacy.lang.en import English
from spacy.lang.punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES, TOKENIZER_INFIXES
from spacy.lang.en import TOKENIZER_EXCEPTIONS
from spacy.tokenizer import Tokenizer
from spacy.util import compile_prefix_regex, compile_suffix_regex, compile_infix_regex

prefix_re = compile_prefix_regex(TOKENIZER_PREFIXES).search
suffix_re = compile_suffix_regex(TOKENIZER_SUFFIXES).search
infix_re = compile_infix_regex(TOKENIZER_INFIXES).finditer
filtered_exc = {key: value for key, value in TOKENIZER_EXCEPTIONS.items() if key not in ["dont"]}

nlp = English()
tokenizer = Tokenizer(
    nlp.vocab,
    prefix_search=prefix_re,
    suffix_search=suffix_re,
    infix_finditer=infix_re,
    rules=filtered_exc
)
nlp.tokenizer = tokenizer
doc = nlp("I dont understand")

Approach 2: Merge (or split) tokens afterwards

An alternative aproach would be to keep the tokenization as it is, but add rules on top that merge certain tokens back together aftwards to match the desired tokenization. This is obviously going to be slower at runtime, but it might be easier to implement and reason about, because you can approach it from the perspective of "Which tokens are currently separated but should be one?". For this, you could use the rule-based Matcher and the retokenizer to merge the matched tokens back together. As of spaCy v2.1, it also supports splitting, in case that's relevant.

from spacy.lang.en import English
from spacy.matcher import Matcher

nlp = English()
matcher = Matcher(nlp.vocab)
patterns = [[{"LOWER": "do"}, {"LOWER": "nt"}]]
matcher.add("TO_MERGE", None, *patterns)

doc = nlp("I dont understand")
matches = matcher(doc)
with doc.retokenize() as retokenizer:
    for match_id, start, end in matches:
        span = doc[start:end]
        retokenizer.merge(span)

The above pattern would match two tokens (one dict per token), whose lowercase forms are "do" and "nt" (e.g. "DONT", "dont", "DoNt"). You can add more lists of dicts to the patterns to describe other sequences of tokens. For each match, you can then create a Span and merge it into one token. To make this logic more elegant, you could also wrap it as a custom pipeline component, so it's applied automatically when you call nlp on a text.


问:
Spring-Data-Jpa save: Related entities saved as null which are not
I have an entity timetable:

```<code>@Entity @Table(name = TableUtils.TIMETABLE)public class Timetable {

private static final long serialVersionUID = -1307879048598194633L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = ColumnUtils.ID)
private long id;

@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
private List<TimetableCell> timetableCells;

public List<TimetableCell> getTimetableCells() {
    return timetableCells;
}

public void setTimetableCells(List<TimetableCell> timetableCells) {
    this.timetableCells = timetableCells;
}
}
</code>```

and an entity timetableCell:

```<code>@Entity
@Table(name = TableUtils.TIMETABLE_CELL)
public class TimetableCell extends AbstractElement {

private static final long serialVersionUID = -8083688091896353882L;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.WEEK_DAY_ID, nullable = false)
private WeekDay weekDay;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.LESSON_HOUR_ID, nullable = false)
private LessonHour lessonHour;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.TIMETABLE_ID, nullable = false)
private Timetable timetable;

...
}
</code>```

At first I create timetable cells with weekDay and LessonHours. After I set this list to timetable and try to save it. But All timetable cells are saved with null weekDay and null LessonHour.
I debugged it. Before save all fields are set as well.

timetableRepository.save(timetable);

Debug result showing following

答:
1) The timetableCells are marked with only these cascade types:

```<code>@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
</code>```

2) The week and hour deps have only this:

```<code>@ManyToOne(cascade = CascadeType.PERSIST)
</code>```

3) If you pass Timetable to save method here and it has been persisted before:

```<code>timetableRepository.save(timetable);
</code>```

Spring Data JPA will not call persist, but merge instead.

That might be the case why the cascading does not work. If you add this to your config you might get what you need:

```<code>cascade = {CascadeType.REMOVE, CascadeType.PERSIST, CascadeType.MERGE})
</code>```

Body:
I have an entity timetable:

@Entity @Table(name = TableUtils.TIMETABLE)public class Timetable {

private static final long serialVersionUID = -1307879048598194633L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = ColumnUtils.ID)
private long id;

@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
private List<TimetableCell> timetableCells;

public List<TimetableCell> getTimetableCells() {
    return timetableCells;
}

public void setTimetableCells(List<TimetableCell> timetableCells) {
    this.timetableCells = timetableCells;
}
}

and an entity timetableCell:

@Entity
@Table(name = TableUtils.TIMETABLE_CELL)
public class TimetableCell extends AbstractElement {

private static final long serialVersionUID = -8083688091896353882L;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.WEEK_DAY_ID, nullable = false)
private WeekDay weekDay;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.LESSON_HOUR_ID, nullable = false)
private LessonHour lessonHour;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.TIMETABLE_ID, nullable = false)
private Timetable timetable;

...
}

At first I create timetable cells with weekDay and LessonHours. After I set this list to timetable and try to save it. But All timetable cells are saved with null weekDay and null LessonHour.
I debugged it. Before save all fields are set as well.

timetableRepository.save(timetable);

Debug result showing following

Body:
1) The timetableCells are marked with only these cascade types:

@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})

2) The week and hour deps have only this:

@ManyToOne(cascade = CascadeType.PERSIST)

3) If you pass Timetable to save method here and it has been persisted before:

timetableRepository.save(timetable);

Spring Data JPA will not call persist, but merge instead.

That might be the case why the cascading does not work. If you add this to your config you might get what you need:

cascade = {CascadeType.REMOVE, CascadeType.PERSIST, CascadeType.MERGE})


问:
Can't locate data on page
I am attempting to pull the title and link of each so called raffle in the list on this website. However, when i try to scrape this data, it can't seem to be found.

I have tried scraping all links on the page, but I think these "boxes" may be loaded via javascript.

The results I am receiving are a few links unrelated to what I want to get. There should be 40+ links that show up in this list, but the majority are not showing. Any help would be great, been stuck on this for a while

For some reason, this link and many others aren't showing up when I am scraping:

my code:

def raffle_page_collection():
    chrome_driver()
    page = requests.get('https://www.soleretriever.com/yeezy-boost-350-v2-black/')
    soup = BeautifulSoup(page.text,'html.parser')
    product_header = soup.find('h1').text
    product_colorway = soup.find('h2').text
    product_sku_and_release_date_and_price = soup.find('h3').text

    container = soup.find(class_='main-container')
    raffles = container.find_all('a')

    raffle_list = []

    for items in raffles:
        raffle_list.append(items.get('href'))

    print(raffle_list)
```

答:
You should try automation selenium library. it allows you to scrape dynamic rendering request(js or ajax) page data.

Try this:

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time

browser = webdriver.Chrome()
browser.get('https://www.soleretriever.com/yeezy-boost-350-v2-black/')
time.sleep(3)

soup = BeautifulSoup(browser.page_source,'html.parser')

product_header = soup.find('h1').text
product_colorway = soup.find('h2').text
product_sku_and_release_date_and_price = soup.find('h3').text

container = soup.find(class_='main-container')
raffles = container.find("div",{"class":"vc_pageable-slide-wrapper vc_clearfix"})

raffle_list = []

for items in raffles.find_all("a",href=True):
    raffle_list.append(items.get('href'))

print(product_header)
print(product_colorway)
print(product_sku_and_release_date_and_price)
print(raffle_list)
</code>```

O/P:

```<code>Yeezy Boost 350 v2 Black
Black/ Black/ Black
FU9006 | 07/06/19 | $220
['https://www.43einhalb.com/en/adidas-yeezy-boost-350-v2-black-328672#SR', 'https://www.adidas.co.uk/yeezy#SR', 'https://www.allikestore.com/default/adidas-yeezy-boost-350-v2-static-black-black-fu9006-105308.html#SR', 'https://archive1820.com/en/forms/6/yeezy-raffle#SR', 'https://drops.blackboxstore.com/blackbox_launches_view/catalog/product/view/id/22296/s/yeezy-boost-350-v2#SR', 'https://woobox.com/4szm9v#SR', 'https://launches.endclothing.com/product/yeezy-boost-350-v2-fu9006#SR', 'https://www.instagram.com/p/ByEIHSHDSY6/', 'https://www.instagram.com/p/ByFG1G0lWf7/', 'https://releases.footshop.com/adidas-yeezy-boost-350-v2-agqn6WoBJZ9y4RSnzw9G#SR', 'https://launches.goodhoodstore.com/launches/yeezy-boost-350-v2-black-33#SR', 'https://www.hervia.com/launches/yeezy-350#SR', 'https://www.hibbett.com/adidas-yeezy-350-v2-black-mens-shoe/M0991.html#SR', 'https://reporting.jdsports.co.uk/cgi-bin/msite?yeezy_comp+a+0+0+0+0+0&utm_source=RedEye&utm_medium=Email&utm_campaign=Yeezy%20Boost%20351%20Clay&utm_content=0905%20Yeezy%20Clay#SR', 'https://www.instagram.com/p/ByDnK6uH6kE/', 'https://www.nakedcph.com/yeezy-boost-v2-350-static-black-raffle/s/635#SR', 'https://www.instagram.com/p/ByIXT8zHvYz/', 'https://launches.sevenstore.com/launch/yeezy-boost-350-v2-black-4033024#SR', 'https://shelta.eu/news/adidas-yeezy-boost-350-v2-black-fu9006x#SR', 'https://www.instagram.com/p/ByDI_6JAfty/', 'https://www.sneakersnstuff.com/en/product/38889/adidas-yeezy-350-v2#SR', 'https://www.instagram.com/p/ByHtt3HFkE0/', 'https://www.instagram.com/p/ByCaKR7Cde1/', 'https://tres-bien.com/adidas-yeezy-boost-350-v2-black-fu9006-fw19#SR', 'https://yeezysupply.com/products/yeezy-boost-350-v2-black-june-7-2019#SR']
</code>```

for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

selenium tutorial

https://selenium-python.readthedocs.io/

Title: Can't locate data on page

Body:
You should try automation selenium library. it allows you to scrape dynamic rendering request(js or ajax) page data.

Try this:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

browser = webdriver.Chrome()
browser.get('https://www.soleretriever.com/yeezy-boost-350-v2-black/')
time.sleep(3)

soup = BeautifulSoup(browser.page_source,'html.parser')

product_header = soup.find('h1').text
product_colorway = soup.find('h2').text
product_sku_and_release_date_and_price = soup.find('h3').text

container = soup.find(class_='main-container')
raffles = container.find("div",{"class":"vc_pageable-slide-wrapper vc_clearfix"})

raffle_list = []

for items in raffles.find_all("a",href=True):
    raffle_list.append(items.get('href'))

print(product_header)
print(product_colorway)
print(product_sku_and_release_date_and_price)
print(raffle_list)

O/P:

Yeezy Boost 350 v2 Black
Black/ Black/ Black
FU9006 | 07/06/19 | $220
['https://www.43einhalb.com/en/adidas-yeezy-boost-350-v2-black-328672#SR', 'https://www.adidas.co.uk/yeezy#SR', 'https://www.allikestore.com/default/adidas-yeezy-boost-350-v2-static-black-black-fu9006-105308.html#SR', 'https://archive1820.com/en/forms/6/yeezy-raffle#SR', 'https://drops.blackboxstore.com/blackbox_launches_view/catalog/product/view/id/22296/s/yeezy-boost-350-v2#SR', 'https://woobox.com/4szm9v#SR', 'https://launches.endclothing.com/product/yeezy-boost-350-v2-fu9006#SR', 'https://www.instagram.com/p/ByEIHSHDSY6/', 'https://www.instagram.com/p/ByFG1G0lWf7/', 'https://releases.footshop.com/adidas-yeezy-boost-350-v2-agqn6WoBJZ9y4RSnzw9G#SR', 'https://launches.goodhoodstore.com/launches/yeezy-boost-350-v2-black-33#SR', 'https://www.hervia.com/launches/yeezy-350#SR', 'https://www.hibbett.com/adidas-yeezy-350-v2-black-mens-shoe/M0991.html#SR', 'https://reporting.jdsports.co.uk/cgi-bin/msite?yeezy_comp+a+0+0+0+0+0&utm_source=RedEye&utm_medium=Email&utm_campaign=Yeezy%20Boost%20351%20Clay&utm_content=0905%20Yeezy%20Clay#SR', 'https://www.instagram.com/p/ByDnK6uH6kE/', 'https://www.nakedcph.com/yeezy-boost-v2-350-static-black-raffle/s/635#SR', 'https://www.instagram.com/p/ByIXT8zHvYz/', 'https://launches.sevenstore.com/launch/yeezy-boost-350-v2-black-4033024#SR', 'https://shelta.eu/news/adidas-yeezy-boost-350-v2-black-fu9006x#SR', 'https://www.instagram.com/p/ByDI_6JAfty/', 'https://www.sneakersnstuff.com/en/product/38889/adidas-yeezy-350-v2#SR', 'https://www.instagram.com/p/ByHtt3HFkE0/', 'https://www.instagram.com/p/ByCaKR7Cde1/', 'https://tres-bien.com/adidas-yeezy-boost-350-v2-black-fu9006-fw19#SR', 'https://yeezysupply.com/products/yeezy-boost-350-v2-black-june-7-2019#SR']

for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

selenium tutorial

https://selenium-python.readthedocs.io/


答:
You can use asort() to order the elements (keeping the keys of the array) right before your loop.

```<code>$elements = array(
    'section_one'   => 6,
    'section_two'   => 1,
    'section_three' => 0,
    'section_four'  => 3,
    'section_five'  => 2,
    'section_six'   => 5,
    'section_seven' => 4
);

asort($elements);

foreach ( $elements as $element => $position ) {

}
</code>```

Title: How can I call functions in PHP depending of their position?

Body:
You can use asort() to order the elements (keeping the keys of the array) right before your loop.

$elements = array(
    'section_one'   => 6,
    'section_two'   => 1,
    'section_three' => 0,
    'section_four'  => 3,
    'section_five'  => 2,
    'section_six'   => 5,
    'section_seven' => 4
);

asort($elements);

foreach ( $elements as $element => $position ) {

}


问:
How to parse this date 2018-10-22T2250?
How to parse this strange datetime 2018-10-22T2250 in golang?
I couldn't find date layout</p>

答:
You can create your own custom format.  In production, you should also handle the error.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    timeString := "2018-10-22T2250"
    timeFormat := "2006-01-02T1504"

    t, _ := time.Parse(timeFormat, timeString)

    fmt.Println(t)
}
</code>```

Playground link

This returns the time in UTC.  You may need to adjust to another timezone, depending on your source.

```<code>//init the location
loc, _ := time.LoadLocation("Asia/Shanghai")
//localize the time
localTime := t.In(loc)
</code>```

Title: How to parse this date 2018-10-22T2250?

Body:
You can create your own custom format.  In production, you should also handle the error.

package main

import (
    "fmt"
    "time"
)

func main() {
    timeString := "2018-10-22T2250"
    timeFormat := "2006-01-02T1504"

    t, _ := time.Parse(timeFormat, timeString)

    fmt.Println(t)
}

Playground link

This returns the time in UTC.  You may need to adjust to another timezone, depending on your source.

//init the location
loc, _ := time.LoadLocation("Asia/Shanghai")
//localize the time
localTime := t.In(loc)


问:
Parse multipart request string in Python
I have a string like this

```<code>"--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3--\r\n"
</code>```

I also have request headers available in other vairbles.

How do I easily parse this with Python3?

I am handling a file upload in AWS Lambda via API Gateway, request body and headers are available via Python dicts.

There are other similar questions on stackoverflow, but most are assuming use of the requests module or other modules and expect the request details to be in a specific object or format.

NOTE: I am aware its possible to have user upload to S3 and trigger Lambda, but I am intentionally choosing not to do that in this case.

答:
If you want to use Python's CGI,</p>
```<code>from cgi import parse_multipart, parse_header
from io import BytesIO

c_type, c_data = parse_header(event['headers']['Content-Type'])
assert c_type == 'multipart/form-data'
decoded_string = base64.b64decode(event['body'])
#For Python 3: these two lines of bugfixing are mandatory
#see also: https://stackoverflow.com/questions/31486618/cgi-parse-multipart-function-throws-typeerror-in-python-3
c_data['boundary'] = bytes(c_data['boundary'], "utf-8")
c_data['CONTENT-LENGTH'] = event['headers']['Content-length']
form_data = parse_multipart(BytesIO(decoded_string), c_data)

for image_str in form_data['file']:
    ...
</code>```

Body:
I have a string like this

"--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3--\r\n"

I also have request headers available in other vairbles.

How do I easily parse this with Python3?

I am handling a file upload in AWS Lambda via API Gateway, request body and headers are available via Python dicts.

There are other similar questions on stackoverflow, but most are assuming use of the requests module or other modules and expect the request details to be in a specific object or format.

NOTE: I am aware its possible to have user upload to S3 and trigger Lambda, but I am intentionally choosing not to do that in this case.

Body:
If you want to use Python's CGI,

from cgi import parse_multipart, parse_header
from io import BytesIO

c_type, c_data = parse_header(event['headers']['Content-Type'])
assert c_type == 'multipart/form-data'
decoded_string = base64.b64decode(event['body'])
#For Python 3: these two lines of bugfixing are mandatory
#see also: https://stackoverflow.com/questions/31486618/cgi-parse-multipart-function-throws-typeerror-in-python-3
c_data['boundary'] = bytes(c_data['boundary'], "utf-8")
c_data['CONTENT-LENGTH'] = event['headers']['Content-length']
form_data = parse_multipart(BytesIO(decoded_string), c_data)

for image_str in form_data['file']:
    ...


问:
Why is my stylesheet being ignored by a stylesheet with a lower specificity?
I created a spacing-element that uses two classes:

.spacer-mobile-M = spacing height on mobile devices

.spacer-desktop-0 = spacing height on desktop devices (only active @media (min-width: 992px))

.spacer-blank {
    display: block;
    border: 1px solid #000;
}

.spacer-mobile-M {
    height: 20px;
}

@media (min-width: 992px) {
    .spacer-desktop-0 {
        height: 0px;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="spacer-blank spacer-mobile-M spacer-desktop-0" aria-hidden="true"></div></code>```

The expected behavior on a 1200px wide screen would be, that the mobile-spacer is being overwritten by the desktop style (higher specificity due to media query and defined later in the code).

However, right now, the desktop spacer is being overwritten by the mobile style.

I only experience this behavior with a spacer that has a lower height than the mobile value.

Is there a rule, that classes with height: 0 or lower height than the general one (without media query) can be overwritten? I can't find anything in Google when I search for specificity.

Thanks for a short hint.

答:
I think the problem could be use two different CSS classes for the same element. If you use media queries, why don't use the same class? For example:

```<code>.spacer {
  display: block;
  height: 20px;
}

@media (min-width: 992px) {

  .spacer {
    height: 0;
  }
}
</code>```

I don't know the rest of the code, but if on desktop size you want simply hide the spacer also you can use:

```<code>@media (min-width: 992px) {

  .spacer {
    display: none;
  }
}
</code>```

Body:
I created a spacing-element that uses two classes:

.spacer-mobile-M = spacing height on mobile devices

.spacer-desktop-0 = spacing height on desktop devices (only active @media (min-width: 992px))

.spacer-blank {
    display: block;
    border: 1px solid #000;
}

.spacer-mobile-M {
    height: 20px;
}

@media (min-width: 992px) {
    .spacer-desktop-0 {
        height: 0px;
    }
}

The expected behavior on a 1200px wide screen would be, that the mobile-spacer is being overwritten by the desktop style (higher specificity due to media query and defined later in the code).

However, right now, the desktop spacer is being overwritten by the mobile style.

I only experience this behavior with a spacer that has a lower height than the mobile value.

Is there a rule, that classes with height: 0 or lower height than the general one (without media query) can be overwritten? I can't find anything in Google when I search for specificity.

Thanks for a short hint.

Body:
I think the problem could be use two different CSS classes for the same element. If you use media queries, why don't use the same class? For example:

.spacer {
  display: block;
  height: 20px;
}

@media (min-width: 992px) {

  .spacer {
    height: 0;
  }
}

<div class="spacer" aria-hidden="true"></div>

I don't know the rest of the code, but if on desktop size you want simply hide the spacer also you can use:

@media (min-width: 992px) {

  .spacer {
    display: none;
  }
}