问:
Third party C static library: Add -ffunction-sections -fdata-sections
I am in the situation to have a c static library (compiled with arm-gcc), which is provided by a third party. I have no possibility to (let the third party) re-compile the library.

When investigating the library contents, i found that the gcc options -ffunction-sections and -fdata-sections have not been used for compiling the library. But this would be very helpful for reducing the binary size of the project.

Compilation is done with: (GNU Tools for ARM Embedded Processors) 4.8.4 20140526 (release) [ARM/embedded-4_8-branch revision 211358].

Is there any way to put every data and every function into their own separate section to enable function-level-linking for this library, without needing to recompile code?

I thought of this possible approach:

Split library into its object files.

For each object file:

Write code to move the symbols into own sections

Put new object files back together into archive file

Could this work, or do you have other suggestions, which ideally only use the tools provided by arm-gcc?

答:
I'm aware this is old, but I came across this problem as well, and figured I'd provide my findings.

TL;DR: It's possible, but incredibly difficult. You can't simply move symbols into their own sections. Relocations will bite you.

When the compiler generates machine code, it will generate slightly different instructions if the -ffunction-sections and -fdata-sections flags are, or are not, provided. This is due to assumptions the compiler is able to make about where symbols will be located. These assumptions change depending on the flags provided.

This is best illustrated by example. Take the following very simple code snippet:

```<code>int a, b;

int getAPlusB()
{
    return a + b;
}
</code>```

The following is the result of arm-none-eabi-objdump -xdr test.o:

arm-none-eabi-gcc -c -Os -mthumb -mcpu=cortexm3 -mlittle-endian -o test.o test.c:

SYMBOL TABLE:
00000000 g     F .text  0000000c getAPlusB
00000004 g     O .bss   00000004 b
00000000 g     O .bss   00000004 a

Disassembly of section .text:

