问:
Coach a newbie through basic WPF? (I Do Not Grok It.)
Question is as it sounds. No matter how hard and how often I try to understand WPF, I feel like I'm hitting my head against a wall. I like Winforms, where everything makes sense.

As an example, I'm trying to write a simple app that will allow me to lay out a bunch of 2-D paths (represented by polylines) and drag their vertices around, and have the vertex information synchronised with a presenter (that is, I suppose, a ViewModel)

So the problem is thus:

Make the window recognise an instance of IExtendedObjectPresenter as a data source;

From a collection of IExtendedObject, draw one polyline for each IExtendedObject;

For each vertex in the extended object, represented by the collection IExtendedObject.Points, place a polyline vertex at the specified co-ordinates.

The IDE is giving me no help at all here. None of the many properties available in XAML sound meaningful to me. Because so much seems to be done implicitly, there is no obvious place to just tell the window what to do.

Before I get slated and told to RTFM, I would like to re-emphasise that I have researched the basic concepts of WPF a great many times. I know no more about it than I did when it was first released. It seems totally inpenetrable. Examples given for one type of behaviour are not in any way applicable to an even slightly different kind of behaviour, so you're back to square one. I'm hoping that repetition and targeted exampes might switch a light on in my head at some point.

答:
I'll show how to build a WPF application with MVVM pattern for 2D-Poliline with draggable vertexes.

PointViewModel.cs

```<code>public class PointViewModel: ViewModelBase
{
    public PointViewModel(double x, double y)
    {
        this.Point = new Point(x, y);
    }

    private Point point;

    public Point Point
    {
        get { return point; }
        set
        {
            point = value;
            OnPropertyChanged("Point");
        }
    }
}
</code>```

The class ViewModelBase contains only an implementation of interface INotifyPropertyChanged. This is necessary for reflecting changes of the clr-property on the visual representation.

LineViewModel.cs

```<code>public class LineViewModel
{
    public LineViewModel(PointViewModel start, PointViewModel end)
    {
        this.StartPoint = start;
        this.EndPoint = end;
    }

    public PointViewModel StartPoint { get; set; }
    public PointViewModel EndPoint { get; set; }
}
</code>```

It has references to Points, so the changes will be received automatically.

MainViewModel.cs

```<code>public class MainViewModel
{
    public MainViewModel()
    {
        this.Points = new List<PointViewModel>
        {
            new PointViewModel(30, 30),
            new PointViewModel(60, 100),
            new PointViewModel(50, 120)
        };
        this.Lines = this.Points.Zip(this.Points.Skip(1).Concat(this.Points.Take(1)),
            (p1, p2) => new LineViewModel(p1, p2)).ToList();
    }

    public List<PointViewModel> Points { get; set; }
    public List<LineViewModel> Lines { get; set; }
}
</code>```

It contains a sample data of points and lines

MainVindow.xaml

```<code><Window.Resources>
    <ItemsPanelTemplate x:Key="CanvasPanelTemplate">
        <Canvas/>
    </ItemsPanelTemplate>
    <Style x:Key="PointListBoxItem">
        <Setter Property="Canvas.Left" Value="{Binding Point.X}"/>
        <Setter Property="Canvas.Top" Value="{Binding Point.Y}"/>
    </Style>
    <DataTemplate x:Key="LineTemplate">
        <Line X1="{Binding StartPoint.Point.X}" X2="{Binding EndPoint.Point.X}" Y1="{Binding StartPoint.Point.Y}" Y2="{Binding EndPoint.Point.Y}" Stroke="Blue"/>
    </DataTemplate>
    <DataTemplate x:Key="PointTemplate">
        <view:PointView />
    </DataTemplate>
</Window.Resources>
<Grid>
    <ItemsControl ItemsSource="{Binding Lines}" ItemsPanel="{StaticResource CanvasPanelTemplate}" ItemTemplate="{StaticResource LineTemplate}"/>
    <ItemsControl ItemsSource="{Binding Points}" ItemContainerStyle="{StaticResource PointListBoxItem}" ItemsPanel="{StaticResource CanvasPanelTemplate}"
                  ItemTemplate="{StaticResource PointTemplate}"/>
</Grid>
</code>```

Here is a lot of tricks. First of all, these ItemsControls are based not on vertical StackPanel, but on Canvas. The ItemsControl of points applies a special container template with a goal to place items on necessary coordinates. But the ItemsControl of lines don't require such templates, and it is strange at some point. Two last DataTemplates are obvious.

PointView.xaml

```<code><Ellipse Width="12" Height="12" Stroke="Red" Margin="-6,-6,0,0" Fill="Transparent"/>
</code>```

Left and Top margins are equal to a half of the Width and the Height. We have a transparent Fill because this property doesn't have a default value and the events of mouse don't work.

That's almost all. Only drag-n-drop functionality remains.

PointView.xaml.cs

```<code>public partial class PointView : UserControl
{
    public PointView()
    {
        InitializeComponent();

        this.MouseLeftButtonDown += DragSource_MouseLeftButtonDown;
        this.MouseMove += DragSource_MouseMove;
    }

    private bool isDraggingStarted;

    private void DragSource_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.isDraggingStarted = true;
    }

    private void DragSource_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDraggingStarted == true)
        {
            var vm = this.DataContext as PointViewModel;
            var oldPoint = vm.Point;

            DataObject data = new DataObject("Point", this.DataContext);
            DragDropEffects effects = DragDrop.DoDragDrop(this, data, DragDropEffects.Move);

            if (effects == DragDropEffects.None) //Drag cancelled
                vm.Point = oldPoint;

            this.isDraggingStarted = false;
        }
    }
</code>```

MainVindow.xaml.cs

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();

        this.AllowDrop = true;
        this.DragOver += DropTarget_DragOver;

    }

    private void DropTarget_DragOver(object sender, DragEventArgs e)
    {
        var vm = e.Data.GetData("Point") as PointViewModel;
        if (vm != null)
            vm.Point = e.GetPosition(this);
    }
}
</code>```

So your sample is done using 2 xaml files and 3 viewmodels.

Body:
I'll show how to build a WPF application with MVVM pattern for 2D-Poliline with draggable vertexes.

PointViewModel.cs

public class PointViewModel: ViewModelBase
{
    public PointViewModel(double x, double y)
    {
        this.Point = new Point(x, y);
    }

    private Point point;

    public Point Point
    {
        get { return point; }
        set
        {
            point = value;
            OnPropertyChanged("Point");
        }
    }
}

The class ViewModelBase contains only an implementation of interface INotifyPropertyChanged. This is necessary for reflecting changes of the clr-property on the visual representation.

LineViewModel.cs

public class LineViewModel
{
    public LineViewModel(PointViewModel start, PointViewModel end)
    {
        this.StartPoint = start;
        this.EndPoint = end;
    }

    public PointViewModel StartPoint { get; set; }
    public PointViewModel EndPoint { get; set; }
}

It has references to Points, so the changes will be received automatically.

MainViewModel.cs

public class MainViewModel
{
    public MainViewModel()
    {
        this.Points = new List<PointViewModel>
        {
            new PointViewModel(30, 30),
            new PointViewModel(60, 100),
            new PointViewModel(50, 120)
        };
        this.Lines = this.Points.Zip(this.Points.Skip(1).Concat(this.Points.Take(1)),
            (p1, p2) => new LineViewModel(p1, p2)).ToList();
    }

    public List<PointViewModel> Points { get; set; }
    public List<LineViewModel> Lines { get; set; }
}

It contains a sample data of points and lines

MainVindow.xaml

<Window.Resources>
    <ItemsPanelTemplate x:Key="CanvasPanelTemplate">
        <Canvas/>
    </ItemsPanelTemplate>
    <Style x:Key="PointListBoxItem">
        <Setter Property="Canvas.Left" Value="{Binding Point.X}"/>
        <Setter Property="Canvas.Top" Value="{Binding Point.Y}"/>
    </Style>
    <DataTemplate x:Key="LineTemplate">
        <Line X1="{Binding StartPoint.Point.X}" X2="{Binding EndPoint.Point.X}" Y1="{Binding StartPoint.Point.Y}" Y2="{Binding EndPoint.Point.Y}" Stroke="Blue"/>
    </DataTemplate>
    <DataTemplate x:Key="PointTemplate">
        <view:PointView />
    </DataTemplate>
</Window.Resources>
<Grid>
    <ItemsControl ItemsSource="{Binding Lines}" ItemsPanel="{StaticResource CanvasPanelTemplate}" ItemTemplate="{StaticResource LineTemplate}"/>
    <ItemsControl ItemsSource="{Binding Points}" ItemContainerStyle="{StaticResource PointListBoxItem}" ItemsPanel="{StaticResource CanvasPanelTemplate}"
                  ItemTemplate="{StaticResource PointTemplate}"/>
</Grid>

Here is a lot of tricks. First of all, these ItemsControls are based not on vertical StackPanel, but on Canvas. The ItemsControl of points applies a special container template with a goal to place items on necessary coordinates. But the ItemsControl of lines don't require such templates, and it is strange at some point. Two last DataTemplates are obvious.

PointView.xaml

<Ellipse Width="12" Height="12" Stroke="Red" Margin="-6,-6,0,0" Fill="Transparent"/>

Left and Top margins are equal to a half of the Width and the Height. We have a transparent Fill because this property doesn't have a default value and the events of mouse don't work.

That's almost all. Only drag-n-drop functionality remains.

PointView.xaml.cs

public partial class PointView : UserControl
{
    public PointView()
    {
        InitializeComponent();

        this.MouseLeftButtonDown += DragSource_MouseLeftButtonDown;
        this.MouseMove += DragSource_MouseMove;
    }

    private bool isDraggingStarted;

    private void DragSource_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.isDraggingStarted = true;
    }

    private void DragSource_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDraggingStarted == true)
        {
            var vm = this.DataContext as PointViewModel;
            var oldPoint = vm.Point;

            DataObject data = new DataObject("Point", this.DataContext);
            DragDropEffects effects = DragDrop.DoDragDrop(this, data, DragDropEffects.Move);

            if (effects == DragDropEffects.None) //Drag cancelled
                vm.Point = oldPoint;

            this.isDraggingStarted = false;
        }
    }

MainVindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();

        this.AllowDrop = true;
        this.DragOver += DropTarget_DragOver;

    }

    private void DropTarget_DragOver(object sender, DragEventArgs e)
    {
        var vm = e.Data.GetData("Point") as PointViewModel;
        if (vm != null)
            vm.Point = e.GetPosition(this);
    }
}

So your sample is done using 2 xaml files and 3 viewmodels.


来源: stackexchange

问:
Clustered Index in MySQL
Are clustered index created and stored separately than the actual data in MySQL and if so, then why can we not have more than one clustered index. All we need to do is create another index and store it in memory. </p>

答:
A clustered index is, at least partially, the way the table is physically sorted and stored, i.e. the row order on disk.  That's why you can only have one.  But because it reflects the physical layout of the rows, it's potentially more compact and performant than a typical index.

UPDATE:
As @RickJames excellently points out below, in InnoDB (MySQL's default engine since 5.5.5), a lookup is typically a two-stage process.  One b-tree relates a secondary key to a primary key, a second b-tree relates the primary key to the location of a data record.  If retrieving data on primary key, only the second lookup is necessary.  In that sense, a b-tree lookup is always necessary.

Additionally, according to the MySQL documentation:

Typically, the clustered index is synonymous with the primary key.  1

And the reason it's considered "clustered" and not just a primary key is because InnoDB attempts to order the data records according to primary key and leaves room for future records to be inserted in the correct location in its data pages 2.

Because of that, not only is a query on a InnoDB primary key one fewer b-tree lookup than a secondary index, but the primary key b-tree can be significantly smaller because of the physically ordering of the data on disk.

It stands to reason even if there were a mechanism to make a secondary index that pointed directly to a data record (like an index MyISAM), it wouldn't perform as well as InnoDB's primary/clustered index.

So, it's fundamentally the (at least partial) physical ordering of data records by primary key which prevents you from getting the same performance from a secondary index.

ContentLicense: CC BY-SA 3.0

Title: Clustered Index in MySQL


问:
Hide specific part of passed parameters in URL
I am passing multiple parameters in select form with GET method. I want to hide 3 from 4 parameters in URL after form submit. I have an options with 4 values and the I explode them and get each like that:

```<code><select name="hardware">
<option value="Bitmain AntMiner S9|1-btc-sha-256|14000|1375">BITMAIN AntMiner S9</option>
<option value="Bitmain AntMiner D3|34-dash-x11|15000|1200">BITMAIN AntMiner D3</option>
</select>

<?php
$hardware = $_GET["hardware"];
$hardware_explode = explode('|', $hardware);
echo $hardware_explode[0];
echo $hardware_explode[1];
echo $hardware_explode[2];
echo $hardware_explode[3];
?>
</code>```

in URL it is like that: example.com/calculate.php?hardware=Bitmain+AntMiner+S9%7C1-btc-sha-256%7C13000%7C1375

and I want it to be example.com/calculate.php?hardware=Bitmain+AntMiner+S9

How can I hide this last 3 parameters in JS or PHP?

答: There is no possible way to do it from client side and to hide the query parameters like 1hidden and 1 showing. But you can completely avoid sending values in query parameter by using "POST" method.</p>

Body:
I am passing multiple parameters in select form with GET method. I want to hide 3 from 4 parameters in URL after form submit. I have an options with 4 values and the I explode them and get each like that:

<select name="hardware">
<option value="Bitmain AntMiner S9|1-btc-sha-256|14000|1375">BITMAIN AntMiner S9</option>
<option value="Bitmain AntMiner D3|34-dash-x11|15000|1200">BITMAIN AntMiner D3</option>
</select>

<?php
$hardware = $_GET["hardware"];
$hardware_explode = explode('|', $hardware);
echo $hardware_explode[0];
echo $hardware_explode[1];
echo $hardware_explode[2];
echo $hardware_explode[3];
?>

in URL it is like that: example.com/calculate.php?hardware=Bitmain+AntMiner+S9%7C1-btc-sha-256%7C13000%7C1375

and I want it to be example.com/calculate.php?hardware=Bitmain+AntMiner+S9

How can I hide this last 3 parameters in JS or PHP?


问:
JS: functions arguments default values
In some languages you can set default values for function's arguments:

```<code>function Foo(arg1 = 50, arg2 = 'default') {
    //...
}
</code>```

How do you do it in JavaScript?

答:
In JavaScript, anything that isn't set is given the value undefined. This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:

```<code>function Foo(arg1, arg2) {
    if (typeof(arg1) === "undefined") { arg1 = 50; }
    if (typeof(arg2) === "undefined") { arg2 = "default"; }
}
</code>```

You can take a bit of a short cut if you know roughly what those values will be:

```<code>function Foo(arg1, arg2) {
    arg1 = arg1 || 50;
    arg2 = arg2 || "default";
}
</code>```

However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null, undefined, false or 0 it'll be changed to 50, so be careful if you chose to use it

Title: JS: functions arguments default values

Body:
In some languages you can set default values for function's arguments:

function Foo(arg1 = 50, arg2 = 'default') {
    //...
}

How do you do it in JavaScript?

Body:
In JavaScript, anything that isn't set is given the value undefined. This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:

function Foo(arg1, arg2) {
    if (typeof(arg1) === "undefined") { arg1 = 50; }
    if (typeof(arg2) === "undefined") { arg2 = "default"; }
}

You can take a bit of a short cut if you know roughly what those values will be:

function Foo(arg1, arg2) {
    arg1 = arg1 || 50;
    arg2 = arg2 || "default";
}

However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null, undefined, false or 0 it'll be changed to 50, so be careful if you chose to use it

ContentLicense: CC BY-SA 2.5


问:
How to retrieve Google Directions GPS data from real device
I'm trying to make an application based on Google Directions (Maps) API. Basically, I'll develop a mobile app which will tell users where to navigate with their cars and I'll monitor the actual trip (route followed, time, speed etc). Then, I'll need to process the data retrieved in order to display it on a web platform and compute some statistics.

My questions is, which API should I use and how? I've actually searched about this topic but I couldn't find something useful (like a tutorial) regarding this subject, given the fact that I'm new in this domain and I don't know how to begin and what to do.

Thus, I would really appreciate if you can give me some steps that I must follow in order to accomplish this. Also, all types of materials (tutorials, documentations, articles and anything regarding that subject and tips for really beginners) would be very, very helpful for me!

答:
```<code>Refer the following link for directions API documentation.
</code>```

https://developers.google.com/maps/documentation/directions/intro

```<code>You can refer the following link for parsing directions.
</code>```

https://github.com/jd-alexander/Google-Directions-Android

```<code>On Location Listener,listen continuosly your current location and store in a list and after the trip is completed,You can use that list that which path that the user as travelled and do your algorithm according to your requirement.
</code>```

Body:
Refer the following link for directions API documentation.

https://developers.google.com/maps/documentation/directions/intro

You can refer the following link for parsing directions.

https://github.com/jd-alexander/Google-Directions-Android

On Location Listener,listen continuosly your current location and store in a list and after the trip is completed,You can use that list that which path that the user as travelled and do your algorithm according to your requirement.


问:
reprepro failing to add file: "Skipping inclusion"
I have a few dozen air-gapped machines that I want to upload very specific patches onto. My solution is to create a private repository and have each individual machine updates their /etc/apt/sources.list file. I have a list of deb packages that I want to be in the repository.

I am using this guide to create a private repository HOWTO: Create debian repositories with reprepro using repropro.

When I try to import the a deb package, I get an error:

```<code>$ reprepro -b repo/ includedeb yakkety python3_3.5.1-4_amd64.deb
Skipping inclusion of 'python3' '3.5.1-4' in 'yakkety|main|amd64', as
it has already '3.5.1-4'.
</code>```

I am not certain what is causing this error. Any insights?

答:
Package with same version already in your distribution.
Use
reprepro ls python3
To check it</p>

Body:
I have a few dozen air-gapped machines that I want to upload very specific patches onto. My solution is to create a private repository and have each individual machine updates their /etc/apt/sources.list file. I have a list of deb packages that I want to be in the repository.

I am using this guide to create a private repository HOWTO: Create debian repositories with reprepro using repropro.

When I try to import the a deb package, I get an error:

$ reprepro -b repo/ includedeb yakkety python3_3.5.1-4_amd64.deb
Skipping inclusion of 'python3' '3.5.1-4' in 'yakkety|main|amd64', as
it has already '3.5.1-4'.

I am not certain what is causing this error. Any insights?


问:
sqlite3 database got encrypted?
I was doing some processing on my sqlite3 database power ran out and when I ran DB browser for sqlite3 to open my above mentioned database it prompted me to enter a key that was used to encrypt the database which I never did. I looked in my directory I have a new .db-journal file which I think should help me recover that I have absolutely no idea how to do it. If anyone has had this problem and can help me out I'd really appreciate that.</p>

答:
The SQLite transaction recovery mechanism assumes that the storage system does not change any part of the file that was not written.

But in your case, the beginning of the database file got corrupted, so the database structure is lost.
You have to restore the data from the backup.

Title: sqlite3 database got encrypted?


问:
Split a data.frame column into others columns
I have a big data.frame with some columns, but my 9th column is made of data separated by semicolon :

```<code>    gtf$V9
1                 gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
2  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
3  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
4  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
</code>```

So I would like to cut this column into others columns and merge this later with the other part of the data.frame (the others columns before the 9th column).

I've tried some code without results :

```<code>head(gtf$V9, sep = ";",stringsAsFactors = FALSE)
</code>```

or

```<code>new_df <- matrix(gtf$V9, ncol=7, byrow=TRUE) # sep = ";"
</code>```

The same thing with as.data.frame, data.frame or as.matrix

I have also tried to write.csv and import this with includ a sep=";", but the data.frame is too bigger and my computer is lagging..

Any advice?

Body:
I have a big data.frame with some columns, but my 9th column is made of data separated by semicolon :

    gtf$V9
1                 gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
2  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
3  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
4  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;

So I would like to cut this column into others columns and merge this later with the other part of the data.frame (the others columns before the 9th column).

I've tried some code without results :

head(gtf$V9, sep = ";",stringsAsFactors = FALSE)

or

new_df <- matrix(gtf$V9, ncol=7, byrow=TRUE) # sep = ";"

The same thing with as.data.frame, data.frame or as.matrix

I have also tried to write.csv and import this with includ a sep=";", but the data.frame is too bigger and my computer is lagging..

Any advice?

Body:
Another option is to use the splitstackshape-package (which also loads data.table). Using:

library(splitstackshape)
cSplit(cSplit(df, 'V9', sep = ';', direction = 'long'),
       'V9', sep = ' ')[, dcast(.SD, cumsum(V9_1 == 'gene_id') ~ V9_1)]

gives:

   V9_1  conf_hi  conf_lo       cov exon_number         FPKM     frac gene_id transcript_id
1:    1 9.805420 4.347062 25.616962          NA 7.0762407256 1.000000  CUFF.1      CUFF.1.1
2:    2 9.805420 4.347062 25.616962           1 7.0762407256 1.000000  CUFF.1      CUFF.1.1
3:    3 9.805420 4.347062 25.616962           2 7.0762407256 1.000000  CUFF.1      CUFF.1.1
4:    4 9.805420 4.347062 25.616962           3 7.0762407256 1.000000  CUFF.1      CUFF.1.1


问:
Is it possible to keep Socket.IO client socket active across pages, or simply reconnect?
Is it in any way possible that:

A Socket.IO connection is setup on a certain page

Upon browsing to another page:

Or: The socket is retrieved and re-used from cookies (or similar)

Or: The client is reconnected to the socket with the same socket ID (since the socket ID is linked to a specific session in my case), on the other page.

I need the connection to stay persistent across pages for my application (for synchronising behaviours across multiple devices using the Socket.IO connection).

If it is not possible at all, does WebRTC have the same limitation? Maybe I could use WebRTC in order to solve this problem?

答:
If using single-page-application it is quite simple create connection in root element and use it everywhere.

If not using single-page-application some workaround are as follows:

e.g. we have pages a.html, b.html

1st way(using iframes):

```<code>  1. Wrap all your pages in some iframe let x
  2. Make socket connection in it let mySocketObj
  2. Case 1: a.html/b.html are on different origin:
        > give a xhr/fetch request of a.html/b.html
        > create an iframe tag inside x  let y(don't set any src so as default it will be about:blank)
        > open doc of y and put content of xhr/fetch inside it close doc of y
      Case 2: a.html/b.html are on same origin:
        > create an iframe tag inside x let y.
        > set source as a.html/b.html
  3. add a dynamic script in y as below:
        window.top.mySocketObj = window. mySocketObj
  4. use window.mySocketObj for socket events.
</code>```

2nd Way(using browser extension):

```<code>  1. Make socket connection in extension environment let mySocketObj.
  2. Call/Message extension environment for socket events.
</code>```

3rd way(By altering content page):

```<code>  1. Make socket connection in main page let mySocketObj.
  2. give a xhr/fetch request of a.html/b.html.
  3. put response content in current doc without changing doc/window objects.
  4. use mySocketObj for socket events.
</code>```

Body:
If using single-page-application it is quite simple create connection in root element and use it everywhere.

If not using single-page-application some workaround are as follows:

e.g. we have pages a.html, b.html

1st way(using iframes):

  1. Wrap all your pages in some iframe let x
  2. Make socket connection in it let mySocketObj
  2. Case 1: a.html/b.html are on different origin:
        > give a xhr/fetch request of a.html/b.html
        > create an iframe tag inside x  let y(don't set any src so as default it will be about:blank)
        > open doc of y and put content of xhr/fetch inside it close doc of y
      Case 2: a.html/b.html are on same origin:
        > create an iframe tag inside x let y.
        > set source as a.html/b.html
  3. add a dynamic script in y as below:
        window.top.mySocketObj = window. mySocketObj
  4. use window.mySocketObj for socket events.

2nd Way(using browser extension):

  1. Make socket connection in extension environment let mySocketObj.
  2. Call/Message extension environment for socket events.

3rd way(By altering content page):

  1. Make socket connection in main page let mySocketObj.
  2. give a xhr/fetch request of a.html/b.html.
  3. put response content in current doc without changing doc/window objects.
  4. use mySocketObj for socket events.


问:
How can I refer an object pragmatically in R
```<code>a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000
</code>```

I want to Print each series in programmatic way using a for loop.

```<code>for (i in 1:3)
{
print(paste("a_", i, sep = "")
}
</code>```

Kindly Advise.

答:
If you know you're building several variables of the same kind, put them in a list and use apply functions to do whatever you want:

```<code>a_items <- list(11,12,13)
a_items <- list(a_1 = 11,a_2 = 12) # define list in one go
a_items <- c(a_items,a_3=13)       # or add some later
a_items[[2]]     # 12
a_items[["a_2"]] # 12
a_items
# $a_1
# [1] 11
#
# $a2
# [1] 12
#
# $a_3
# [1] 13
temp <- sapply(names(a_items),function(x) {print(paste("item",x,"has value",a_items[x]))})
# [1] "item a_1 has value 11"
# [1] "item a_2 has value 12"
# [1] "item a_3 has value 13"
</code>```

If you have already a messy workspace, sort it out and do the same:

```<code>banana_1 <- 21
banana_2 <- 22
banana_3 <- 23
potatoe_1 <- 31
potatoe_2 <- 32
potatoe_3 <- 33

var_names <- grep("banana",ls(),value = TRUE)
# [1] "banana_1" "banana_2" "banana_3"

bananas <- mget(var_names)
# $banana_1
# [1] 21
#
# $banana_2
# [1] 22
#
# $banana_3
# [1] 23

#optionally remove the objects so they don't clutter your workspace
rm(list=var_names)

temp <- sapply(names(bananas),function(x) {print(paste("item",x,"has value",bananas[x]))})
# [1] "item banana_1 has value 21"
# [1] "item banana_2 has value 22"
# [1] "item banana_3 has value 23"
</code>```

Body:
a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000

I want to Print each series in programmatic way using a for loop.

for (i in 1:3)
{
print(paste("a_", i, sep = "")
}

Kindly Advise.

Body:
If you know you're building several variables of the same kind, put them in a list and use apply functions to do whatever you want:

a_items <- list(11,12,13)
a_items <- list(a_1 = 11,a_2 = 12) # define list in one go
a_items <- c(a_items,a_3=13)       # or add some later
a_items[[2]]     # 12
a_items[["a_2"]] # 12
a_items
# $a_1
# [1] 11
#
# $a2
# [1] 12
#
# $a_3
# [1] 13
temp <- sapply(names(a_items),function(x) {print(paste("item",x,"has value",a_items[x]))})
# [1] "item a_1 has value 11"
# [1] "item a_2 has value 12"
# [1] "item a_3 has value 13"

If you have already a messy workspace, sort it out and do the same:

banana_1 <- 21
banana_2 <- 22
banana_3 <- 23
potatoe_1 <- 31
potatoe_2 <- 32
potatoe_3 <- 33

var_names <- grep("banana",ls(),value = TRUE)
# [1] "banana_1" "banana_2" "banana_3"

bananas <- mget(var_names)
# $banana_1
# [1] 21
#
# $banana_2
# [1] 22
#
# $banana_3
# [1] 23

#optionally remove the objects so they don't clutter your workspace
rm(list=var_names)

temp <- sapply(names(bananas),function(x) {print(paste("item",x,"has value",bananas[x]))})
# [1] "item banana_1 has value 21"
# [1] "item banana_2 has value 22"
# [1] "item banana_3 has value 23"


问:
what's the BestPractice for Docker logging?
Im using docker with my Web service.

when I deploy using Docker, loosing some logging files (nginx accesslog, service log, system log.. etc)

Cause, docker deployment system using down and up container architecures.

So I thought about this problem.
LoggingServer and serviceServer(for api) must seperate!

using these, methods..

First, Using logstash(in elk)(attaching all my logFile) .
Second, Using batch system, this batch system will moves logfiles to otherServer on every midnight.

isn't it okay?

I expect a better answer.

thanks.

答:
There are many ways for logging which most the admin uses for containers

1 ) mount log directory to host , so even if docker goes up/down logs will be persisted on host.

2) ELK server, using logstash/filebeat for pushing logs to elastic search server with tailing option of file, so if new log contents it pushes to server.

3) if there is application logs like maven based projects, then there are many plugins which pushes logs to server

4) batch system , which is not recommended because if containers dies before mid-night then logs will be lost.


问:
How do I include other files in PHP?
I just started creating a website at my home.

Absolutely, I must have these two pages to finish my website rapidly:- footer.php, header.php.

So I created those pages & put  some contents. Also created an index page as index.php inside the htdocs folder.

Then I did include the header & footer pages inside the index.php page by using these following codes.

```<code><?php include 'header.php'; ?>
<?php include 'footer.php'; ?>
</code>```

Undoubtedly, they worked fine without any trouble.

Then I created a directory as account inside the htdocs.

Now I've a login.php page inside the account directory (/account/login.php).

Repeatedly I used those same codes to include the header & footer in the login page. But they didn't work! I saw nothing is happening. If I create the login.php page inside of the  htdocs folder (not in htdocs/account/), so it works.

So, how can I include them while the login page is in account directory?

答:
When creating sub directories and including files it is always simpler to use absolute file paths.

The path with reference to root directory is called absolute (https://www.website.com/modules/header.php), you can even remove the domain and just have /modules/header.php. The path with reference to current directory is called relative (../images/phone.png). The ../ indicates that the URL points to the directory above the current folder.

Please see answers relating to a similar question here: difference-between-relative-path-and-absolute-path-in-javascript

ContentLicense: CC BY-SA 4.0

Title: How do I include other files in PHP?

Body:
I just started creating a website at my home.

Absolutely, I must have these two pages to finish my website rapidly:- footer.php, header.php.

So I created those pages & put  some contents. Also created an index page as index.php inside the htdocs folder.

Then I did include the header & footer pages inside the index.php page by using these following codes.

<?php include 'header.php'; ?>
<?php include 'footer.php'; ?>

Undoubtedly, they worked fine without any trouble.

Then I created a directory as account inside the htdocs.

Now I've a login.php page inside the account directory (/account/login.php).

Repeatedly I used those same codes to include the header & footer in the login page. But they didn't work! I saw nothing is happening. If I create the login.php page inside of the  htdocs folder (not in htdocs/account/), so it works.

So, how can I include them while the login page is in account directory?


问:
pass data from a TableView to the contained Views of a PageViewController
I have a tableview with a list of names and what I wish to have is when pressing one of the cells inside the tableview to pass the name content of the cell to an upcoming page view controller containing 2 different views.  I am using a library called pulley in which I am not able to do segues by pushing modally so inside of the 'didSelectRow' method I am doing this

```<code>let pagevc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PageVC") as! PageViewController

(parent as? PulleyViewController)?.setDrawerContentViewController(controller: pagevc, animated: true)
</code>```

to accomplish the segue to the pageviewcontroller. This should be right.
But the 2 Views inside the pageviewcontroller View, they all need the Name of the selected cell. So I did this:

```<code>pagevc.name = selBarName
</code>```

and to be sure i did the same for the 2 views of the page controller like  this(still inside of didSelectRow method of the previous tableview class):

```<code>let detvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailVC") as! DetailVC
    detvc.barname = selBarName

    let speisevc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SpeisekarteVC") as! SpeisekarteVC

    speisevc.barname = selBarName
</code>```

but printing the var barname in each class shows that the var is still an empty string. Only the var name of pagevc has changed to the wanted Name.
So I instantiated the two views inside viewdidload of the PageViewController Class but it still doesn't pass the data from the pagevc to the other 2 views contained in the pagevc.

I hope I could make the problem clear. If you need more input tell me what is missing. Basically I just need to know how to pass a String from the PageViewController to its contained Views. By now i am able to pass the name of the selected cell to the pageviewcontroller but not to the views that are presented by the pageviewcontroller.

Edit:

The PageController itself should be correct because using just 2 empty views inside it which doesn't require the var name works all fine.

Here is part of the class PageViewController just to make things complete:

```<code>class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {

    var name = ""

    var pageControl = UIPageControl()

    lazy var orderedViewControllers: [UIViewController] = {
        return [self.newVc(viewController: "DetailVC"),
                self.newVc(viewController: "SpeisekarteVC")]
    }()

    override func viewDidLoad() {
        print(name, "hierpageview") //THIS NAME IS PRINTED CORRECTLY AS WISHED
        super.viewDidLoad()
        self.dataSource = self
        self.delegate = self

        let speisevc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SpeisekarteVC") as! SpeisekarteVC

        speisevc.barname = name

        let detvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailVC") as! DetailVC
        detvc.barname = name
        print(detvc.barname, "dhdhfhdah") //THIS ONE IS ALSO PRINTED RIGHT BUT PRINTING IT INSIDE THE ACTUAL CLASS RETURNS AGAIN AN EMPTY STRING !!!

        if let firstViewController = orderedViewControllers.first {
            setViewControllers([firstViewController],
                               direction: .forward,
                               animated: true,
                               completion: nil)

        }

     func newVc(viewController: String) -> UIViewController {
        return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: viewController)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
            return nil
        }

        let previousIndex = viewControllerIndex - 1

        guard previousIndex >= 0 else {

             return nil
        }

        guard orderedViewControllers.count > previousIndex else {
            return nil
        }

        return orderedViewControllers[previousIndex]
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
            return nil
        }

        let nextIndex = viewControllerIndex + 1
        let orderedViewControllersCount = orderedViewControllers.count

        guard orderedViewControllersCount != nextIndex else {

             return nil
        }

        guard orderedViewControllersCount > nextIndex else {
            return nil
        }

        return orderedViewControllers[nextIndex]
    }

}

    }