00000024 <getAPlusB>:
  24:   4b01        ldr r3, [pc, #4]    ; (2c <getAPlusB+0x8>)
  26:   cb09        ldmia   r3, {r0, r3}
  28:   4418        add r0, r3
  2a:   4770        bx  lr
  2c:   00000000    .word   0x00000000
            2c: R_ARM_ABS32 .bss
```

<p><code>arm-none-eabi-gcc -c -Os -ffunction-sections -fdata-sections \
  -mthumb -mcpu=cortexm3 -mlittle-endian -o test.o test.c</code>:</p>

<pre class="lang-none prettyprint-override"><code>SYMBOL TABLE:
00000000 g     F .text.getAPlusB    00000014 getAPlusB
00000000 g     O .bss.b 00000004 b
00000000 g     O .bss.a 00000004 a

Disassembly of section .text.getAPlusB:

00000000 <getAPlusB>:
   0:   4b02        ldr r3, [pc, #8]    ; (c <getAPlusB+0xc>)
   2:   6818        ldr r0, [r3, #0]
   4:   4b02        ldr r3, [pc, #8]    ; (10 <getAPlusB+0x10>)
   6:   681b        ldr r3, [r3, #0]
   8:   4418        add r0, r3
   a:   4770        bx  lr
    ...
            c: R_ARM_ABS32  .bss.a
            10: R_ARM_ABS32 .bss.b
</code>```

The difference is subtle, but important. The flag enabled code performs two separate loads, while the disabled code performs a single "load multiple." The enabled code does this because it knows both symbols are contained in the same section, in a certain sequence. With the enabled code, this is not the case. The symbols are in two separate sections, and while it is likely they will keep their order and proximity, it is not guaranteed. What's more, if both sections are not referenced, the linker may decide one section is not used, and remove it.

Another example:

```<code>int a, b;

int getB()
{
  return b;
}
</code>```

And the generated code. First without the flags:

SYMBOL TABLE:
00000000 g     F .text  0000000c getB
00000004 g     O .bss   00000004 b
00000000 g     O .bss   00000004 a

Disassembly of section .text:

00000018 <getB>:
  18:   4b01        ldr r3, [pc, #4]    ; (20 <getB+0x8>)
  1a:   6858        ldr r0, [r3, #4]
  1c:   4770        bx  lr
  1e:   bf00        nop
  20:   00000000    .word   0x00000000
            20: R_ARM_ABS32 .bss
```

<p>And with the flags:</p>

<pre class="lang-none prettyprint-override"><code>SYMBOL TABLE:
00000000 g     F .text.getB 00000014 getB
00000000 g     O .bss.b 00000004 b
00000000 g     O .bss.a 00000004 a

Disassembly of section .text.getB:

00000000 <getB>:
   0:   4b01        ldr r3, [pc, #4]    ; (8 <getB+0x8>)
   2:   6818        ldr r0, [r3, #0]
   4:   4770        bx  lr
   6:   bf00        nop
   8:   00000000    .word   0x00000000
            8: R_ARM_ABS32  .bss.b
</code>```

In this case, the difference is even more subtle. The enabled code loads with an offset of 0, while the disabled code uses 4. Since the disabled code references the beginning of the section, it needs to offset to the location of b. However the enabled code references the section which contains solely b, and therefore does not need an offset. If we were to split this and only change the relocation, the new code would contain a reference to the section a was in, but not b. This, again, could cause the linker to garbage collect the wrong section.

These were just two scenarios that I came across when looking at this problem, there may be more.

Producing valid object files functionally equivalent to code compiled with the -ffunction-sections and -fdata-sections flags would require parsing the machine instructions looking for these and any other relocation issues that could come up. This is not an easy task to accomplish.

Body:
I'm aware this is old, but I came across this problem as well, and figured I'd provide my findings.

TL;DR: It's possible, but incredibly difficult. You can't simply move symbols into their own sections. Relocations will bite you.

When the compiler generates machine code, it will generate slightly different instructions if the -ffunction-sections and -fdata-sections flags are, or are not, provided. This is due to assumptions the compiler is able to make about where symbols will be located. These assumptions change depending on the flags provided.

This is best illustrated by example. Take the following very simple code snippet:

int a, b;

int getAPlusB()
{
    return a + b;
}

The following is the result of arm-none-eabi-objdump -xdr test.o:

arm-none-eabi-gcc -c -Os -mthumb -mcpu=cortexm3 -mlittle-endian -o test.o test.c:

SYMBOL TABLE:
00000000 g     F .text  0000000c getAPlusB
00000004 g     O .bss   00000004 b
00000000 g     O .bss   00000004 a

Disassembly of section .text:

00000024 <getAPlusB>:
  24:   4b01        ldr r3, [pc, #4]    ; (2c <getAPlusB+0x8>)
  26:   cb09        ldmia   r3, {r0, r3}
  28:   4418        add r0, r3
  2a:   4770        bx  lr
  2c:   00000000    .word   0x00000000
            2c: R_ARM_ABS32 .bss

arm-none-eabi-gcc -c -Os -ffunction-sections -fdata-sections \
  -mthumb -mcpu=cortexm3 -mlittle-endian -o test.o test.c:

SYMBOL TABLE:
00000000 g     F .text.getAPlusB    00000014 getAPlusB
00000000 g     O .bss.b 00000004 b
00000000 g     O .bss.a 00000004 a

Disassembly of section .text.getAPlusB:

00000000 <getAPlusB>:
   0:   4b02        ldr r3, [pc, #8]    ; (c <getAPlusB+0xc>)
   2:   6818        ldr r0, [r3, #0]
   4:   4b02        ldr r3, [pc, #8]    ; (10 <getAPlusB+0x10>)
   6:   681b        ldr r3, [r3, #0]
   8:   4418        add r0, r3
   a:   4770        bx  lr
    ...
            c: R_ARM_ABS32  .bss.a
            10: R_ARM_ABS32 .bss.b

The difference is subtle, but important. The flag enabled code performs two separate loads, while the disabled code performs a single "load multiple." The enabled code does this because it knows both symbols are contained in the same section, in a certain sequence. With the enabled code, this is not the case. The symbols are in two separate sections, and while it is likely they will keep their order and proximity, it is not guaranteed. What's more, if both sections are not referenced, the linker may decide one section is not used, and remove it.

Another example:

int a, b;

int getB()
{
  return b;
}

And the generated code. First without the flags:

SYMBOL TABLE:
00000000 g     F .text  0000000c getB
00000004 g     O .bss   00000004 b
00000000 g     O .bss   00000004 a

Disassembly of section .text:

00000018 <getB>:
  18:   4b01        ldr r3, [pc, #4]    ; (20 <getB+0x8>)
  1a:   6858        ldr r0, [r3, #4]
  1c:   4770        bx  lr
  1e:   bf00        nop
  20:   00000000    .word   0x00000000
            20: R_ARM_ABS32 .bss

And with the flags:

SYMBOL TABLE:
00000000 g     F .text.getB 00000014 getB
00000000 g     O .bss.b 00000004 b
00000000 g     O .bss.a 00000004 a

Disassembly of section .text.getB:

00000000 <getB>:
   0:   4b01        ldr r3, [pc, #4]    ; (8 <getB+0x8>)
   2:   6818        ldr r0, [r3, #0]
   4:   4770        bx  lr
   6:   bf00        nop
   8:   00000000    .word   0x00000000
            8: R_ARM_ABS32  .bss.b

In this case, the difference is even more subtle. The enabled code loads with an offset of 0, while the disabled code uses 4. Since the disabled code references the beginning of the section, it needs to offset to the location of b. However the enabled code references the section which contains solely b, and therefore does not need an offset. If we were to split this and only change the relocation, the new code would contain a reference to the section a was in, but not b. This, again, could cause the linker to garbage collect the wrong section.

These were just two scenarios that I came across when looking at this problem, there may be more.

Producing valid object files functionally equivalent to code compiled with the -ffunction-sections and -fdata-sections flags would require parsing the machine instructions looking for these and any other relocation issues that could come up. This is not an easy task to accomplish.


来源: stackexchange

问:
DataGrid not updating when rebinding a new datasoure
I bind an ObservableCollection CustomerList to a datagrid, it works fine when it is opened initially, but when I use a buttion to call the fuction to give a new object to CustomerList the datagrid is not refreshed, I am aware that this is the way how the datagrid update works, as the original CustomerList is not upadted, so what can I do to solve the problem in this case? I am using MVVM pattern
</p>

```<code>class CustomerViewModel
{
    public ObservableCollection<Customer> CustomerList { get; set; }

    public RelayCommand SearchCommand { get; set; }
    public CustomerViewModel()
    {
        CustomerList = new ObservableCollection<Customer>(customerDAL.GetAllCustomers());
        SearchCommand = new RelayCommand(SearchCustomersByKeyWords);
    }

    void SearchCustomersByKeyWords(object parameter)
    {

        CustomerList = new ObservableCollection<Customer>(customerDAL.SearchByKeywords(keyWords));

    }
}
</code>```

答:
CustomerViewModel is not actually a viewmodel. It's just a regular class. To be a proper viewmodel, it needs to implement INotifyPropertyChanged.

When you change the value of CustomerList, you must raise the PropertyChanged event of INotifyPropertyChanged. Otherwise, the UI will never know that the value of CustomerList has changed. The binding on DataGrid.ItemsSource has no idea that you updated the source property, so it isn't updating the target property.

CustomerList should look something like this:

```<code>public class CustomerViewModel : ViewModelBase
{
    private ObservableCollection<Customer> _customerList = new ObservableCollection<Customer>();
    public ObservableCollection<Customer> CustomerList {
        get { return _customerList; }
        set {
            if (_customerList != value) {
                _customerList != value;
                //  Member of ViewModelBase that raises PropertyChanged
                OnPropertyChanged(nameof(CustomerList));
            }
        }
    }
</code>```

And write a ViewModelBase class that implements INotifyPropertyChanged; you'll find many examples of that online.

A poor workaround would be to keep the collection you've got, but Clear() it and add the new items to it one by one in a loop.

ContentLicense: CC BY-SA 3.0

Body:
I bind an ObservableCollection CustomerList to a datagrid, it works fine when it is opened initially, but when I use a buttion to call the fuction to give a new object to CustomerList the datagrid is not refreshed, I am aware that this is the way how the datagrid update works, as the original CustomerList is not upadted, so what can I do to solve the problem in this case? I am using MVVM pattern

class CustomerViewModel
{
    public ObservableCollection<Customer> CustomerList { get; set; }

    public RelayCommand SearchCommand { get; set; }
    public CustomerViewModel()
    {
        CustomerList = new ObservableCollection<Customer>(customerDAL.GetAllCustomers());
        SearchCommand = new RelayCommand(SearchCustomersByKeyWords);
    }

    void SearchCustomersByKeyWords(object parameter)
    {

        CustomerList = new ObservableCollection<Customer>(customerDAL.SearchByKeywords(keyWords));

    }
}

Body:
CustomerViewModel is not actually a viewmodel. It's just a regular class. To be a proper viewmodel, it needs to implement INotifyPropertyChanged.

When you change the value of CustomerList, you must raise the PropertyChanged event of INotifyPropertyChanged. Otherwise, the UI will never know that the value of CustomerList has changed. The binding on DataGrid.ItemsSource has no idea that you updated the source property, so it isn't updating the target property.

CustomerList should look something like this:

public class CustomerViewModel : ViewModelBase
{
    private ObservableCollection<Customer> _customerList = new ObservableCollection<Customer>();
    public ObservableCollection<Customer> CustomerList {
        get { return _customerList; }
        set {
            if (_customerList != value) {
                _customerList != value;
                //  Member of ViewModelBase that raises PropertyChanged
                OnPropertyChanged(nameof(CustomerList));
            }
        }
    }

And write a ViewModelBase class that implements INotifyPropertyChanged; you'll find many examples of that online.

A poor workaround would be to keep the collection you've got, but Clear() it and add the new items to it one by one in a loop.


问:
"this" is not refering the the user object in mongoose model
I have the following code to save user object to database from express,

```<code>api.post('/signup', function (req, res) {
    var user = new User();
    user.name = req.body.name;
    user.email = req.body.email;
    user.setPassword(req.body.password);
    user.save(function (err) {
        err ? res.send(err) : res.json({ message: 'User Created!'})
    })
})
</code>```

and below here for the user schema,

```<code>var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;

var Schema = mongoose.Schema;

var userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: String,
})

userSchema.methods.setPassword = function (password) {
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return console.log(err);
        bcrypt.hash(password, salt, function (err, hash) {
            if (err) return console.log(err);
            this.password = hash; // <= `this` will not be saved to mongoDB
        })
    })
}

module.exports = mongoose.model('User', userSchema);
</code>```

When it performed the save function, it will show that the password was undefined and will save the object to mongodb without password value.

I've checked the this question as well and changed all my functions to not using arrow method but it still got the same error.

The same issue when i was using middleware hook that this reference was not referring to user object. Below here for my another approach,

```<code>userSchema.pre('save', (next) => {

    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if(err) return next(err);
        bcrypt.hash(this.password, salt, function (err, hash) {
            if (err) return next(err);

            this.password = hash; // <= `this` will not be saved to mongoDB
            next();
        })
    })
})
</code>```

Any idea for this value to be saved to database when perform save?

答:
I will elaborate more in the next days (I want to test a couple of things) but the error, I think, is because the meaning of this in JS is tricky.

Basically this is not a reference to the function's lexical scope, it is binding done in the context where the function is called.

So, as a fast solution while I elaborate more, I would recommend you to encrypt the password in:
user.setPassword(encrypt(req.body.password)); and simplify the mongoose's setPassword function

Hope that helps.

Body:
I have the following code to save user object to database from express,

api.post('/signup', function (req, res) {
    var user = new User();
    user.name = req.body.name;
    user.email = req.body.email;
    user.setPassword(req.body.password);
    user.save(function (err) {
        err ? res.send(err) : res.json({ message: 'User Created!'})
    })
})

and below here for the user schema,

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;

var Schema = mongoose.Schema;

var userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: String,
})

userSchema.methods.setPassword = function (password) {
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return console.log(err);
        bcrypt.hash(password, salt, function (err, hash) {
            if (err) return console.log(err);
            this.password = hash; // <= `this` will not be saved to mongoDB
        })
    })
}

module.exports = mongoose.model('User', userSchema);

When it performed the save function, it will show that the password was undefined and will save the object to mongodb without password value.

I've checked the this question as well and changed all my functions to not using arrow method but it still got the same error.

The same issue when i was using middleware hook that this reference was not referring to user object. Below here for my another approach,

userSchema.pre('save', (next) => {

    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if(err) return next(err);
        bcrypt.hash(this.password, salt, function (err, hash) {
            if (err) return next(err);

            this.password = hash; // <= `this` will not be saved to mongoDB
            next();
        })
    })
})

Any idea for this value to be saved to database when perform save?


问:
delete packages of domain by adb shell pm
There is a command to ease the pain of managing packages for Android phone,

```<code>adb shell pm uninstall org.kde.necessitas.example.one
adb shell pm uninstall org.kde.necessitas.example.two
</code>```

But I have many phones and just want to delete all packages from a particular domain on them.

It cannot be done by

```<code>adb shell pm uninstall org.kde.necessitas.example.*
</code>```

what is your suggestion?

答:
for mac users:</p>

```<code>adb shell pm list packages com.your.domain \
| cut -d ':' -f 2 \
| tr -d '\r' \
| xargs -L1 -t adb uninstall
</code>```

Body:
There is a command to ease the pain of managing packages for Android phone,

adb shell pm uninstall org.kde.necessitas.example.one
adb shell pm uninstall org.kde.necessitas.example.two

But I have many phones and just want to delete all packages from a particular domain on them.

It cannot be done by

adb shell pm uninstall org.kde.necessitas.example.*

what is your suggestion?

Body:
for mac users:

adb shell pm list packages com.your.domain \
| cut -d ':' -f 2 \
| tr -d '\r' \
| xargs -L1 -t adb uninstall


问:
Have another class control a picture[ ] on the main form
I try create a class "bgcar" for race cars that is responsible for handling all variables related to some race cars, one of those variables are pictures of the race car, to be placed on the main form. All variables speed position location gasoline etc work (but i removed that from below).

However loading and updating the images turns out to be problematic.
I tried a few variations on the code below but so far nothing works.

I can imagine one would think why dont simply write it all in the Main form, however i dont want to create lots of form variables, i want a class to be able to handle it self and with an classtype.update(). update the main form.
Wich is a winform application.

```<code>namespace game
{
public class Main:Form
  {
    bgcar racecars;

    public Main()
    {
      racecars = new bgcar();
      racecars.update

      //to add later
      //traficlights.update
      //people.update
    }
  }
class bgcar
{
  public PictureBox[] wagon;
  public bgcar() //constructor
  {
    wagon = new PictureBox[2];

    //below wont work.
    //while on the main form
    // picturebox1.image new bitmap(game.Properties.Resources.SportwagonA)
    //works, proving it does exist in the resource file.
    wagon[0].image = new Bitmap(game.Properties.Resources.SportwagonA);
    wagon[1].image = new Bitmap(game.Properties.Resources.SportwagonB);
  }
  public void update()
  {
    //displaying those images is also a problem
    Random rnd = new Random();
    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[0].location = new point (x,y);

    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[1].location = new point (x,y);
  }
 }
}
</code>```

==update
Going to eat first, i'm now thinking of creating on my Main :form
a public PictureBox[] sportcars, then have in my mainform a routine that
does something like: sportscar = bgcar.wagon;   not sure if that will work.

答:
Pass the Form into your class so you can add the controls to it:

```<code>public Main()
{
  racecars = new bgcar(this); // <--- Pass the Form in
  racecars.update();
}
</code>```

Here's an updated version of the Class:

```<code>}

public class bgcar
{

    private Form frm;
    private List<PictureBox> wagon;
    private Random rnd = new Random();

    public bgcar(Form frm) //constructor receives the Form
    {
        this.frm = frm; // store Form reference for possible later use
        wagon = new List<PictureBox>();

        PictureBox pb = new PictureBox();
        pb.Image = new Bitmap(game.Properties.Resources.SportwagonA);
        frm.Controls.Add(pb); // add created control to both the Form and our List
        wagon.Add(pb);

        pb = new PictureBox();
        pb.Image = new Bitmap(game.Properties.Resources.SportwagonB);
        frm.Controls.Add(pb);
        wagon.Add(pb);
    }

    public void update()
    {
        foreach(PictureBox pb in wagon)
        {
            int x = rnd.Next(100);
            int y = rnd.Next(100);
            pb.Location = new Point(x, y);
        }
    }

}
</code>```

Body:
I try create a class "bgcar" for race cars that is responsible for handling all variables related to some race cars, one of those variables are pictures of the race car, to be placed on the main form. All variables speed position location gasoline etc work (but i removed that from below).

However loading and updating the images turns out to be problematic.
I tried a few variations on the code below but so far nothing works.

I can imagine one would think why dont simply write it all in the Main form, however i dont want to create lots of form variables, i want a class to be able to handle it self and with an classtype.update(). update the main form.
Wich is a winform application.

namespace game
{
public class Main:Form
  {
    bgcar racecars;

    public Main()
    {
      racecars = new bgcar();
      racecars.update

      //to add later
      //traficlights.update
      //people.update
    }
  }
class bgcar
{
  public PictureBox[] wagon;
  public bgcar() //constructor
  {
    wagon = new PictureBox[2];

    //below wont work.
    //while on the main form
    // picturebox1.image new bitmap(game.Properties.Resources.SportwagonA)
    //works, proving it does exist in the resource file.
    wagon[0].image = new Bitmap(game.Properties.Resources.SportwagonA);
    wagon[1].image = new Bitmap(game.Properties.Resources.SportwagonB);
  }
  public void update()
  {
    //displaying those images is also a problem
    Random rnd = new Random();
    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[0].location = new point (x,y);

    int x = rnd.next(100);
    int y = rnd.next(100);
    Wagon[1].location = new point (x,y);
  }
 }
}

==update
Going to eat first, i'm now thinking of creating on my Main :form
a public PictureBox[] sportcars, then have in my mainform a routine that
does something like: sportscar = bgcar.wagon;   not sure if that will work.

Body:
Pass the Form into your class so you can add the controls to it:

public Main()
{
  racecars = new bgcar(this); // <--- Pass the Form in
  racecars.update();
}

Here's an updated version of the Class:

}

public class bgcar
{

    private Form frm;
    private List<PictureBox> wagon;
    private Random rnd = new Random();

    public bgcar(Form frm) //constructor receives the Form
    {
        this.frm = frm; // store Form reference for possible later use
        wagon = new List<PictureBox>();

        PictureBox pb = new PictureBox();
        pb.Image = new Bitmap(game.Properties.Resources.SportwagonA);
        frm.Controls.Add(pb); // add created control to both the Form and our List
        wagon.Add(pb);

        pb = new PictureBox();
        pb.Image = new Bitmap(game.Properties.Resources.SportwagonB);
        frm.Controls.Add(pb);
        wagon.Add(pb);
    }

    public void update()
    {
        foreach(PictureBox pb in wagon)
        {
            int x = rnd.Next(100);
            int y = rnd.Next(100);
            pb.Location = new Point(x, y);
        }
    }

}


问:
Can we connect two computers practically using OMNet++?
i have two computers both running OMNet++ separately,and connected via Wi-Fi,
can i send message  from one computer to another using omnet++ over wifi?</p>

答: Yes, you can, but I'm not sure you should. Check how to set up MPI bases parallel simulation scenario in the manual, however I'm almost sure that this is not what you want to do. If you want to simulate two applications while they are speaking to each other via a physical, real world WIFI card, then you should check how to set up external interfaces in INET.


问:
Remove charset in Content-Type header in Citrus
I'm using v2.6.2 of the Citrus Framework to write automated tests for a rest end point using the http module.  Citrus is appending charset=UTF-8 to the Content-Type header.  The server is responding 415 Unsupported Media due to the charset being present.

I cannot modify the rest end point.

Can I configure Citrus and the http module to not append the charset?

答:
This was related to Citrus Http message converter always adding the default charset "UTF-8"which is set as attribute on the citrus-http:client component. So you need to overwrite the Content-Type explicitly in each send operation in order to not add the default charset.

Since Citrus 2.7.2 you can set the charset on the citrus-http:client component to an empty string. This fixes the charset appendix.


问:
Passing values to Construtor
```<code>package org.apache.wicket.examples.guestbook;

import java.util.Date;
import org.apache.wicket.IClusterable;

public class Comment implements IClusterable {
    private String text;
    private Date date = new Date();

    public Comment() {
    }

    public Comment(final Comment comment) {
        this.text = comment.text;
        this.date = comment.date;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String toString() {
        return "[Comment date = " + date + ", text = " + text + "]";
    }
}
</code>```

Why does the other construtor do here?
Why the Comment comment is declared as final?

答:
There are two constructors: one that initializes both the date and the text given a Comment object, and another that leaves the members uninitialized (therefore requiring the use of the setters to initialize them).

The final qualifier has no effect at all for the caller of the constructor. It only states that the method implementation doesn't assign the argument reference a new value. Note that even if it did, the caller would not be aware of it because java always passes parameters by value.

I suspect that the origin of this copy constructor pattern is C++, where const can be used to prevent modifying the state of the other object. With java's final this is not the case. You can freely modify the data members of the argument.

ContentLicense: CC BY-SA 2.5

Title: Passing values to Construtor

Body:
package org.apache.wicket.examples.guestbook;

import java.util.Date;
import org.apache.wicket.IClusterable;

public class Comment implements IClusterable {
    private String text;
    private Date date = new Date();

    public Comment() {
    }

    public Comment(final Comment comment) {
        this.text = comment.text;
        this.date = comment.date;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String toString() {
        return "[Comment date = " + date + ", text = " + text + "]";
    }
}

Why does the other construtor do here?
Why the Comment comment is declared as final?


问:
Knockoutjs Button Click
Hi how can ı get my value with knockoutjs click event my button code

```<code> <button data-bind="click : LikeButtonClick , value : MessageId" class="btn btn-default like"><span data-bind="text:LikeCount"></span> <i class="fa fa-thumbs-o-up"></i></button>
</code>```

and my knockoutjs click code

```<code> var LikeButtonClick = function () {
    alert("");
 }
</code>```

And how can I refresh my likes after like button click event. I use template binding. My template binding code is

```<code>  var viewModel = {
            messages: ko.observableArray()
        };
        ko.options.useOnlyNativeEvents = true;
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });
</code>```

and my like button code

```<code>var LikeButtonClick = function (id) {
            $.ajax({
                url: '/Home/Like/' + id,
                type: 'POST',
                success: function (data) {
                        // refresh
                        });
                }
            });
        }
</code>```

答:
this context passed to the method will be your viewmodel, or whatever you have bound to the element. Inside LikeButtonClick you should be able to get the value of MessageId by referencing the property this.MessageId().

If you want to pass a value to the click handler, you'll want to declare an inline function where you data-bind, or alternatively, bind the function with a context. Here the context is the main viewmodel:

```<code>data-bind="click: LikeButtonClick.bind($root,'green')"

var LikeButtonClick = function (src) {
        alert(src); // src='green' in this example
    }
</code>```

Title: Knockoutjs Button Click

Body:
Hi how can ı get my value with knockoutjs click event my button code

 <button data-bind="click : LikeButtonClick , value : MessageId" class="btn btn-default like"> </button>

and my knockoutjs click code

 var LikeButtonClick = function () {
    alert("");
 }

And how can I refresh my likes after like button click event. I use template binding. My template binding code is

  var viewModel = {
            messages: ko.observableArray()
        };
        ko.options.useOnlyNativeEvents = true;
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });

and my like button code

var LikeButtonClick = function (id) {
            $.ajax({
                url: '/Home/Like/' + id,
                type: 'POST',
                success: function (data) {
                        // refresh
                        });
                }
            });
        }

Body:
this context passed to the method will be your viewmodel, or whatever you have bound to the element. Inside LikeButtonClick you should be able to get the value of MessageId by referencing the property this.MessageId().

If you want to pass a value to the click handler, you'll want to declare an inline function where you data-bind, or alternatively, bind the function with a context. Here the context is the main viewmodel:

data-bind="click: LikeButtonClick.bind($root,'green')"

var LikeButtonClick = function (src) {
        alert(src); // src='green' in this example
    }


问:
Splitting XML into rows (TSQL)
I've been wrestling with this for hours and I'm completely befuddled on why it's not working. I have the following XML as a single column (a few dozen records stored this way).

```<code><dsMQ1License xmlns="http://tempuri.org/dsMQ1License.xsd">
  <licenseModuleInfo>
    <module>AP</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>AU</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>CO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>DO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
.
.
.
</dsMQ1License>
</code>```

I want to be able to take the XML column, and turn it into rows where each column represents the inner most element.

```
+--------+--------+---------------+
| Module | Status | StatusEndDate |
+--------+--------+---------------+
| AD     |      1 | 2017-12-28    |
| AU     |      1 | 2017-12-28    |
| CO     |      1 | 2017-12-28    |
| DO     |      1 | 2017-12-28    |
+--------+--------+---------------+
```

Based on everything I've read so far, I feel like what I've done should work.

```<code>SELECT
T.C.value('(module)[1]','VARCHAR(MAX)') AS ModuleAbbr
,T.C.value('(status)[1]','bit') AS Active
FROM LicenseXML
CROSS APPLY LicenseXML.License.nodes('/dsMQ1License/licenseModuleInfo') T(C)
</code>```

But it just returns 0 rows.

Where am I going wrong?

答:
I'm using a WITH statement and some subqueries to actually find the license. In the end, defining the namespace and using the namespace alias is what made this work.</p>

```<code>WITH XMLNAMESPACES ('http://tempuri.org/dsMQ1License.xsd' AS ns)
,LicenseXML AS (
SELECT CAST(License AS XML) AS License
    FROM (
        SELECT a.i.value('.','varchar(max)') AS License
        FROM
            (SELECT CAST(memLicense AS XML) memLicense FROM tblMQ1SysLicense) AS X
            CROSS APPLY X.memLicense.nodes('/License') AS a(i)
        ) AS LicXML
)
SELECT
T.C.value('ns:module[1]','VARCHAR(MAX)') AS ModuleAbbr
,T.C.value('ns:status[1]','bit') AS Active
,T.C.value('ns:statusEndDate[1]','DATE') AS StatusDate
FROM LicenseXML
CROSS APPLY LicenseXML.License.nodes('/ns:dsMQ1License/ns:licenseModuleInfo') T(C)
</code>```

Title: Splitting XML into rows (TSQL)

Body:
I've been wrestling with this for hours and I'm completely befuddled on why it's not working. I have the following XML as a single column (a few dozen records stored this way).

<dsMQ1License xmlns="http://tempuri.org/dsMQ1License.xsd">
  <licenseModuleInfo>
    <module>AP</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>AU</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>CO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>DO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
.
.
.
</dsMQ1License>

I want to be able to take the XML column, and turn it into rows where each column represents the inner most element.

+--------+--------+---------------+
| Module | Status | StatusEndDate |
+--------+--------+---------------+
| AD     |      1 | 2017-12-28    |
| AU     |      1 | 2017-12-28    |
| CO     |      1 | 2017-12-28    |
| DO     |      1 | 2017-12-28    |
+--------+--------+---------------+

Based on everything I've read so far, I feel like what I've done should work.

SELECT
T.C.value('(module)[1]','VARCHAR(MAX)') AS ModuleAbbr
,T.C.value('(status)[1]','bit') AS Active
FROM LicenseXML
CROSS APPLY LicenseXML.License.nodes('/dsMQ1License/licenseModuleInfo') T(C)

But it just returns 0 rows.

Where am I going wrong?

Body:
I'm using a WITH statement and some subqueries to actually find the license. In the end, defining the namespace and using the namespace alias is what made this work.

WITH XMLNAMESPACES ('http://tempuri.org/dsMQ1License.xsd' AS ns)
,LicenseXML AS (
SELECT CAST(License AS XML) AS License
    FROM (
        SELECT a.i.value('.','varchar(max)') AS License
        FROM
            (SELECT CAST(memLicense AS XML) memLicense FROM tblMQ1SysLicense) AS X
            CROSS APPLY X.memLicense.nodes('/License') AS a(i)
        ) AS LicXML
)
SELECT
T.C.value('ns:module[1]','VARCHAR(MAX)') AS ModuleAbbr
,T.C.value('ns:status[1]','bit') AS Active
,T.C.value('ns:statusEndDate[1]','DATE') AS StatusDate
FROM LicenseXML
CROSS APPLY LicenseXML.License.nodes('/ns:dsMQ1License/ns:licenseModuleInfo') T(C)


问:
Cannot submit Informatica PowerCenter jobs after a Web Services Hub restart in Workload Scheduler
Following a restart of the Web Services Hub, the Plug-in for Informatica jobs launched from the command line end in FAIL state (Error state in the Dynamic Workload Console) and return the following exception in the job log: </p>

```<code>AWKIPC005E Failed to run workflow.
Remote Exception
</code>```

答:
To enable the correct submission of plug-in jobs, after restarting the Hub, connect to the Informatica PowerCenter Web Services Hub URL and follow these steps:

In the Navigator pane, expand Web Service -> Batch WebService, and
then click Integration WebService

In the Operations pane, click Try-It from the toolbar

In the Web Service Operations avigator pane, click login.

Fill out the form in the right pane, pecifying the required
information in the UserName, RepositoryName, nd Password text
fields.

Click Send.

In the SOAP Response pane, copy the value for the SessionId tag.

In the Web Service Operations Navigator pane, click getWorkflowLog.

Paste the value copied previously in the SessionId text field and
then enter the required information in the FolderName, WorkflowName,
Timeout, and ServiceName text fields.

Click Send.

It should work.

Body:
Following a restart of the Web Services Hub, the Plug-in for Informatica jobs launched from the command line end in FAIL state (Error state in the Dynamic Workload Console) and return the following exception in the job log:

AWKIPC005E Failed to run workflow.
Remote Exception


问:
Processing SAML response with Spring SAML
I developed a Service Provider by using Spring SAML.
I've configured several IdPs, each of them with a different naming conventions for the attributes.

Could I log (on Tomcat's logs/catalina.out file) an entire SAML response after a successful AuthN process?

Are there some native features in order to define an association between a certain IdP's EntityID and the attribute that maps the returned userID?

I'm also reading about the OID format: how can I properly decode this kind of data?

Update:

About the first question, according to the documentation, I setup up both debug logging and authentication logging as follows:

```<code>// Logger for SAML messages and events
@Bean
public SAMLDefaultLogger samlDefaultLogger() {
    SAMLDefaultLogger samlDefaultLogger = new SAMLDefaultLogger();
    samlDefaultLogger.setLogMessages(true);
    samlDefaultLogger.setLogErrors(true);
    return samlDefaultLogger;
}
</code>```

Then, by defining a log4j.properties as follows:

```<code>log4j.logger.org.springframework.security.saml=DEBUG
log4j.logger.org.opensaml=DEBUG
</code>```

And by properly configuring the Maven pom.xml

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

Despite that, the complete SAML response doesn't appear (I'm expecting an XML message). The output is as follows:

```<code>[2014-07-29 14:13:51.985] boot - 1118 DEBUG [http-bio-443-exec-38] --- MetadataCredentialResolver: Attempting to retrieve credentials from cache using index: [http:/test.idp.prv/services/trust,{urn:oasis:names:tc:SAML:2.0:metadata}IDPSSODescriptor,urn:oasis:names:tc:SAML:2.0:protocol,SIGNING]
[2014-07-29 14:13:51.985] boot - 1118 DEBUG [http-bio-443-exec-38] --- MetadataCredentialResolver: Retrieved credentials from cache using index: [http:/test.idp.prv/services/trust,{urn:oasis:names:tc:SAML:2.0:metadata}IDPSSODescriptor,urn:oasis:names:tc:SAML:2.0:protocol,SIGNING]
[2014-07-29 14:13:51.985] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableUsageCredentialCriteria for criteria class org.opensaml.xml.security.criteria.UsageCriteria
[2014-07-29 14:13:51.986] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableKeyAlgorithmCredentialCriteria for criteria class org.opensaml.xml.security.criteria.KeyAlgorithmCriteria
[2014-07-29 14:13:51.986] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableEntityIDCredentialCriteria for criteria class org.opensaml.xml.security.criteria.EntityIDCriteria
[2014-07-29 14:13:51.986] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry could not locate evaluable criteria for criteria class org.opensaml.security.MetadataCriteria
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Attempting to verify signature and establish trust using KeyInfo-derived credentials
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Found 0 key names: []
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Processing KeyInfo child with qname: {http://www.w3.org/2000/09/xmldsig#}X509Data
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Provider org.opensaml.xml.security.keyinfo.provider.RSAKeyValueProvider doesn't handle objects of type {http://www.w3.org/2000/09/xmldsig#}X509Data, skipping
[2014-07-29 14:13:51.988] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Provider org.opensaml.xml.security.keyinfo.provider.DSAKeyValueProvider doesn't handle objects of type {http://www.w3.org/2000/09/xmldsig#}X509Data, skipping
[2014-07-29 14:13:51.988] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Processing KeyInfo child {http://www.w3.org/2000/09/xmldsig#}X509Data with provider org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider
[2014-07-29 14:13:51.988] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Attempting to extract credential from an X509Data
[2014-07-29 14:13:51.993] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Found 1 X509Certificates
[2014-07-29 14:13:51.993] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Found 0 X509CRLs
[2014-07-29 14:13:51.993] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Single certificate was present, treating as end-entity certificate
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Credentials successfully extracted from child {http://www.w3.org/2000/09/xmldsig#}X509Data by provider org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: A total of 1 credentials were resolved
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry could not locate evaluable criteria for criteria class org.opensaml.xml.security.keyinfo.KeyInfoCriteria
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Attempting to validate signature using key from supplied credential
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Creating XMLSignature object
[2014-07-29 14:13:51.995] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Validating signature with signature algorithm URI: http://www.w3.org/2000/09/xmldsig#rsa-sha1
[2014-07-29 14:13:51.995] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl'
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Signature validated with key from supplied credential
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Signature validation using candidate credential was successful
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Successfully verified signature using KeyInfo-derived credential
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Attempting to establish trust of KeyInfo-derived credential
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- ExplicitKeyTrustEvaluator: Successfully validated untrusted credential against trusted key
[2014-07-29 14:13:52.000] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Successfully established trust of KeyInfo-derived credential
[2014-07-29 14:13:52.000] boot - 1118 DEBUG [http-bio-443-exec-38] --- WebSSOProfileConsumerImpl: Processing Bearer subject confirmation
[2014-07-29 14:13:52.000] boot - 1118 DEBUG [http-bio-443-exec-38] --- WebSSOProfileConsumerImpl: Verifying received AuthnContext org.opensaml.saml2.core.impl.AuthnContextImpl@3ab2fc5f against requested null
[2014-07-29 14:13:52.001] boot - 1118  INFO [http-bio-443-exec-38] --- PrismaUserDetailsServiceImpl: SAML Response      EntityID: urn:com:vdenotaris:mysp
[2014-07-29 14:13:52.001] boot - 1118  INFO [http-bio-443-exec-38] --- PrismaUserDetailsServiceImpl: SAML Response      RemoteEntityID: http:/test.idp.prv/services/trust
</code>```

Note that the last two lines are defined manually by me.

答:
How about adding this:

```<code>log4j.logger.PROTOCOL_MESSAGE=DEBUG
</code>```

Or this for Logback:

```<code><logger name="PROTOCOL_MESSAGE" level="DEBUG" />
</code>```

Body:
I developed a Service Provider by using Spring SAML.
I've configured several IdPs, each of them with a different naming conventions for the attributes.

Could I log (on Tomcat's logs/catalina.out file) an entire SAML response after a successful AuthN process?

Are there some native features in order to define an association between a certain IdP's EntityID and the attribute that maps the returned userID?

I'm also reading about the OID format: how can I properly decode this kind of data?

Update:

About the first question, according to the documentation, I setup up both debug logging and authentication logging as follows:

// Logger for SAML messages and events
@Bean
public SAMLDefaultLogger samlDefaultLogger() {
    SAMLDefaultLogger samlDefaultLogger = new SAMLDefaultLogger();
    samlDefaultLogger.setLogMessages(true);
    samlDefaultLogger.setLogErrors(true);
    return samlDefaultLogger;
}

Then, by defining a log4j.properties as follows:

log4j.logger.org.springframework.security.saml=DEBUG
log4j.logger.org.opensaml=DEBUG

And by properly configuring the Maven pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

Despite that, the complete SAML response doesn't appear (I'm expecting an XML message). The output is as follows:

[2014-07-29 14:13:51.985] boot - 1118 DEBUG [http-bio-443-exec-38] --- MetadataCredentialResolver: Attempting to retrieve credentials from cache using index: [http:/test.idp.prv/services/trust,{urn:oasis:names:tc:SAML:2.0:metadata}IDPSSODescriptor,urn:oasis:names:tc:SAML:2.0:protocol,SIGNING]
[2014-07-29 14:13:51.985] boot - 1118 DEBUG [http-bio-443-exec-38] --- MetadataCredentialResolver: Retrieved credentials from cache using index: [http:/test.idp.prv/services/trust,{urn:oasis:names:tc:SAML:2.0:metadata}IDPSSODescriptor,urn:oasis:names:tc:SAML:2.0:protocol,SIGNING]
[2014-07-29 14:13:51.985] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableUsageCredentialCriteria for criteria class org.opensaml.xml.security.criteria.UsageCriteria
[2014-07-29 14:13:51.986] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableKeyAlgorithmCredentialCriteria for criteria class org.opensaml.xml.security.criteria.KeyAlgorithmCriteria
[2014-07-29 14:13:51.986] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableEntityIDCredentialCriteria for criteria class org.opensaml.xml.security.criteria.EntityIDCriteria
[2014-07-29 14:13:51.986] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry could not locate evaluable criteria for criteria class org.opensaml.security.MetadataCriteria
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Attempting to verify signature and establish trust using KeyInfo-derived credentials
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Found 0 key names: []
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Processing KeyInfo child with qname: {http://www.w3.org/2000/09/xmldsig#}X509Data
[2014-07-29 14:13:51.987] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Provider org.opensaml.xml.security.keyinfo.provider.RSAKeyValueProvider doesn't handle objects of type {http://www.w3.org/2000/09/xmldsig#}X509Data, skipping
[2014-07-29 14:13:51.988] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Provider org.opensaml.xml.security.keyinfo.provider.DSAKeyValueProvider doesn't handle objects of type {http://www.w3.org/2000/09/xmldsig#}X509Data, skipping
[2014-07-29 14:13:51.988] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Processing KeyInfo child {http://www.w3.org/2000/09/xmldsig#}X509Data with provider org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider
[2014-07-29 14:13:51.988] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Attempting to extract credential from an X509Data
[2014-07-29 14:13:51.993] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Found 1 X509Certificates
[2014-07-29 14:13:51.993] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Found 0 X509CRLs
[2014-07-29 14:13:51.993] boot - 1118 DEBUG [http-bio-443-exec-38] --- InlineX509DataProvider: Single certificate was present, treating as end-entity certificate
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: Credentials successfully extracted from child {http://www.w3.org/2000/09/xmldsig#}X509Data by provider org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- BasicProviderKeyInfoCredentialResolver: A total of 1 credentials were resolved
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- EvaluableCredentialCriteriaRegistry: Registry could not locate evaluable criteria for criteria class org.opensaml.xml.security.keyinfo.KeyInfoCriteria
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Attempting to validate signature using key from supplied credential
[2014-07-29 14:13:51.994] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Creating XMLSignature object
[2014-07-29 14:13:51.995] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Validating signature with signature algorithm URI: http://www.w3.org/2000/09/xmldsig#rsa-sha1
[2014-07-29 14:13:51.995] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl'
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- SignatureValidator: Signature validated with key from supplied credential
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Signature validation using candidate credential was successful
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Successfully verified signature using KeyInfo-derived credential
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Attempting to establish trust of KeyInfo-derived credential
[2014-07-29 14:13:51.999] boot - 1118 DEBUG [http-bio-443-exec-38] --- ExplicitKeyTrustEvaluator: Successfully validated untrusted credential against trusted key
[2014-07-29 14:13:52.000] boot - 1118 DEBUG [http-bio-443-exec-38] --- BaseSignatureTrustEngine: Successfully established trust of KeyInfo-derived credential
[2014-07-29 14:13:52.000] boot - 1118 DEBUG [http-bio-443-exec-38] --- WebSSOProfileConsumerImpl: Processing Bearer subject confirmation
[2014-07-29 14:13:52.000] boot - 1118 DEBUG [http-bio-443-exec-38] --- WebSSOProfileConsumerImpl: Verifying received AuthnContext org.opensaml.saml2.core.impl.AuthnContextImpl@3ab2fc5f against requested null
[2014-07-29 14:13:52.001] boot - 1118  INFO [http-bio-443-exec-38] --- PrismaUserDetailsServiceImpl: SAML Response      EntityID: urn:com:vdenotaris:mysp
[2014-07-29 14:13:52.001] boot - 1118  INFO [http-bio-443-exec-38] --- PrismaUserDetailsServiceImpl: SAML Response      RemoteEntityID: http:/test.idp.prv/services/trust

Note that the last two lines are defined manually by me.

Body:
How about adding this:

log4j.logger.PROTOCOL_MESSAGE=DEBUG

Or this for Logback:

<logger name="PROTOCOL_MESSAGE" level="DEBUG" />


问:
I want to be able to print stack traces java style in c
Simple question, I want to be able to print stack traces java style in c. I have the signal handlers set up and I get the stack trace addresses but I want to translate the addresses to the function names. Therefore, I decided to implement reflection. Right now I have tables as follows: {"FOO", &FOO, "BAR", &BAR}. While this solution works for all platforms, it is really annoying to keep up to date. Is there another way to do this (one that wouldnt require manual upkeep?)</p>

答:
You do not need to keep track of the tables yourself, the linker will do that for you already. It's called the 'symbol table'. You can configure your compiler/linker to include this table in the final output or leave it out. You could use that table to lookup the function names when walking the stack.

If you want easy stack tracing in C, use a debugger like GDB. Otherwise, there are already libraries and other solutions that provide this functionality. Look at this one for example: http://www.nongnu.org/libunwind/


问:
Data binding for TextBox
I have a basic property that stores an object of type Fruit:

```<code>Fruit food;
public Fruit Food
{
    get {return this.food;}
    set
    {
        this.food= value;
        this.RefreshDataBindings();
    }
}

public void RefreshDataBindings()
{
    this.textBox.DataBindings.Clear();
    this.textBox.DataBindings.Add("Text", this.Food, "Name");
}
</code>```

So I set this.Food outside the form and then it shows up in the UI.

If I modify this.Food, it updates correctly. If I modify the UI programmatically like:

this.textBox.Text = "NewFruit", it doesn't update this.Food.

Why could this be? I also implemented INotifyPropertyChanged for Fruit.Name, but still the same.

答:
We can use following code

```<code>textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
</code>```

Where

"Text" – the property of textbox

model  – the model object enter code here

"Name" – the value of model which to bind the textbox.

Title: Data binding for TextBox

Body:
I have a basic property that stores an object of type Fruit:

Fruit food;
public Fruit Food
{
    get {return this.food;}
    set
    {
        this.food= value;
        this.RefreshDataBindings();
    }
}

public void RefreshDataBindings()
{
    this.textBox.DataBindings.Clear();
    this.textBox.DataBindings.Add("Text", this.Food, "Name");
}

So I set this.Food outside the form and then it shows up in the UI.

If I modify this.Food, it updates correctly. If I modify the UI programmatically like:

this.textBox.Text = "NewFruit", it doesn't update this.Food.

Why could this be? I also implemented INotifyPropertyChanged for Fruit.Name, but still the same.

Body:
We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

"Text" – the property of textbox

model  – the model object enter code here

"Name" – the value of model which to bind the textbox.


问:
How to handle null or empty responses using retrofit
From the server, sometimes we are getting a response that is null or empty. Because of this, our code will crash at some null pointer exception. We don't want to have null checks everywhere in code. Is there a way to specify default values when a retrofit response is null or empty? In the code below, this is how we can handle it on a case-by-case basis. But, we do not want to write this logic for every object. We want to do this somehow at the application level. Is that possible?</p>

```<code>@SerializedName("isPdf")
@Expose
private String isPdf;

public boolean getIsPdf() {
    return !Util.isNullOrEmpty(isPdf) && isPdf.equalsIgnoreCase("true") ? true : false;
}

public void setIsPDF(boolean isPdf) {

    this.isPdf = isPdf ? "true" : "false";
}
</code>```

答:
You can create a default callback that handles a null response the way you want. For example, calling onFailure:

```<code>public class DefaultCallback<T> implements Callback<T> {

    private static final String TAG = "YOUR_TAG";
    private Callback<T> callback;

    public DefaultCallback(Callback<T> callback) {
        this.callback = callback;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.body() == null) {
            callback.onFailure(call, new NullPointerException("Empty response"));
        } else {
            callback.onResponse(call, response);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        Log.e(TAG, t.toString());
        callback.onFailure(call, t);
    }
}
</code>```

And then use this callback in your implementation.

```<code>Call<MyObject> call = ... //Create your call
call.enqueue(new DefaultCallback<>(new Callback<MyObject>() {
    @Override
    public void onResponse(Call<MyObject> call, Response<MyObject> response) {
        //Handle successful non-null responses
    }

    @Override
    public void onFailure(Call<MyObject> call, Throwable t) {
        //Handle errors/null responses
    }
}));
</code>```

Body:
From the server, sometimes we are getting a response that is null or empty. Because of this, our code will crash at some null pointer exception. We don't want to have null checks everywhere in code. Is there a way to specify default values when a retrofit response is null or empty? In the code below, this is how we can handle it on a case-by-case basis. But, we do not want to write this logic for every object. We want to do this somehow at the application level. Is that possible?

@SerializedName("isPdf")
@Expose
private String isPdf;

public boolean getIsPdf() {
    return !Util.isNullOrEmpty(isPdf) && isPdf.equalsIgnoreCase("true") ? true : false;
}

public void setIsPDF(boolean isPdf) {

    this.isPdf = isPdf ? "true" : "false";
}

Body:
You can create a default callback that handles a null response the way you want. For example, calling onFailure:

public class DefaultCallback<T> implements Callback<T> {

    private static final String TAG = "YOUR_TAG";
    private Callback<T> callback;

    public DefaultCallback(Callback<T> callback) {
        this.callback = callback;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.body() == null) {
            callback.onFailure(call, new NullPointerException("Empty response"));
        } else {
            callback.onResponse(call, response);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        Log.e(TAG, t.toString());
        callback.onFailure(call, t);
    }
}

And then use this callback in your implementation.

Call<MyObject> call = ... //Create your call
call.enqueue(new DefaultCallback<>(new Callback<MyObject>() {
    @Override
    public void onResponse(Call<MyObject> call, Response<MyObject> response) {
        //Handle successful non-null responses
    }

    @Override
    public void onFailure(Call<MyObject> call, Throwable t) {
        //Handle errors/null responses
    }
}));


问:
Keep bootstrap 4 navbar at the top and transparent
The only way I am able to keep my navbar transparent so far is by setting it to fixed-top like such:

```<code><nav class="navbar fixed-top navbar-inverse">
    <!-- more html -->
</nav>
</code>```

As you can see here.

I wish for my navbar to be stuck at the top of my page and to be transparent at the same time. Removing fixed-top removed the transparency and pushes my landing page picture (and component as a whole) under the navbar (when it should overlap the picture).

How can that be achieved?

答:
Try this:

```<code><nav class="navbar navbar-overlay navbar-inverse">
    <!-- more html -->
</nav>
</code>```

Then in your CSS write this:

```<code>.navbar-overlay {
    margin-bottom: -104px; // Pulls the content under the navbar up by 104px which is the height of your navbar.
    z-index: 1; // Tells the browser that your navbar should be ontop of your content. This allows your links in your navbar to still work when you hover over them.
}
</code>```

Body:
The only way I am able to keep my navbar transparent so far is by setting it to fixed-top like such:

As you can see here.

I wish for my navbar to be stuck at the top of my page and to be transparent at the same time. Removing fixed-top removed the transparency and pushes my landing page picture (and component as a whole) under the navbar (when it should overlap the picture).

How can that be achieved?

Body:
Try this:

<nav class="navbar navbar-overlay navbar-inverse">
    <!-- more html -->
</nav>

Then in your CSS write this:

.navbar-overlay {
    margin-bottom: -104px; // Pulls the content under the navbar up by 104px which is the height of your navbar.
    z-index: 1; // Tells the browser that your navbar should be ontop of your content. This allows your links in your navbar to still work when you hover over them.
}


问:
How to convert an array of char to array of int
Is there a way to convert an array of char to array of int32 without iterating every member.

I need to convert a huge amount of data so I'm looking for some faster than:

```<code>char ac[1000000];
int32_t ai[1000000];
for(int i=0;i<1000000;i++) {
    ai[i]=ac[i];
}
</code>```

Notes:

I'm not asking about how to convert '3' to 0x03, I'm talking about convert 0x03 (one byte) to 0x00000003 (to  4 bytes)

Not portable is not a problem (platform linux AMD64).

The proposed method is slow.

looking for a library that use SSE instructions or similar.
I need it to feed a math function that works with int32 numbers and my original data is in 8 bits size, so I need to convert it, and obviously I can't cast because is an memory area not a value.

答:
Is there a way to convert an array of char to array of int without iterate every member.

No.

Trying to explain this (I assumed it would be obvious): an int is a different size than a char, so no block copies would ever help you. In one or another way, you have to touch each element.

There might be solutions parallelizing this, e.g. by partitioning the array and using threads to handle the parts. But you would still have to convert each and every element.

Regarding your edit:

convert 0x03 (one byte) to 0x0003 (to bytes)

  [...] not portable is not a problem (platform linux AMD64)

There seems to be another misconception: int on Linux x86_64 has four bytes, not two. If you really need two bytes per input value, you should use int16_t.

And yet another remark: Typical SIMD instructions (like in SSE2) won't help you either. They assume the same layout of input and output areas. As already stated, the only "optimization" I can possibly see is parallelizing. There's no way around having to touch each element.

Body:
Is there a way to convert an array of char to array of int32 without iterating every member.

I need to convert a huge amount of data so I'm looking for some faster than:

char ac[1000000];
int32_t ai[1000000];
for(int i=0;i<1000000;i++) {
    ai[i]=ac[i];
}

Notes:

I'm not asking about how to convert '3' to 0x03, I'm talking about convert 0x03 (one byte) to 0x00000003 (to  4 bytes)

Not portable is not a problem (platform linux AMD64).

The proposed method is slow.

looking for a library that use SSE instructions or similar.
I need it to feed a math function that works with int32 numbers and my original data is in 8 bits size, so I need to convert it, and obviously I can't cast because is an memory area not a value.


问:
how to do android image animation
i am trying to get a simple image animation going. i want to make it looks as if the helicopter's propeller blades are turning.  i have 3 images for the helicopter, and i am showing one of these images depending on the animation progress. the problem is that all three images end up overlapping each other as opposed to just one image showing up at one time, thereby creating the animation.  this is what i did so far, i even tried to clear canvas by doing this canvas.drawColor(Color.BLACK), but that would clear out the whole canvas, which is not what i want.

this is what i have:

1) in the View class:

static class Helicopter {
        private long mLastUpdate;
        private long mProgress = 0;
        private final float mX;
        private final float mY;

```<code>    private final Bitmap mHelicopter1;
    private final Bitmap mHelicopter2;
    private final Bitmap mHelicopter3;
    private final float mRadius;

    Helicopter(long mLastUpdate, float mX, float mY,
              Bitmap helicopter1, Bitmap helicopter2, Bitmap helicopter3) {
        this.mLastUpdate = mLastUpdate;
        this.mX = mX;
        this.mY = mY;
        this.mHelicopter1 = helicopter1;
        this.mHelicopter2 = helicopter2;
        this.mHelicopter3 = helicopter3;
        mRadius = ((float) mHelicopter1.getWidth()) / 2f;

    }

    public void update(long now) {
        mProgress += (now - mLastUpdate);

        if(mProgress >= 400L)
        {
         mProgress = 0;
        }
        mLastUpdate = now;
    }

    public void setNow(long now) {
        mLastUpdate = now;
    }

    public void draw(Canvas canvas, Paint paint)
    {

        if (mProgress < 150L)
        {
            canvas.drawBitmap(mHelicopter1, mX - mRadius, mY - mRadius, paint);
        }
        else if (mProgress < 300L)
        {
            canvas.drawBitmap(mHelicopter2, mX - mRadius, mY - mRadius, paint);

        }
        else if(mProgress < 400L)
        {
         canvas.drawBitmap(mHelicopter3, mX - mRadius, mY - mRadius, paint);
        }

    }

    public boolean done() {
        return mProgress > 700L;
    }
}

private ArrayList<Helicopter> mHelicopters = new ArrayList<Helicopter>();
</code>```

2)    this is being called in the run() of a thread:

```<code>private void doDraw(Canvas canvas)
    {
     final long now = SystemClock.elapsedRealtime();

        canvas.save();

        for (int i = 0; i < mHelicopters.size(); i++) {
            final Helicopter explosion = mHelicopters.get(i);
            explosion.update(now);
        }

        for (int i = 0; i < mHelicopters.size(); i++) {
            final Helicopter explosion = mHelicopters.get(i);
            explosion.draw(canvas, mPaint);
        }

        canvas.restore();
    }
</code>```

can someone help me?  i have looked at a lot of the examples on the web on animation, they seem to always involve text, but not images.  thanks.

答:
It is maybe late but the response seems to be here :
http://developer.android.com/guide/topics/graphics/2d-graphics.html#frame-animation</p>

Title: how to do android image animation

Body:
i am trying to get a simple image animation going. i want to make it looks as if the helicopter's propeller blades are turning.  i have 3 images for the helicopter, and i am showing one of these images depending on the animation progress. the problem is that all three images end up overlapping each other as opposed to just one image showing up at one time, thereby creating the animation.  this is what i did so far, i even tried to clear canvas by doing this canvas.drawColor(Color.BLACK), but that would clear out the whole canvas, which is not what i want.

this is what i have:

1) in the View class:

static class Helicopter {
        private long mLastUpdate;
        private long mProgress = 0;
        private final float mX;
        private final float mY;

    private final Bitmap mHelicopter1;
    private final Bitmap mHelicopter2;
    private final Bitmap mHelicopter3;
    private final float mRadius;

    Helicopter(long mLastUpdate, float mX, float mY,
              Bitmap helicopter1, Bitmap helicopter2, Bitmap helicopter3) {
        this.mLastUpdate = mLastUpdate;
        this.mX = mX;
        this.mY = mY;
        this.mHelicopter1 = helicopter1;
        this.mHelicopter2 = helicopter2;
        this.mHelicopter3 = helicopter3;
        mRadius = ((float) mHelicopter1.getWidth()) / 2f;

    }

    public void update(long now) {
        mProgress += (now - mLastUpdate);

        if(mProgress >= 400L)
        {
         mProgress = 0;
        }
        mLastUpdate = now;
    }

    public void setNow(long now) {
        mLastUpdate = now;
    }

    public void draw(Canvas canvas, Paint paint)
    {

        if (mProgress < 150L)
        {
            canvas.drawBitmap(mHelicopter1, mX - mRadius, mY - mRadius, paint);
        }
        else if (mProgress < 300L)
        {
            canvas.drawBitmap(mHelicopter2, mX - mRadius, mY - mRadius, paint);

        }
        else if(mProgress < 400L)
        {
         canvas.drawBitmap(mHelicopter3, mX - mRadius, mY - mRadius, paint);
        }

    }

    public boolean done() {
        return mProgress > 700L;
    }
}

private ArrayList<Helicopter> mHelicopters = new ArrayList<Helicopter>();

2)    this is being called in the run() of a thread:

private void doDraw(Canvas canvas)
    {
     final long now = SystemClock.elapsedRealtime();

        canvas.save();

        for (int i = 0; i < mHelicopters.size(); i++) {
            final Helicopter explosion = mHelicopters.get(i);
            explosion.update(now);
        }

        for (int i = 0; i < mHelicopters.size(); i++) {
            final Helicopter explosion = mHelicopters.get(i);
            explosion.draw(canvas, mPaint);
        }

        canvas.restore();
    }

can someone help me?  i have looked at a lot of the examples on the web on animation, they seem to always involve text, but not images.  thanks.


问:
XMLHttpRequest Cannot Load https://[website].com Cross Origin Requests are not supported
I ran my JavaScript file with phantomjs --web-security=no myfile.js successfully in my MacBook (with macOS), but fail to run it on Ubuntu, where it give out this error:

```<code>XMLHttpRequest Cannot Load https://[website].com Cross Origin
Requests are not supported
</code>```

I find my problem is different from questions below

XMLHttpRequest cannot load Cross origin requests are only supported for HTTP

XMLHttpRequest cannot load https://www.[website].com/

For the first one, my error message is simply 'not supported', but not tell my 'only supported for HTTP' (though I send request to a HTTPS url).
For the second one, my error message doesn't require the 'Access-Control-Allow-Origin' header.

I tried --debug=true option for PhantomJS, and it turned out that when running within Ubuntu, the PhantomJS silently dropping cookies.

Under my circumstance, could any one tell me how to fix this?

答:
phantomjs seems to have an option which allows to make XMLHttpRequests from local files to a http server: --local-to-remote-url-access

For reference: http://phantomjs.org/api/command-line.html

Body:
I ran my JavaScript file with phantomjs --web-security=no myfile.js successfully in my MacBook (with macOS), but fail to run it on Ubuntu, where it give out this error:

XMLHttpRequest Cannot Load https://[website].com Cross Origin
Requests are not supported

I find my problem is different from questions below

XMLHttpRequest cannot load Cross origin requests are only supported for HTTP

XMLHttpRequest cannot load https://www.[website].com/

For the first one, my error message is simply 'not supported', but not tell my 'only supported for HTTP' (though I send request to a HTTPS url).
For the second one, my error message doesn't require the 'Access-Control-Allow-Origin' header.

I tried --debug=true option for PhantomJS, and it turned out that when running within Ubuntu, the PhantomJS silently dropping cookies.

Under my circumstance, could any one tell me how to fix this?


问:
Jquery count closing divs
How can I count the occurence of closing divs

```<code>$("body").html().match(/\/div/gi).length;
</code>```

The Code above is not working as expected, although I escaped the slash.
https://jsfiddle.net/zjqtpje4/1/

答:
Firstly, never use Regex to parse HTML.

Secondly, the number of closing div tags will always be equal to the number of opening div tags as the browser will automatically insert any mismatching tags.

You can see this behaviour in the console of the below snippet. Two closing
 will be added to the code:

console.log($("body").html().match(/\/div/gi).length);
console.log($('body').html());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
      <div></div></code>```

The only way this could work is if you can work with the HTML as a string before it is placed in the DOM. This will prevent the HTML being corrected.

Title: Jquery count closing divs

Body:
How can I count the occurence of closing divs

$("body").html().match(/\/div/gi).length;

The Code above is not working as expected, although I escaped the slash.
https://jsfiddle.net/zjqtpje4/1/

Body:
Firstly, never use Regex to parse HTML.

Secondly, the number of closing div tags will always be equal to the number of opening div tags as the browser will automatically insert any mismatching tags.

You can see this behaviour in the console of the below snippet. Two closing </div> will be added to the code:

console.log($("body").html().match(/\/div/gi).length);
console.log($('body').html());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
      <div></div>

The only way this could work is if you can work with the HTML as a string before it is placed in the DOM. This will prevent the HTML being corrected.


问:
How to take my widget in QListWidget, using currentItemChanged signal?
I have QListWidget pointer (pListWidget). A have my custom (QCustomItem) widget, inerited from QWidget and containing some data. I adding some widgets into the list:

```<code>int iMyData = 555;
...
QListWidgetItem *pListWidgetItem = new QListWidgetItem();
QCustomItem *pCustomWidget = new QCustomItem(iMyData);
pListWidget->addItem(pListWidgetItem);
pListWidget->setItemWidget(pListWidgetItem, pCustomWidget);
...
</code>```

This part of code may be in cycle (adding few widgets).

Also I detecting item changing by connection:

```<code>connect(pListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(slotItemChanged(QListWidgetItem*,QListWidgetItem*)) );
</code>```

And slot realization:

```<code>void QSomeForm::slotItemChanged(QListWidgetItem* pCurrent, QListWidgetItem* pPrevious)
{
  QCustomItem *pCustomWidget = // And this is my question: how to take my custom widget in this block code using pListWidget and pCurrent?

  // Processing pCustomWidget
  int iMyData = pCustomWidget->iMyData(); // In current example I want to see 555 here
}
</code>```

How I can extract my widget from QListWidget ? Thanks! I hope on your help!

答:
Read the doc. If you have found QListWidget::setItemWidget() you can find:

```<code>QWidget * QListWidget::itemWidget(QListWidgetItem * item) const
</code>```

Body:
I have QListWidget pointer (pListWidget). A have my custom (QCustomItem) widget, inerited from QWidget and containing some data. I adding some widgets into the list:

int iMyData = 555;
...
QListWidgetItem *pListWidgetItem = new QListWidgetItem();
QCustomItem *pCustomWidget = new QCustomItem(iMyData);
pListWidget->addItem(pListWidgetItem);
pListWidget->setItemWidget(pListWidgetItem, pCustomWidget);
...

This part of code may be in cycle (adding few widgets).

Also I detecting item changing by connection:

connect(pListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(slotItemChanged(QListWidgetItem*,QListWidgetItem*)) );

And slot realization:

void QSomeForm::slotItemChanged(QListWidgetItem* pCurrent, QListWidgetItem* pPrevious)
{
  QCustomItem *pCustomWidget = // And this is my question: how to take my custom widget in this block code using pListWidget and pCurrent?

  // Processing pCustomWidget
  int iMyData = pCustomWidget->iMyData(); // In current example I want to see 555 here
}

How I can extract my widget from QListWidget ? Thanks! I hope on your help!

Body:
Read the doc. If you have found QListWidget::setItemWidget() you can find:

QWidget * QListWidget::itemWidget(QListWidgetItem * item) const


问:
SQL: If exists, limit user. If not exists show everything
I'm trying to found the best way to this requirements:

@fkStaffID INT = Current user.

If @fkStaffID got resource BLABLA only show rows of table X where is StaffID is here. If he DON'T have resource BLABLA, show everything.

SORRY I cannot paste full SQL, for employer's security policy. (I wish I show enough for help, not too much for security...)

What I do:

```<code>SELECT * FROM X
WHERE ((EXISTS
(SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) AND X.fkStaff=@fkStaffID)
OR ((NOT EXISTS (SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) )
</code>```

PROBLEM: It's really slow. Can I do a more efficient way? Can I do another way? Thank you for your help!

答:
I would try this:

```<code>if exists(select 1 from staff where pkstaff=@fkstaffid)
    begin
        select * from X where ResourceName = 'Blabla' and fkStaff = @fkStaffId
    end
else
    begin
        select * from X where ResourceName = 'Blabla'
    end
</code>```

If we have a matching record, then we filter by that @fkStaffId, otherwise we select everything.

Body:
I'm trying to found the best way to this requirements:

@fkStaffID INT = Current user.

If @fkStaffID got resource BLABLA only show rows of table X where is StaffID is here. If he DON'T have resource BLABLA, show everything.

SORRY I cannot paste full SQL, for employer's security policy. (I wish I show enough for help, not too much for security...)

What I do:

SELECT * FROM X
WHERE ((EXISTS
(SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) AND X.fkStaff=@fkStaffID)
OR ((NOT EXISTS (SELECT 1 FROM STAFF WHERE pkStaff=@fkStaffID
AND STAFF.PkStaff IN (SELECT fkStaff FROM SECURITYSUBQUERY WHERE ResourceName='BLABLA')) )

PROBLEM: It's really slow. Can I do a more efficient way? Can I do another way? Thank you for your help!

Body:
I would try this:

if exists(select 1 from staff where pkstaff=@fkstaffid)
    begin
        select * from X where ResourceName = 'Blabla' and fkStaff = @fkStaffId
    end
else
    begin
        select * from X where ResourceName = 'Blabla'
    end

If we have a matching record, then we filter by that @fkStaffId, otherwise we select everything.


问:
Java reAdd items that have been removed from JComboBox
What i'm trying to do is whenever i press the "Remove" Button it will remove the item that i have selected in the JComboBox. So once i have removed all the items, I have another button called "Reset" where all the items that have been removed will be inside the JComboBox again and is it possible to have a restore method instead of having to reAdd each model again cause my actual program has lots of models

This is what i have tried but it doesnt work any suggestions how can this be done?

```<code>public class Testing{

    JFrame frame;
    JPanel panel;
    JButton remove,reset;
    JComboBox box;
    final DefaultComboBoxModel items = new DefaultComboBoxModel(new String[]
    {
        "-","Database System","Computer Fundamentals",
        "Computer Maths","Internet Web Tech","Tertiary English 1"
    });

    public void display()
    {
        frame = new JFrame();
        panel = new JPanel();

        box = new JComboBox();
        box.setModel(items);
        remove = new JButton("Remove");
        reset = new JButton("Reset");

        remove.addActionListener((ActionEvent e)->{
        box.removeItem(box.getSelectedItem());
        });

        reset.addActionListener((ActionEvent e)->{
        System.out.println("Reset");
        box.setModel(items);
        box.revalidate();
        box.repaint();

        });

        panel.revalidate();
        panel.repaint();
        panel.add(box);
        panel.add(remove);
        panel.add(reset);
        frame.add(panel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
    }

    public static void main(String[] args)
    {
        TestingProgram te = new TestingProgram();
        te.display();
    }
}
</code>```

答:
I fixed it. Here is the new code:

```<code> public class Test{

    JFrame frame;
    JPanel panel;
    JButton remove,reset;
    JComboBox box;
    final DefaultComboBoxModel items = new DefaultComboBoxModel(new String[]
    {
        "-","Database System","Computer Fundamentals",
        "Computer Maths","Internet Web Tech","Tertiary English 1"
    });
    public DefaultComboBoxModel getClone(DefaultComboBoxModel items) {
        DefaultComboBoxModel clone = new DefaultComboBoxModel();
        for(int i = 0;i<items.getSize();i++) {
            clone.addElement(items.getElementAt(i));
        }
        return clone;
    }
    public void display()
    {
        frame = new JFrame();
        panel = new JPanel();

        box = new JComboBox();
        box.setModel(getClone(items));
        remove = new JButton("Remove");
        reset = new JButton("Reset");

        remove.addActionListener((ActionEvent e)->{
        box.removeItem(box.getSelectedItem());
        });

        reset.addActionListener((ActionEvent e)->{

        box.setModel(getClone(items));

        });

        panel.revalidate();
        panel.repaint();
        panel.add(box);
        panel.add(remove);
        panel.add(reset);
        frame.add(panel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
    }

    public static void main(String[] args)
    {
        Test te = new Test();
        te.display();
    }
 }
</code>```

The problem was that you were using the same DefaultComboBoxModel, and every time you removed an item from the JComboBox, it actually removed it from your DefaultComboBoxModel item. That means that when you reset the model, the stuff you removed had also been removed from your DefaultComboBoxModel, and it didn't do anything

This new code makes a clone of your DefaultComboBoxModel and adds that, so when you remove stuff from it, it doesn't effect the final one

Body:
What i'm trying to do is whenever i press the "Remove" Button it will remove the item that i have selected in the JComboBox. So once i have removed all the items, I have another button called "Reset" where all the items that have been removed will be inside the JComboBox again and is it possible to have a restore method instead of having to reAdd each model again cause my actual program has lots of models

This is what i have tried but it doesnt work any suggestions how can this be done?

public class Testing{

    JFrame frame;
    JPanel panel;
    JButton remove,reset;
    JComboBox box;
    final DefaultComboBoxModel items = new DefaultComboBoxModel(new String[]
    {
        "-","Database System","Computer Fundamentals",
        "Computer Maths","Internet Web Tech","Tertiary English 1"
    });

    public void display()
    {
        frame = new JFrame();
        panel = new JPanel();

        box = new JComboBox();
        box.setModel(items);
        remove = new JButton("Remove");
        reset = new JButton("Reset");

        remove.addActionListener((ActionEvent e)->{
        box.removeItem(box.getSelectedItem());
        });

        reset.addActionListener((ActionEvent e)->{
        System.out.println("Reset");
        box.setModel(items);
        box.revalidate();
        box.repaint();

        });

        panel.revalidate();
        panel.repaint();
        panel.add(box);
        panel.add(remove);
        panel.add(reset);
        frame.add(panel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
    }

    public static void main(String[] args)
    {
        TestingProgram te = new TestingProgram();
        te.display();
    }
}

Body:
I fixed it. Here is the new code:

 public class Test{

    JFrame frame;
    JPanel panel;
    JButton remove,reset;
    JComboBox box;
    final DefaultComboBoxModel items = new DefaultComboBoxModel(new String[]
    {
        "-","Database System","Computer Fundamentals",
        "Computer Maths","Internet Web Tech","Tertiary English 1"
    });
    public DefaultComboBoxModel getClone(DefaultComboBoxModel items) {
        DefaultComboBoxModel clone = new DefaultComboBoxModel();
        for(int i = 0;i<items.getSize();i++) {
            clone.addElement(items.getElementAt(i));
        }
        return clone;
    }
    public void display()
    {
        frame = new JFrame();
        panel = new JPanel();

        box = new JComboBox();
        box.setModel(getClone(items));
        remove = new JButton("Remove");
        reset = new JButton("Reset");

        remove.addActionListener((ActionEvent e)->{
        box.removeItem(box.getSelectedItem());
        });

        reset.addActionListener((ActionEvent e)->{

        box.setModel(getClone(items));

        });

        panel.revalidate();
        panel.repaint();
        panel.add(box);
        panel.add(remove);
        panel.add(reset);
        frame.add(panel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
    }

    public static void main(String[] args)
    {
        Test te = new Test();
        te.display();
    }
 }

The problem was that you were using the same DefaultComboBoxModel, and every time you removed an item from the JComboBox, it actually removed it from your DefaultComboBoxModel item. That means that when you reset the model, the stuff you removed had also been removed from your DefaultComboBoxModel, and it didn't do anything

This new code makes a clone of your DefaultComboBoxModel and adds that, so when you remove stuff from it, it doesn't effect the final one


问:
Bootstrap Open Image in Modal having dynamic image src
My question is regarding this answer. Bootstrap open image in modal

How can I display images that's src comes from MySQL database?

答:
simply echo the img source from the database.

```<code><?php
  if(isset($_POST['profile_id'])){
     var uid=$_POST['profile_id'];
     $result->query("SELECT profile FROM user WHERE uid=$uid");
     $row=$result->fetch_array();
     die(json_encode($row));
  }
?>
</code>```

HTML:

```<code><a href="#" class="pop">
  <img src="" style="width: 400px; height: 264px;">
</a>
</code>```

Jquery Part:

```<code>$.post("ajax.php",{profile_id:1},function(response){
   if(response){
     var profileImg=JSON.parse(response);
         profileImg=profileImg[0].profile;
         $('.pop img').attr('src','http://example.com/image/'+profileImg);
         $('.pop').modal('show');
   }
});
</code>```

Body:
simply echo the img source from the database.

<?php
  if(isset($_POST['profile_id'])){
     var uid=$_POST['profile_id'];
     $result->query("SELECT profile FROM user WHERE uid=$uid");
     $row=$result->fetch_array();
     die(json_encode($row));
  }
?>

HTML:

<a href="#" class="pop">
  <img src="" style="width: 400px; height: 264px;">
</a>

Jquery Part:

$.post("ajax.php",{profile_id:1},function(response){
   if(response){
     var profileImg=JSON.parse(response);
         profileImg=profileImg[0].profile;
         $('.pop img').attr('src','http://example.com/image/'+profileImg);
         $('.pop').modal('show');
   }
});


问:
Create slug with id in Laravel
I would like to create a slug with the element ID, i have try with:

```<code>$article->slug = $article->id.'-'.Str::slug($article->name, '-');
</code>```

But instead of returning me:

247-Hello-World

It saves me:

-Hello-World

It's just a post of a new article, Example, if the previous article was ID 246, This article becomes 247-Slug-a-b-c. How do I pick up the ID that this article will have?

答:
Try creating the slug AFTER creating the article.

```<code>$article->save();
$articleID = $article->id;
$article->slug = $articleID.'-'.Str::slug($article->name, '-');
$article->save();
</code>```

Reference for getting the id of the model »

Title: Create slug with id in Laravel

Body:
I would like to create a slug with the element ID, i have try with:

$article->slug = $article->id.'-'.Str::slug($article->name, '-');

But instead of returning me:

247-Hello-World

It saves me:

-Hello-World

It's just a post of a new article, Example, if the previous article was ID 246, This article becomes 247-Slug-a-b-c. How do I pick up the ID that this article will have?

Body:
Try creating the slug AFTER creating the article.

$article->save();
$articleID = $article->id;
$article->slug = $articleID.'-'.Str::slug($article->name, '-');
$article->save();

Reference for getting the id of the model »


问:
Why does PHP remove the space after the first word when returning a string in a function
For some reason, the space after the first word is removed when returning a string in a php function. I can't figure out why.

```<code>function something() {
   $string = "My sentence looks like this";
   return $string;
}

function something_else() {
   $output = something();
   echo $output;
}
</code>```

Outputs "Mysentence looks like this"

Edit:
If I add echo $string; after line 2 it prints $string correctly. However, the second function does not output it that way.

Also, I am able to get it working by changing line 2 to

```<code>$string = "<strong>My sentence</strong looks like this";
</code>```

答: After testing various browsers, the issue seems related to MS Edge only. It works fine in Firefox, Chrome, Safari, and IE.</p>

Body:
For some reason, the space after the first word is removed when returning a string in a php function. I can't figure out why.

function something() {
   $string = "My sentence looks like this";
   return $string;
}

function something_else() {
   $output = something();
   echo $output;
}

Outputs "Mysentence looks like this"

Edit:
If I add echo $string; after line 2 it prints $string correctly. However, the second function does not output it that way.

Also, I am able to get it working by changing line 2 to

$string = "My sentence</strong looks like this";