</code>```

答:
You can do this by :

Create a string in your destination root controller.
(say for example let barName : String = "")

In your didSelectRow method, store the data into the string against your desired indexPath. (say for ex., view.barName //name of your string = // value you want to store, for example if it is an array then maybe myArr[indexPath.row])

Then in your destinationViewController, in viewDidLoad method, push value onto the desired label. (say for ex., yourLbl.text = barName)

Body:
I have a tableview with a list of names and what I wish to have is when pressing one of the cells inside the tableview to pass the name content of the cell to an upcoming page view controller containing 2 different views.  I am using a library called pulley in which I am not able to do segues by pushing modally so inside of the 'didSelectRow' method I am doing this

let pagevc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PageVC") as! PageViewController

(parent as? PulleyViewController)?.setDrawerContentViewController(controller: pagevc, animated: true)

to accomplish the segue to the pageviewcontroller. This should be right.
But the 2 Views inside the pageviewcontroller View, they all need the Name of the selected cell. So I did this:

pagevc.name = selBarName

and to be sure i did the same for the 2 views of the page controller like  this(still inside of didSelectRow method of the previous tableview class):

let detvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailVC") as! DetailVC
    detvc.barname = selBarName

    let speisevc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SpeisekarteVC") as! SpeisekarteVC

    speisevc.barname = selBarName

but printing the var barname in each class shows that the var is still an empty string. Only the var name of pagevc has changed to the wanted Name.
So I instantiated the two views inside viewdidload of the PageViewController Class but it still doesn't pass the data from the pagevc to the other 2 views contained in the pagevc.

I hope I could make the problem clear. If you need more input tell me what is missing. Basically I just need to know how to pass a String from the PageViewController to its contained Views. By now i am able to pass the name of the selected cell to the pageviewcontroller but not to the views that are presented by the pageviewcontroller.

Edit:

The PageController itself should be correct because using just 2 empty views inside it which doesn't require the var name works all fine.

Here is part of the class PageViewController just to make things complete:

class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {

    var name = ""

    var pageControl = UIPageControl()

    lazy var orderedViewControllers: [UIViewController] = {
        return [self.newVc(viewController: "DetailVC"),
                self.newVc(viewController: "SpeisekarteVC")]
    }()

    override func viewDidLoad() {
        print(name, "hierpageview") //THIS NAME IS PRINTED CORRECTLY AS WISHED
        super.viewDidLoad()
        self.dataSource = self
        self.delegate = self

        let speisevc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SpeisekarteVC") as! SpeisekarteVC

        speisevc.barname = name

        let detvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailVC") as! DetailVC
        detvc.barname = name
        print(detvc.barname, "dhdhfhdah") //THIS ONE IS ALSO PRINTED RIGHT BUT PRINTING IT INSIDE THE ACTUAL CLASS RETURNS AGAIN AN EMPTY STRING !!!

        if let firstViewController = orderedViewControllers.first {
            setViewControllers([firstViewController],
                               direction: .forward,
                               animated: true,
                               completion: nil)

        }

     func newVc(viewController: String) -> UIViewController {
        return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: viewController)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
            return nil
        }

        let previousIndex = viewControllerIndex - 1

        guard previousIndex >= 0 else {

             return nil
        }

        guard orderedViewControllers.count > previousIndex else {
            return nil
        }

        return orderedViewControllers[previousIndex]
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
            return nil
        }

        let nextIndex = viewControllerIndex + 1
        let orderedViewControllersCount = orderedViewControllers.count

        guard orderedViewControllersCount != nextIndex else {

             return nil
        }

        guard orderedViewControllersCount > nextIndex else {
            return nil
        }

        return orderedViewControllers[nextIndex]
    }

}

    }


问:
Xamarin : Date in string
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label inside listview-viewcell, to show time in UI. The date is received as a number like 1510822596449(Java Timestamp). I want to show the date in strings like "n days ago".How can I achieve this?

```<code>    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Label Text="{Binding createdTime}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

Anybody please suggest a solution with working code.
Thanks in advance.

答:
First, create a class DatetimeToStringConverter and add the following code:

```<code>   public class DatetimeToStringConverter : IValueConverter
      {
    #region IValueConverter implementation

     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return string.Empty;

       return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            .AddMilliseconds((long)value) // put your value here
             .ToLocalTime().ToString("g");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
</code>```

Then in xaml add the following code at the root of the page:

```<code>    <ContentPage.Resources>
        <ResourceDictionary>
            <local:DatetimeToStringConverter x:Key="cnvDateTimeConverter"></local:DatetimeToStringConverter>
        </ResourceDictionary>
    </ContentPage.Resources>
</code>```

Then add namespace:

```<code>      xmlns:local="clr-namespace:Myapp;assembly=Myapp"
</code>```

Then change the label text like this:

```<code>Text="{Binding createdTime,  Converter={StaticResource cnvDateTimeConverter}}"
</code>```

Keep the createTime type as long in model, otherwise you get invalid cast exception.

Title: Xamarin : Date in string

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label inside listview-viewcell, to show time in UI. The date is received as a number like 1510822596449(Java Timestamp). I want to show the date in strings like "n days ago".How can I achieve this?

    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

Anybody please suggest a solution with working code.
Thanks in advance.

Body:
First, create a class DatetimeToStringConverter and add the following code:

   public class DatetimeToStringConverter : IValueConverter
      {
    #region IValueConverter implementation

     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return string.Empty;

       return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            .AddMilliseconds((long)value) // put your value here
             .ToLocalTime().ToString("g");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Then in xaml add the following code at the root of the page:

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:DatetimeToStringConverter x:Key="cnvDateTimeConverter"></local:DatetimeToStringConverter>
        </ResourceDictionary>
    </ContentPage.Resources>

Then add namespace:

      xmlns:local="clr-namespace:Myapp;assembly=Myapp"

Then change the label text like this:

Text="{Binding createdTime,  Converter={StaticResource cnvDateTimeConverter}}"

Keep the createTime type as long in model, otherwise you get invalid cast exception.


问:
Extend SAP Fiori crud app with a button to get to a new view and load there data from OData
I´m pretty new in this SAP fiori world and now I´m trying to extend a SAP Fiori Crud Application. I´ll briefly explain what the app shoud do:
 enter image description here

•   In the MasterView i get the name of all the workers (and this works good!);
•   When I click on one worker from the MasterView I get a list of all the projects available for this specifical worker in the DetailView (In other words: all the projects, where that worker works: and this works as well!);
•   When I click on the button "Projekt hinzufügen" (down, on the right, in the DetailView: in english it means "add a new Project"), a new view (the "addProject.view") should open (Till here it works, the addProjectView actually opens!).
From here on I need your help: In this new View I should have the possibility to load all the available project, in order to add one or more project for that worker which was originally selected in the MasterView.I tried to load some data in these new view, just to see if everything was loaded in the right way before starting with all the List/Checkboxes work. For example I loaded in this new view the WorkerSet (the same which appears in the Master View) and this works, but as soon as I try to load  the ProjectSet (the same which is shown in the DetailView) no data are shown! I don´t know what I´m doing wrong!!

Here you find the last part of the manifest.json (I hope i set everything in the right way for "routes" and "targets")...  PS: "Mitarbeiter" means "worker" ;-)

```<code> {.....},
    "sap.ui5": {
        "rootView": {
            "viewName": "de.paricon.Mitarbeiter.view.App",
            "type": "XML",
            "id": "app"
        },
        "dependencies": {
            "minUI5Version": "1.30.0",
            "libs": {
                "sap.ui.core": {},
                "sap.m": {},
                "sap.ui.layout": {},
                "sap.f": {},
                "sap.ushell": {},
                "sap.collaboration": {},
                "sap.ui.comp": {},
                "sap.uxap": {}
            }
        },
        "contentDensities": {
            "compact": true,
            "cozy": true
        },
        "models": {
            "i18n": {
                "type": "sap.ui.model.resource.ResourceModel",
                "settings": {
                    "bundleName": "de.paricon.Mitarbeiter.i18n.i18n"
                }
            },
            "": {
                "dataSource": "mainService",
                "settings": {
                    "metadataUrlParams": {
                        "sap-documentation": "heading"
                    },
                    "defaultBindingMode": "TwoWay"
                }
            }
        },
        "routing": {
            "config": {
                "routerClass": "sap.m.routing.Router",
                "viewType": "XML",
                "viewPath": "de.paricon.Mitarbeiter.view",
                "controlId": "idAppControl",
                "controlAggregation": "detailPages",
                "bypassed": {
                    "target": [
                        "master",
                        "notFound"
                    ]
                },
                "async": true
            },
            "routes": [
                {
                    "pattern": "",
                    "name": "master",
                    "target": [
                        "object",
                        "master"
                    ]
                },
                {
                    "pattern": "MitarbeiterSet/{Mitarbeiterid}",
                    "name": "object",
                    "target": [
                        "master",
                        "object"
                    ]
                },
                {
                    "pattern": "addProject",
                    "name": "addProject",
                    "target": "addProject"
                }
            ],
            "targets": {
                "master": {
                    "viewName": "Master",
                    "viewLevel": 1,
                    "viewId": "master",
                    "controlAggregation": "masterPages"
                },
                "object": {
                    "viewName": "Detail",
                    "viewId": "detail",
                    "viewLevel": 2
                },
                "create": {
                    "viewName": "CreateEntity",
                    "viewLevel": 2
                },
                "detailObjectNotFound": {
                    "viewName": "DetailObjectNotFound",
                    "viewId": "detailObjectNotFound"
                },
                "detailNoObjectsAvailable": {
                    "viewName": "DetailNoObjectsAvailable",
                    "viewId": "detailNoObjectsAvailable"
                },
                "notFound": {
                    "viewName": "NotFound",
                    "viewId": "notFound"
                },
                "addProject": {
                    "viewType": "XML",
                    "viewName": "addProject"
                }
            }
        }
    },
    "sap.platform.hcp": {
        "uri": "",
        "_version": "1.1.0"
    }
}
</code>```

here is the Button in the Detail.view.xml:

```<code><Button xmlns:mvc="sap.ui.core.mvc" xmlns:semantic="sap.m.semantic" xmlns:footerbar="sap.ushell.ui.footerbar" xmlns="sap.m" id="about" visible="true" text="Projekt hinzufügen" enabled="true" icon="sap-icon://add-activity" press="onNewProject">
                    </Button>
</code>```

here ist the Detail.controller.js for the on press event of the button:

```<code> onNewProject: function(oEvent) {
            //This code was generated by the layout editor.
        var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
        oRouter.navTo("addProject");
  }
</code>```

In the addProject.controller.js i haven´t done anything: could it be the onInit function my solution? If yes, I still don´t understand why the WorkerSet is shown, while the ProjectSet isn´t....

Let me know if you need more information

答:
Hello Tatiana and first of all feel welcome to the „SAP Fiori World“!
I believe the reason for your view “addProject.view” to not display the collection “ProjectSet” is because the view should be binded to that dataset.
So in a Master/Detail Pattern, the binding takes place through different ways:
In the master view - for instance, the binding is carried out in the file Master.view.xml :

```<code>            <List
            id="list"
            items="{
                **path: '/WorkerSet'**,
                  ...
            }"
</code>```

The object “list” is binded to the WorkerSet collection.

The binding in the detail is carried out in the Detail.controller.js and is being made based on the routing parameters:

```<code>            _onObjectMatched : function (oEvent) {
            var sObjectId =  oEvent.getParameter("arguments").objectId;
            this.getModel().metadataLoaded().then( function() {
                var sObjectPath = this.getModel().createKey("ProductSet", {
                    ProductId :  sObjectId
                });
                **this._bindView("/" + sObjectPath)**;
            }.bind(this));
        },
</code>```

And in fact, the whole view is binded (not only an control but the entire view)

Ok so once you are in the “addProject.view” make sure you bind either a combobox (or whatever UI Element you use for selecting the new project), or you bind the entire view to the collection “ProjectSet”

I hope I have understood the question and this answer helps you.
Best regards,
Gabriel

Body:
I´m pretty new in this SAP fiori world and now I´m trying to extend a SAP Fiori Crud Application. I´ll briefly explain what the app shoud do:
 enter image description here

•   In the MasterView i get the name of all the workers (and this works good!);
•   When I click on one worker from the MasterView I get a list of all the projects available for this specifical worker in the DetailView (In other words: all the projects, where that worker works: and this works as well!);
•   When I click on the button "Projekt hinzufügen" (down, on the right, in the DetailView: in english it means "add a new Project"), a new view (the "addProject.view") should open (Till here it works, the addProjectView actually opens!).
From here on I need your help: In this new View I should have the possibility to load all the available project, in order to add one or more project for that worker which was originally selected in the MasterView.I tried to load some data in these new view, just to see if everything was loaded in the right way before starting with all the List/Checkboxes work. For example I loaded in this new view the WorkerSet (the same which appears in the Master View) and this works, but as soon as I try to load  the ProjectSet (the same which is shown in the DetailView) no data are shown! I don´t know what I´m doing wrong!!

Here you find the last part of the manifest.json (I hope i set everything in the right way for "routes" and "targets")...  PS: "Mitarbeiter" means "worker" ;-)

 {.....},
    "sap.ui5": {
        "rootView": {
            "viewName": "de.paricon.Mitarbeiter.view.App",
            "type": "XML",
            "id": "app"
        },
        "dependencies": {
            "minUI5Version": "1.30.0",
            "libs": {
                "sap.ui.core": {},
                "sap.m": {},
                "sap.ui.layout": {},
                "sap.f": {},
                "sap.ushell": {},
                "sap.collaboration": {},
                "sap.ui.comp": {},
                "sap.uxap": {}
            }
        },
        "contentDensities": {
            "compact": true,
            "cozy": true
        },
        "models": {
            "i18n": {
                "type": "sap.ui.model.resource.ResourceModel",
                "settings": {
                    "bundleName": "de.paricon.Mitarbeiter.i18n.i18n"
                }
            },
            "": {
                "dataSource": "mainService",
                "settings": {
                    "metadataUrlParams": {
                        "sap-documentation": "heading"
                    },
                    "defaultBindingMode": "TwoWay"
                }
            }
        },
        "routing": {
            "config": {
                "routerClass": "sap.m.routing.Router",
                "viewType": "XML",
                "viewPath": "de.paricon.Mitarbeiter.view",
                "controlId": "idAppControl",
                "controlAggregation": "detailPages",
                "bypassed": {
                    "target": [
                        "master",
                        "notFound"
                    ]
                },
                "async": true
            },
            "routes": [
                {
                    "pattern": "",
                    "name": "master",
                    "target": [
                        "object",
                        "master"
                    ]
                },
                {
                    "pattern": "MitarbeiterSet/{Mitarbeiterid}",
                    "name": "object",
                    "target": [
                        "master",
                        "object"
                    ]
                },
                {
                    "pattern": "addProject",
                    "name": "addProject",
                    "target": "addProject"
                }
            ],
            "targets": {
                "master": {
                    "viewName": "Master",
                    "viewLevel": 1,
                    "viewId": "master",
                    "controlAggregation": "masterPages"
                },
                "object": {
                    "viewName": "Detail",
                    "viewId": "detail",
                    "viewLevel": 2
                },
                "create": {
                    "viewName": "CreateEntity",
                    "viewLevel": 2
                },
                "detailObjectNotFound": {
                    "viewName": "DetailObjectNotFound",
                    "viewId": "detailObjectNotFound"
                },
                "detailNoObjectsAvailable": {
                    "viewName": "DetailNoObjectsAvailable",
                    "viewId": "detailNoObjectsAvailable"
                },
                "notFound": {
                    "viewName": "NotFound",
                    "viewId": "notFound"
                },
                "addProject": {
                    "viewType": "XML",
                    "viewName": "addProject"
                }
            }
        }
    },
    "sap.platform.hcp": {
        "uri": "",
        "_version": "1.1.0"
    }
}

here is the Button in the Detail.view.xml:

<Button xmlns:mvc="sap.ui.core.mvc" xmlns:semantic="sap.m.semantic" xmlns:footerbar="sap.ushell.ui.footerbar" xmlns="sap.m" id="about" visible="true" text="Projekt hinzufügen" enabled="true" icon="sap-icon://add-activity" press="onNewProject">
                    </Button>

here ist the Detail.controller.js for the on press event of the button:

 onNewProject: function(oEvent) {
            //This code was generated by the layout editor.
        var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
        oRouter.navTo("addProject");
  }

In the addProject.controller.js i haven´t done anything: could it be the onInit function my solution? If yes, I still don´t understand why the WorkerSet is shown, while the ProjectSet isn´t....

Let me know if you need more information

Body:
Hello Tatiana and first of all feel welcome to the „SAP Fiori World“!
I believe the reason for your view “addProject.view” to not display the collection “ProjectSet” is because the view should be binded to that dataset.
So in a Master/Detail Pattern, the binding takes place through different ways:
In the master view - for instance, the binding is carried out in the file Master.view.xml :

            <List
            id="list"
            items="{
                **path: '/WorkerSet'**,
                  ...
            }"

The object “list” is binded to the WorkerSet collection.

The binding in the detail is carried out in the Detail.controller.js and is being made based on the routing parameters:

            _onObjectMatched : function (oEvent) {
            var sObjectId =  oEvent.getParameter("arguments").objectId;
            this.getModel().metadataLoaded().then( function() {
                var sObjectPath = this.getModel().createKey("ProductSet", {
                    ProductId :  sObjectId
                });
                **this._bindView("/" + sObjectPath)**;
            }.bind(this));
        },

And in fact, the whole view is binded (not only an control but the entire view)

Ok so once you are in the “addProject.view” make sure you bind either a combobox (or whatever UI Element you use for selecting the new project), or you bind the entire view to the collection “ProjectSet”

I hope I have understood the question and this answer helps you.
Best regards,
Gabriel


问:
Debugging an AsyncTask
I have the created the following Async function-

```<code>private class CustomAsyncUtil extends AsyncTask<String, Void, String> {

    private void CreateDocument(){
        try
        {
            //doing some work
        }
        catch (Exception ex)
        {
            String exp = ex.getMessage();
        }
    }

    @Override
    protected String doInBackground(String[] params) {
        if(android.os.Debug.isDebuggerConnected())
            android.os.Debug.waitForDebugger();
        CustomAsyncUtil objUtil = new CustomAsyncUtil();
        objUtil.CreateDocument();
        return "some message";
    }

    @Override
    protected void onPostExecute(String message) {
        //process message
    }
}
</code>```

I am calling the function like this-

```<code>CustomAsyncUtil objUtil = new CustomAsyncUtil();
objUtil.execute();
</code>```

To be debug I have added if(android.os.Debug.isDebuggerConnected()) inside doInBackground() but I don't get a break point inside CreateDocument(). Any idea what I am doing wrong?

答:
When you call

```<code>CustomAsyncUtil objUtil = new CustomAsyncUtil();
objUtil.CreateDocument();
</code>```

you are calling CreateDocument() on a different async task object.  If you want to call this helper method inside the same async task, then just call it directly:

```<code>CreateDocument();
</code>```

An AsyncTask has a number of lifecycle methods, the most basic of which include:

```<code>onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
</code>```

In general, all the work you do in an async task will originate in one of these entry points, then possibly including helper methods you call from the lifecycle methods.

Title: Debugging an AsyncTask

Body:
I have the created the following Async function-

private class CustomAsyncUtil extends AsyncTask<String, Void, String> {

    private void CreateDocument(){
        try
        {
            //doing some work
        }
        catch (Exception ex)
        {
            String exp = ex.getMessage();
        }
    }

    @Override
    protected String doInBackground(String[] params) {
        if(android.os.Debug.isDebuggerConnected())
            android.os.Debug.waitForDebugger();
        CustomAsyncUtil objUtil = new CustomAsyncUtil();
        objUtil.CreateDocument();
        return "some message";
    }

    @Override
    protected void onPostExecute(String message) {
        //process message
    }
}

I am calling the function like this-

CustomAsyncUtil objUtil = new CustomAsyncUtil();
objUtil.execute();

To be debug I have added if(android.os.Debug.isDebuggerConnected()) inside doInBackground() but I don't get a break point inside CreateDocument(). Any idea what I am doing wrong?

Body:
When you call

CustomAsyncUtil objUtil = new CustomAsyncUtil();
objUtil.CreateDocument();

you are calling CreateDocument() on a different async task object.  If you want to call this helper method inside the same async task, then just call it directly:

CreateDocument();

An AsyncTask has a number of lifecycle methods, the most basic of which include:

onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()

In general, all the work you do in an async task will originate in one of these entry points, then possibly including helper methods you call from the lifecycle methods.


问:
static const uint8_t inside function changes value
I am writing a small analysis tool using libpcap that sniffs traffic on an ethernet device and performs some sort of analysis on the received packets. In order to do so, I have the obvious libpcap loop:

```<code>void packet_loop(u_char *args, const struct pcap_pkthdr *header,
        const u_char *packetdata) {
    int size = (int)header->len;

    //Before we map the buffer to the ethhdr struct,
    //we check if the size fits
    if (ETHER_HDR_LEN > size)
        return;

    const struct ethhdr *ethh = (const struct ethhdr *)(packetdata);

    //If this protocol is IPv4 and the packet size is bigger than
    //ETH hdr size
    if (ETHERTYPE_IP == ntohs(ethh->h_proto)) {

        //Before we map the buffer to the iph struct,
        //we check if the size fits
        if (ETHER_HDR_LEN + (int)sizeof(struct iphdr) > size)
            return;

        const struct iphdr *iph = (const struct iphdr*)
            (packetdata + sizeof(struct ethhdr));

        //If this protocol isn't UDP and the header length
        //isn't 5 (20bytes)
        if (IPPROTO_UDP != iph->protocol && 5 != iph->ihl)
            return;

        //eval_udp(packetdata, size);
        const struct udphdr *udph = (const struct udphdr*)
            (packetdata + sizeof(struct ethhdr) +
             sizeof(struct iphdr));

        if (DATA_SRCPORT == ntohs(udph->uh_sport) &&
            DATA_DESTPORT == ntohs(udph->uh_dport)) {
            analyse_data(packetdata);
        }
    }
}
</code>```

that calls the follwoing code snipped on receival of a specific packet type. As you can see, I am using a static variable to keep track of the previous packet, in order to compare two.

```<code>void analyse_data(const uint8_t *packet)
{
    if (!packet)
        return;

    static const uint8_t *basepacket;

    //If there was no packet to base our analysis on, we will wait for one
    if (!basepacket) {
        basepacket = packet;
        return;
    }

    const struct dataheader *basedh = (const struct dataheader *)
          (__OFFSETSHERE__ + basepacket);
    const struct dataheader *dh = (const struct dataheader *)
          (__OFFSETSHERE__ + packet);

    printf("%d -> %d\n", ntohs(basedh->sequenceid),
                         ntohs(dh->sequenceid));

    basepacket = packet;
    return;
}
</code>```

struct dataheader is a regular struct, just like etthdr. I would expect a constant printout like:

```<code>0 -> 1
1 -> 2
2 -> 3
</code>```

Unfortunately, I get a different printout, which is mostly right. But around every 20th-40th packet, I see the following behavior (example):

```<code>12->13
13->14
0->15
15->16
...
</code>```

It is maybe interesting to note that this does NOT occcur, when I receive only packets of the specific type I look after (8-10 Mbit/s). Nevertheless, as soon as I use my tool in the "regular" network environment (around 100Mbit/s), I get this behavior. I checked my if statement, that filters the packet it works flawlessly (checking UDP source and destination ports). Wireshark also shows me that there is not a single packet on those ports that is not of that specific type.

答:
libpcap controls the packet data it passes in to your packet_loop. Once packet_loop returns, you have no guarantee what the pointers for the packet data point to - libpcap could throw the packet away, or it could reuse the same space for a new packet.

This means if you want to compare 2 packets, you must make a copy of the 1. packet - you cannot save the pointer from one call to packet_loop and expect that pointer to be valid and point to the same packet in future calls to packet_loop. So your code could be changed to e.g.

```<code>void analyse_data(const uint8_t *packet, int size )
{
    if (!packet)
        return;

    static const uint8_t basepacket[1024*64];
    static int has_basepacket;

    //If there was no packet to base our analysis on, we will wait for one
    if (!has_basepacket){
        if (size < sizeof basepacket) {
            memcpy(basepacket, packet, size);
            has_basepacket = 1;
         }
        return;
    }
    ...
</code>```

Also, make sure your verify the sizes everywhere. Just because the ethernet type says it is an IPv4 packet, doesn't mean you can trust it to contain a full IP packet. Just because the IP header says it is 20 bytes, doesn't mean you can trust it to contain a full IP packet, and so on for all the layers you attempt to decode.

Body:
I am writing a small analysis tool using libpcap that sniffs traffic on an ethernet device and performs some sort of analysis on the received packets. In order to do so, I have the obvious libpcap loop:

void packet_loop(u_char *args, const struct pcap_pkthdr *header,
        const u_char *packetdata) {
    int size = (int)header->len;

    //Before we map the buffer to the ethhdr struct,
    //we check if the size fits
    if (ETHER_HDR_LEN > size)
        return;

    const struct ethhdr *ethh = (const struct ethhdr *)(packetdata);

    //If this protocol is IPv4 and the packet size is bigger than
    //ETH hdr size
    if (ETHERTYPE_IP == ntohs(ethh->h_proto)) {

        //Before we map the buffer to the iph struct,
        //we check if the size fits
        if (ETHER_HDR_LEN + (int)sizeof(struct iphdr) > size)
            return;

        const struct iphdr *iph = (const struct iphdr*)
            (packetdata + sizeof(struct ethhdr));

        //If this protocol isn't UDP and the header length
        //isn't 5 (20bytes)
        if (IPPROTO_UDP != iph->protocol && 5 != iph->ihl)
            return;

        //eval_udp(packetdata, size);
        const struct udphdr *udph = (const struct udphdr*)
            (packetdata + sizeof(struct ethhdr) +
             sizeof(struct iphdr));

        if (DATA_SRCPORT == ntohs(udph->uh_sport) &&
            DATA_DESTPORT == ntohs(udph->uh_dport)) {
            analyse_data(packetdata);
        }
    }
}

that calls the follwoing code snipped on receival of a specific packet type. As you can see, I am using a static variable to keep track of the previous packet, in order to compare two.

void analyse_data(const uint8_t *packet)
{
    if (!packet)
        return;

    static const uint8_t *basepacket;

    //If there was no packet to base our analysis on, we will wait for one
    if (!basepacket) {
        basepacket = packet;
        return;
    }

    const struct dataheader *basedh = (const struct dataheader *)
          (__OFFSETSHERE__ + basepacket);
    const struct dataheader *dh = (const struct dataheader *)
          (__OFFSETSHERE__ + packet);

    printf("%d -> %d\n", ntohs(basedh->sequenceid),
                         ntohs(dh->sequenceid));

    basepacket = packet;
    return;
}

struct dataheader is a regular struct, just like etthdr. I would expect a constant printout like:

0 -> 1
1 -> 2
2 -> 3

Unfortunately, I get a different printout, which is mostly right. But around every 20th-40th packet, I see the following behavior (example):

12->13
13->14
0->15
15->16
...

It is maybe interesting to note that this does NOT occcur, when I receive only packets of the specific type I look after (8-10 Mbit/s). Nevertheless, as soon as I use my tool in the "regular" network environment (around 100Mbit/s), I get this behavior. I checked my if statement, that filters the packet it works flawlessly (checking UDP source and destination ports). Wireshark also shows me that there is not a single packet on those ports that is not of that specific type.

Body:
libpcap controls the packet data it passes in to your packet_loop. Once packet_loop returns, you have no guarantee what the pointers for the packet data point to - libpcap could throw the packet away, or it could reuse the same space for a new packet.

This means if you want to compare 2 packets, you must make a copy of the 1. packet - you cannot save the pointer from one call to packet_loop and expect that pointer to be valid and point to the same packet in future calls to packet_loop. So your code could be changed to e.g.

void analyse_data(const uint8_t *packet, int size )
{
    if (!packet)
        return;

    static const uint8_t basepacket[1024*64];
    static int has_basepacket;

    //If there was no packet to base our analysis on, we will wait for one
    if (!has_basepacket){
        if (size < sizeof basepacket) {
            memcpy(basepacket, packet, size);
            has_basepacket = 1;
         }
        return;
    }
    ...

Also, make sure your verify the sizes everywhere. Just because the ethernet type says it is an IPv4 packet, doesn't mean you can trust it to contain a full IP packet. Just because the IP header says it is 20 bytes, doesn't mean you can trust it to contain a full IP packet, and so on for all the layers you attempt to decode.


问:
How do I convert a digit Char (0-9) to its numeric value?
Char.toInt() returns the ASCII code of the character, rather than its numeric value. So how do I convert the Char to an integer with the correct numeric value instead?

答:
Answer:

You can create an extension on the Char class which substracts 48 from the ASCII code returned by toInt(). This will give you the proper numerical value of the character!

```<code>fun Char.getNumericValue(): Int {
    if (this !in '0'..'9') {
        throw NumberFormatException()
    }
    return this.toInt() - '0'.toInt()
}
</code>```

Body:
Answer:

You can create an extension on the Char class which substracts 48 from the ASCII code returned by toInt(). This will give you the proper numerical value of the character!

fun Char.getNumericValue(): Int {
    if (this !in '0'..'9') {
        throw NumberFormatException()
    }
    return this.toInt() - '0'.toInt()
}


问:
Customize/Restrict Android OS within 2 Applications
We need to modify existing Android tablet with 6.0 Marshmallow version, to remove all the interactive system applications and other applications and just make it run with 2 applications.

We were thinking as of now with two solutions either to customize the ROM and create the new one. Or two use COSU solution with Enterprise Mobility Management APIs so that user will be restricted to certain white listed Applications only.

Please suggest the feasible solution to go with.

答:
The simplest approach is probably to use Google's Android Management API, it's compatible with all Android devices running Android 5.1 or above.

To lock the device on one app, or on multiple app, you define a kiosk policy like below:

"applications": [
 {
   "packageName": "com.example.app",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 },
 {
   "packageName": "com.example.app2",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 }
"persistentPreferredActivities": [
  {
    "receiverActivity": "com.example.app/.com.example.app.MainActivity",
    "actions": [
      "android.intent.action.MAIN"
    ],
    "categories": [
      "android.intent.category.HOME",
      "android.intent.category.DEFAULT"
    ]
  }
]
```

<p>If there is no link from one app to the other you can implement a very simple custom launcher to allow switching apps, and configure the policy as below:</p>

<pre class="lang-json prettyprint-override"><code>"applications": [
 {
   "packageName": "com.custom.launcher",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 },
 {
   "packageName": "com.example.app",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 },
 {
   "packageName": "com.example.app2",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 }
"persistentPreferredActivities": [
  {
    "receiverActivity": "com.custom.launcher/.com.example.app.MainActivity",
    "actions": [
      "android.intent.action.MAIN"
    ],
    "categories": [
      "android.intent.category.HOME",
      "android.intent.category.DEFAULT"
    ]
  }
]
</code>```

Body:
The simplest approach is probably to use Google's Android Management API, it's compatible with all Android devices running Android 5.1 or above.

To lock the device on one app, or on multiple app, you define a kiosk policy like below:

"applications": [
 {
   "packageName": "com.example.app",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 },
 {
   "packageName": "com.example.app2",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 }
"persistentPreferredActivities": [
  {
    "receiverActivity": "com.example.app/.com.example.app.MainActivity",
    "actions": [
      "android.intent.action.MAIN"
    ],
    "categories": [
      "android.intent.category.HOME",
      "android.intent.category.DEFAULT"
    ]
  }
]

If there is no link from one app to the other you can implement a very simple custom launcher to allow switching apps, and configure the policy as below:

"applications": [
 {
   "packageName": "com.custom.launcher",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 },
 {
   "packageName": "com.example.app",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 },
 {
   "packageName": "com.example.app2",
   "installType": "FORCE_INSTALLED",
   "lockTaskAllowed": true,
   "defaultPermissionPolicy": "GRANT",
 }
"persistentPreferredActivities": [
  {
    "receiverActivity": "com.custom.launcher/.com.example.app.MainActivity",
    "actions": [
      "android.intent.action.MAIN"
    ],
    "categories": [
      "android.intent.category.HOME",
      "android.intent.category.DEFAULT"
    ]
  }
]


问:
Forcing .NET to use assembly alongside application instead of GAC
I'm developing a .NET application. The application uses a managed library. The application only works with a specific version of this library.

Currently I'm including a copy of the library's DLL files alongside the application. This works fine if the user does not have the library installed. The problem is, if the user has another version of the library installed, the application uses that version instead of the one included alongside the application.

How can I disable or override this behaviour? I've tried Googling it and the only answers that I've found seem to either relate to unmanaged assemblies or refer to specifying a path for a library that isn't installed.

EDIT: I did some more investigation and it turns out that the two versions of the library have the same version number and public key token, so there's no way for the system to distinguish between them. So basically I need to force the system to use the supplied version instead of the version in the GAC, even if it thinks they're the same.

答:
You can try setting the Specific Version of the reference to true.

You can set that property on the property pane of the reference to the assembly.


问:
How to pass non serializable objects to an intent service?
I am using AlarmManager to schedule an IntentService to run some tasks periodically, but I will need to pass non-serializable instances to the service, which are required to run those tasks, since they are not serializable, I can't use Intent to pass them in. Also those instances can't be static, so what would be the best way to handle that?

答: If you are using AlarmManager, your process may not exist between events, and so those objects may not exist. Save the data to persistent storage (SQLite database, SharedPreferences, or other types of files) that the IntentService can read in. You could use a process-level cache to save on I/O time, in the chance that your process happens to remain around for consecutive events, but that is an optimization.


问:
What's the best symmetrical .net encryption provider for size?
I have a scenario where I need to serialize a struct to a byte array or string, encrypt it and then store it in a SQL table.

The issue is that it's possible that this table will run into millions of rows and so size is all important.

I've been using the BinaryFormatter to serialize to a byte[], converting it to Ascii and then compressing it with the RijndaelManaged provider.

Prior to encryption, the string is about 230 bytes. Post encryption, it is over 600 bytes.

Does anyone know if any of the other cryptographic providers would do a better job of this? Or, if indeed there's a better way that I should be going about this?

Thanks very much in advance,

Z

答:
I've found the issue.

I've done a few things
1/ stopped using .net serialization. I notice that serialized content includes assembly information (eg culture, version etc) with every object. It even does this when you override ISerializable and 'roll your own'. I can see why it needs that to re-serialize... but I don't want to store that in every row. Instead I've just built a delimited string and converted that to a byte array. I 're-serialize' myself.

2/ I stopped trying to convert the byte[] to a string (with some sort of encoding) prior to encryption. I now just pass the byte[] into rijindal.

3/ I've started using varbinary in the table and am writing the encrypted result as raw bytes. That seems a lot more efficient than trying to use some sort of encoding.

So - with all that, I've got the final, encrypted product down to about 150 bytes. Big improvement! ... also, I haven't tried compressing it yet either.

Thanks for peoples help :-)

Z


问:
rest operator returned by fat-arrow function
Is it possible to write the code below in one line (without return keyword)?</p>

```<code>elements.map(element => {
  return {...element, selected: false};
})
</code>```

答:
Yes, by using the concise arrow form, enclosing the object initializer in ():

```<code>elements.map(element => ({...element, selected: false}));
// ---------------------^-----------------------------^
</code>```

You need the () because otherwise the { of the object initializer is read as the { as the beginning of a function body. The ( instead makes it an expression body with implied return.

Body:
Is it possible to write the code below in one line (without return keyword)?

elements.map(element => {
  return {...element, selected: false};
})

Body:
Yes, by using the concise arrow form, enclosing the object initializer in ():

elements.map(element => ({...element, selected: false}));
// ---------------------^-----------------------------^

You need the () because otherwise the { of the object initializer is read as the { as the beginning of a function body. The ( instead makes it an expression body with implied return.


问:
How to use Hindi(Indian Mother Tongue) language in Text-To-Speech?
I am creating an application for student. I need to enter data in Hindi or Marathi.

When user clicks on specific topic then user should be able to listen this topic in Hindi Or Marathi.

I know How to set Language in TextToSpeech like

```<code>Tts.setLanguage(Locale.US);
</code>```

I need to set Hindi or Marathi Language. My question is that how to use Marathi or Hindi

Language in TextToSpeech. Please give me any reference or hint.

答:
you should use
msg.lang = 'hi-IN';</p>

Body:
I am creating an application for student. I need to enter data in Hindi or Marathi.

When user clicks on specific topic then user should be able to listen this topic in Hindi Or Marathi.

I know How to set Language in TextToSpeech like

Tts.setLanguage(Locale.US);

I need to set Hindi or Marathi Language. My question is that how to use Marathi or Hindi

Language in TextToSpeech. Please give me any reference or hint.

Body:
you should use
msg.lang = 'hi-IN';


问:
retrieve top sellers from single table in mysql.?
I want to retrieve data from mysql of my client affiliated bestsellers for that i have table which store every order id and it's seller id also with amount of it,
table contains same name sellers so now how can i get select data in sequence of first show seller who num of rows are more and keep do it in desc order.

```<code>select DISTINCT MAX(reseller_id) FROM affilated_comission
</code>```

here is mysql query i am using which is only showing one result i want it also shows who are maximum after top 1.

答:
Something like this should do it.</p>

```<code>SELECT
    seller_id,
    COUNT(volume) AS volume
FROM
    table
GROUP BY
    seller_id
HAVING
    COUNT(volume) >= 10
ORDER BY
    volume DESC
</code>```

Body:
I want to retrieve data from mysql of my client affiliated bestsellers for that i have table which store every order id and it's seller id also with amount of it,
table contains same name sellers so now how can i get select data in sequence of first show seller who num of rows are more and keep do it in desc order.

select DISTINCT MAX(reseller_id) FROM affilated_comission

here is mysql query i am using which is only showing one result i want it also shows who are maximum after top 1.

Body:
Something like this should do it.

SELECT
    seller_id,
    COUNT(volume) AS volume
FROM
    table
GROUP BY
    seller_id
HAVING
    COUNT(volume) >= 10
ORDER BY
    volume DESC


问:
Prevent a user to access a page in some situations or directly
I have an Account Model which have a field is_active(Boolean) by default false,
and a Company Model with foreign key to account:

```<code>class Account(Meta):
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=False)
</code>```

In the get method of CBV I check if user is active an if is not I redirect him to a different url page.

```<code>        if not account.is_active:
            return redirect('accounts:inactive')
        return account
</code>```

Url:

```<code>path('inactive/', AccountInactiveView.as_view(), name='inactive'),
</code>```

view for redirect:

```<code>class AccountInactiveView(TemplateView):
    template_name = 'accounts/account_inactive.html'
</code>```

I don't want the redirect page/url to be access by anyone directly especially if Account is active field is True.

答:
The get() method should return an HttpResponse. It doesn't make sense to return account there. Perhaps you want to call super():

```<code>def get(self, request, *args, **kwargs):
    account = self.request.user.account
    if not account:
        raise Http404
    if not account.is_active:
        return redirect('accounts:inactive')
    return super(MyView, self).get(request, *args, **kwargs)
</code>```

It might be better to override dispatch, so that the check is carried out for get and post requests.

Body:
I have an Account Model which have a field is_active(Boolean) by default false,
and a Company Model with foreign key to account:

class Account(Meta):
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=False)

In the get method of CBV I check if user is active an if is not I redirect him to a different url page.

        if not account.is_active:
            return redirect('accounts:inactive')
        return account

Url:

path('inactive/', AccountInactiveView.as_view(), name='inactive'),

view for redirect:

class AccountInactiveView(TemplateView):
    template_name = 'accounts/account_inactive.html'

I don't want the redirect page/url to be access by anyone directly especially if Account is active field is True.

Body:
The get() method should return an HttpResponse. It doesn't make sense to return account there. Perhaps you want to call super():

def get(self, request, *args, **kwargs):
    account = self.request.user.account
    if not account:
        raise Http404
    if not account.is_active:
        return redirect('accounts:inactive')
    return super(MyView, self).get(request, *args, **kwargs)

It might be better to override dispatch, so that the check is carried out for get and post requests.


问:
Why does Visual Studio show "Push" rather than "Publish" for a new git branch created locally?
I'm confused by something in the Visual Studio Team Services documentation relating to git push:

In Team Explorer, open the Sync view. The view lists outgoing commits
  and will present you with one of two links to push them to your remote
  repo: Publish when there is not a branch on the remote repo associated
  with the current local branch. This will create a branch with the same
  name on the remote repo and push the commits to it. Later you will
  Push, not publish changes when using this branch since the
  relationship between the branch on the local branch and the remote
  repo exists. Push when there is a relationship between the local
  branch and the remote repo. Clicking this will push the commits to the
  remote branch.

Yet when I create a new local branch that is not tracking a remote repo, I see the "Push" link and not the "Publish" link:

Why does the link say "Push" and not "Publish"?

答:
With Visual Studio 2017 Microsoft is working hard to align on naming and constructs to be more aligned with the standard Git terminology. The naming in the docs reflects the Visual Studio 2013-2015 UI.

Given the documentation states it covers TFS 2015-2018 and VS2015-10217 there is currently no one-way to document this behaviour.


问:
QWidgetWindow as QObject in event filter with Qt5
In the migration from Qt4 to Qt5 for some code I have to filter events on my application but it does not work anymore. My software has to filter all events when in "Edition Mode" so only a few widgets/buttons can be available/clickable.

I have a class InputGrabber with a QVector of Pointers to QWidget and an eventFilter function. When passing to "Edit" mode , I append the widgets' pointers to the QVector of my InputGrabber that will be available:

```<code>_inputGrabber->add (_gpView);
_inputGrabber->add (_gpView->viewport ());
_inputGrabber->add (_gpView->horizontalScrollBar ());
_inputGrabber->add (_gpView->verticalScrollBar ());
_inputGrabber->add (_view->mainWindow().toolBarMap()["editSquel"]);
</code>```

and then, on the eventFilter function the code goes like:

```<code>bool InputGrabber::eventFilter (QObject* object, QEvent* anevent)
{
    if (QInputEvent* event = dynamic_cast <QInputEvent*> (anevent))
      {
        QWidget* widget = dynamic_cast <QWidget*> (object);
        if (widget)
        {
          if (_widgetList.contains (widget) || _widgetList.contains (widget->parentWidget ()))
            return QObject::eventFilter (object, event);
          else if (QDialog* dlg = dynamic_cast <QDialog*> (widget))
            return QObject::eventFilter (object, event);
          else if (QDialogButtonBox* dlg = dynamic_cast <QDialogButtonBox*> (widget->parentWidget ()))
            return QObject::eventFilter (object, event);
          else
            return true;
        }
        else
          return true;
      }
      else
        return QObject::eventFilter (object, event);
    }
}
</code>```

The issue migrating to Qt5 is that the following cast:

```<code>QWidget* widget = dynamic_cast <QWidget*> (object);
</code>```

returns NULL when object inherits from QWidgetWindow.

Has anyone found same issue and got a solution that follows the same strategy? I wouldn't like to change the behavior of my software, making loops on all widgets and setting setDisabled() for each one.

Thank you very much!

答:
I think your code is wrong here:

```<code>return QObject::eventFilter (object, event);
</code>```

should be

```<code>return QObject::eventFilter (object, anevent);
</code>```

and possibly:

```<code>bool InputGrabber::eventFilter (QObject* object, QEvent* anevent)
{
  if (QInputEvent* event = dynamic_cast <QInputEvent*> (anevent))
  {
    //etc
  }
  return QObject::eventFilter (object, anevent);
}
</code>```

this way, if you don't explicitly return true or false, it will always propagate the event in the chain correctly.

If your casts fail, just don't return anything and let it fall back to the last line. If somehow you stop the event propagation when you meet an object you don't know anything about (like the misterious QWidgetWindow) you are probably breaking the UI logic. If you let the propagation go on, it is very likely that the event you're waiting for will come out, soon or later.

Body:
In the migration from Qt4 to Qt5 for some code I have to filter events on my application but it does not work anymore. My software has to filter all events when in "Edition Mode" so only a few widgets/buttons can be available/clickable.

I have a class InputGrabber with a QVector of Pointers to QWidget and an eventFilter function. When passing to "Edit" mode , I append the widgets' pointers to the QVector of my InputGrabber that will be available:

_inputGrabber->add (_gpView);
_inputGrabber->add (_gpView->viewport ());
_inputGrabber->add (_gpView->horizontalScrollBar ());
_inputGrabber->add (_gpView->verticalScrollBar ());
_inputGrabber->add (_view->mainWindow().toolBarMap()["editSquel"]);

and then, on the eventFilter function the code goes like:

bool InputGrabber::eventFilter (QObject* object, QEvent* anevent)
{
    if (QInputEvent* event = dynamic_cast <QInputEvent*> (anevent))
      {
        QWidget* widget = dynamic_cast <QWidget*> (object);
        if (widget)
        {
          if (_widgetList.contains (widget) || _widgetList.contains (widget->parentWidget ()))
            return QObject::eventFilter (object, event);
          else if (QDialog* dlg = dynamic_cast <QDialog*> (widget))
            return QObject::eventFilter (object, event);
          else if (QDialogButtonBox* dlg = dynamic_cast <QDialogButtonBox*> (widget->parentWidget ()))
            return QObject::eventFilter (object, event);
          else
            return true;
        }
        else
          return true;
      }
      else
        return QObject::eventFilter (object, event);
    }
}

The issue migrating to Qt5 is that the following cast:

QWidget* widget = dynamic_cast <QWidget*> (object);

returns NULL when object inherits from QWidgetWindow.

Has anyone found same issue and got a solution that follows the same strategy? I wouldn't like to change the behavior of my software, making loops on all widgets and setting setDisabled() for each one.

Thank you very much!

Body:
I think your code is wrong here:

return QObject::eventFilter (object, event);

should be

return QObject::eventFilter (object, anevent);

and possibly:

bool InputGrabber::eventFilter (QObject* object, QEvent* anevent)
{
  if (QInputEvent* event = dynamic_cast <QInputEvent*> (anevent))
  {
    //etc
  }
  return QObject::eventFilter (object, anevent);
}

this way, if you don't explicitly return true or false, it will always propagate the event in the chain correctly.

If your casts fail, just don't return anything and let it fall back to the last line. If somehow you stop the event propagation when you meet an object you don't know anything about (like the misterious QWidgetWindow) you are probably breaking the UI logic. If you let the propagation go on, it is very likely that the event you're waiting for will come out, soon or later.