问:
Python print() and sys.stdout.write() issues
Guys see below code in python 2.7.
I'm having issues with the "print(ciphertext)" and the "sys.stdout.write(ciphertext)" parts of the code
when I run the code the "print(passline) and the "sys.stdout.write(passline)" come out fine i.e. if the file has a line that says "Billz" it will show as is but when I try to output using either function(i.e. sys.stdout.write() and print()) the ciphertext(via the encryptMessage(key, message) method)
the output splits across lines depending on the "myKey" variable (see below for code and example)

*I understand the limitations of the transposition encryption method, but the 'ciphertext' going to a new line before the original line has finished outputting the line from the line it started from

I think the problem is with the encryptMessage() function and how it interacts with the enc() method, i.e. the for ...in... block of the code in particular

Does that make sense?

i think the answer to this can help when
-reading data from files but not overwriting those files
-when trying to code programmes related to logs, password/word lists
-and understand how the for, in and .join works together

```<code>i.e. myKey = 1
C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 1
This is a list of Passwords to be encrypted

This is a list of Passwords to be encrypted

Billz786

Billz786

123456

123456

Milly

Milly

Bilklzcfvcx
Bilklzcfvcx

i.e. myKey = 2

C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 2
This is a list of Passwords to be encrypted

Ti sals fPswrst eecytdhsi  ito asod ob nrpe

Billz786

Blz8
il76
123456

135
246
Milly

Mlyil

Bilklzcfvcx
Bllcvxikzfc

i.e. myKey = 4

C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 4
This is a list of Passwords to be encrypted

T asfsrtecthi t sdo reisl Pws eyds ioao bnp

Billz786

Bz
i7l8l6
123456

15263
4
Milly

Myi
ll
Bilklzcfvcx
Blvizclcxkf

i.e. myKey = 8
C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 8
This is a list of Passwords to be encrypted

Tafreth  d eilPsedsia n
 sstcitsors w y oobp
Billz786

B
illz786
123456

123456

Milly

Milly

Bilklzcfvcx
Bviclxklzcf
</code>```

the code is

```<code>def enc():
    myMessage = raw_input('Enter file name: ')
    myKey = int(raw_input('Enter Key: '))
    text_file = open(myMessage, "r")
    lines = text_file.readlines()
    for passline in lines:
        myMessage = passline
        ciphertext = encryptMessage(myKey, myMessage)
        print(passline)
        #sys.stdout.write(passline)
        print ciphertext
        #sys.stdout.write(ciphertext)
    text_file.close()
def encryptMessage(key, message):
    ciphertext = [''] * key
    for col in range(key):
        pointer = col
        while pointer < len(message):
            ciphertext[col] += message[pointer]
            pointer += key
    return ''.join(ciphertext)
</code>```

答: When using readlines and most other ways of reading lines in files, python includes the newline character(s) in the line (So, in your case, passline contains (a) newline character(s)). To prevent this, use something like passline = passline.rstrip('\n\r') in the start of your for loop

Body:
Guys see below code in python 2.7.
I'm having issues with the "print(ciphertext)" and the "sys.stdout.write(ciphertext)" parts of the code
when I run the code the "print(passline) and the "sys.stdout.write(passline)" come out fine i.e. if the file has a line that says "Billz" it will show as is but when I try to output using either function(i.e. sys.stdout.write() and print()) the ciphertext(via the encryptMessage(key, message) method)
the output splits across lines depending on the "myKey" variable (see below for code and example)

*I understand the limitations of the transposition encryption method, but the 'ciphertext' going to a new line before the original line has finished outputting the line from the line it started from

I think the problem is with the encryptMessage() function and how it interacts with the enc() method, i.e. the for ...in... block of the code in particular

Does that make sense?

i think the answer to this can help when
-reading data from files but not overwriting those files
-when trying to code programmes related to logs, password/word lists
-and understand how the for, in and .join works together

i.e. myKey = 1
C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 1
This is a list of Passwords to be encrypted

This is a list of Passwords to be encrypted

Billz786

Billz786

123456

123456

Milly

Milly

Bilklzcfvcx
Bilklzcfvcx

i.e. myKey = 2

C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 2
This is a list of Passwords to be encrypted

Ti sals fPswrst eecytdhsi  ito asod ob nrpe

Billz786

Blz8
il76
123456

135
246
Milly

Mlyil

Bilklzcfvcx
Bllcvxikzfc

i.e. myKey = 4

C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 4
This is a list of Passwords to be encrypted

T asfsrtecthi t sdo reisl Pws eyds ioao bnp

Billz786

Bz
i7l8l6
123456

15263
4
Milly

Myi
ll
Bilklzcfvcx
Blvizclcxkf

i.e. myKey = 8
C:\Users\baawan\Desktop\Cyber Sec\COMP_lang\python>py cypher7.py
would you like to Encrypt(e) or Decrypt(d): e
Enter file name: pass.txt
Enter Key: 8
This is a list of Passwords to be encrypted

Tafreth  d eilPsedsia n
 sstcitsors w y oobp
Billz786

B
illz786
123456

123456

Milly

Milly

Bilklzcfvcx
Bviclxklzcf

the code is

def enc():
    myMessage = raw_input('Enter file name: ')
    myKey = int(raw_input('Enter Key: '))
    text_file = open(myMessage, "r")
    lines = text_file.readlines()
    for passline in lines:
        myMessage = passline
        ciphertext = encryptMessage(myKey, myMessage)
        print(passline)
        #sys.stdout.write(passline)
        print ciphertext
        #sys.stdout.write(ciphertext)
    text_file.close()
def encryptMessage(key, message):
    ciphertext = [''] * key
    for col in range(key):
        pointer = col
        while pointer < len(message):
            ciphertext[col] += message[pointer]
            pointer += key
    return ''.join(ciphertext)


来源: stackexchange

问:
How to implement Index and Row function in VBA
I would like to write the following in VBA:

```<code>=INDEX(Sheet1!B$4:B$15;(ROW(A1)-1)/730+1)
</code>```

I m trying:

```<code>With Application.WorksheetFunction

 ActiveWorkbook.Worksheets("Some_Sheet").Range("H6") = .Index(ActiveWorkbook.Worksheets("Sheet1").Range("B4:B15")), (Range("A1").Row - 1) / 730 + 1)

End With
</code>```

答:
Is the reference to A1 supposed to be relative to the target cell - so do you want the same value returned for rows 1-730, 731-1460, etc?

If that's the case, then something like:

```<code>Function foo(ByRef c As Range)
    With c
        .Value = Worksheets("Sheet1").Range("B4").Offset(Int(.Row / 730), 0).Value
    End With
End Function
</code>```

Used like:

```<code>Sub test()
    foo Worksheets("Some_Sheet").Range("H1463")
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to write the following in VBA:

=INDEX(Sheet1!B$4:B$15;(ROW(A1)-1)/730+1)

I m trying:

With Application.WorksheetFunction

 ActiveWorkbook.Worksheets("Some_Sheet").Range("H6") = .Index(ActiveWorkbook.Worksheets("Sheet1").Range("B4:B15")), (Range("A1").Row - 1) / 730 + 1)

End With

Body:
Is the reference to A1 supposed to be relative to the target cell - so do you want the same value returned for rows 1-730, 731-1460, etc?

If that's the case, then something like:

Function foo(ByRef c As Range)
    With c
        .Value = Worksheets("Sheet1").Range("B4").Offset(Int(.Row / 730), 0).Value
    End With
End Function

Used like:

Sub test()
    foo Worksheets("Some_Sheet").Range("H1463")
End Sub


问:
How to fire Angular 5 async validator onblur for FormGroup
I am using Angular version 5.0.1 and I'm trying to fire an AsyncValidator on a FormGroup on a blur event on one of the FormControls in the FormGroup.

I can get onBlur to work on a form control using the following:

name: ['', {updateOn: 'blur'}]
```

However, when I try to apply it to a FormGroup it doesn't work.

Is it possible to only fire an AsyncValidator onBlur on a FormGroup, and if not, what is the best way to execute the validator only when the user has finished entering data?

My only other option at the moment is to us some sort of debounce wrapper for my validator.

Just reading through here and it appears I should be able to use updateOn: 'blur' for a form group.

After
  new FormGroup(value, {updateOn: 'blur'}));
  new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

答:
It works on my side. Be aware that the FormBuilder may not support this yet.</p>

```<code>this.formGroup = new FormGroup({
  name: new FormControl('', {validators: []})
}, {
  updateOn: 'blur'
});
</code>```

Body:
I am using Angular version 5.0.1 and I'm trying to fire an AsyncValidator on a FormGroup on a blur event on one of the FormControls in the FormGroup.

I can get onBlur to work on a form control using the following:

name: ['', {updateOn: 'blur'}]

However, when I try to apply it to a FormGroup it doesn't work.

Is it possible to only fire an AsyncValidator onBlur on a FormGroup, and if not, what is the best way to execute the validator only when the user has finished entering data?

My only other option at the moment is to us some sort of debounce wrapper for my validator.

Just reading through here and it appears I should be able to use updateOn: 'blur' for a form group.

After
  new FormGroup(value, {updateOn: 'blur'}));
  new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

Body:
It works on my side. Be aware that the FormBuilder may not support this yet.

this.formGroup = new FormGroup({
  name: new FormControl('', {validators: []})
}, {
  updateOn: 'blur'
});


问:
How to add Close Button in tab of Dynamic WPF Tab control
I have a WPF Tab Control..

i am adding tabs in that TabControl dynamically

Now i want to give a Close Button in every Tab of Tab Control..

So please tell me hopw to add Close button in that Tab Control..

Code for adding tab

```<code>private void AddTab(ITabbedMDI mdiChild)
    {
       if (_mdiChildren.ContainsKey(mdiChild.UniqueTabName))
        {
            //user control is already opened in tab.
            //So set focus to the tab item where the control hosted
            foreach (object item in tcMdi.Items)
            {
                TabItem ti = (TabItem)item;
                if (ti.Name == mdiChild.UniqueTabName)
                {
                    ucChildLoc = (UserControl)mdiChild;
                    ti.Focus();
                    //tcMdi.Width = this.ucChildLoc.Width;
                    //tcMdi.Height = this.ucChildLoc.Height;
                    break;
                }
            }
        }
   }
</code>```

Code for Closing tab

```<code>private void CloseTab(ITabbedMDI tab, EventArgs e)
    {
        TabItem ti = null;
        foreach(TabItem item in tcMdi.Items)
        {
            if (tab.UniqueTabName == ((ITabbedMDI)item.Content).UniqueTabName)
            {
                ti = item;
                break;
            }
        }
        if (ti != null)
        {
            _mdiChildren.Remove(((ITabbedMDI)ti.Content).UniqueTabName);
            tcMdi.Items.Remove(ti);
        }
    }
</code>```

I am using TabControl of this article

http://www.codeproject.com/Articles/32362/Tabbed-MDI-in-WPF

Thanks in Advance..

答:
I have tried several solutions and struggled to find something that looked nice and also highlighted the "X" in the button when the mouse hovers. I finally ended with this one. It also does not require too much code. I hope it helps:

```<code><TabControl>
        <TabItem>
            <TabItem.Header>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0">Output</TextBlock>
                    <Button Grid.Column="1" Name="button_close" Click="button_close_Click">
                  <Button.Template>
                            <ControlTemplate TargetType="Button">
                                <Path Data="M0,0 L8,8 M8,0 L0,8" StrokeThickness="3" VerticalAlignment="Center" Margin="5,4,0,2">
                                    <Path.Style>
                                        <Style TargetType="{x:Type Path}">
                                            <Style.Triggers>
                                                <Trigger Property="IsMouseOver" Value="False">
                                                    <Setter Property="Stroke" Value="LightGray" />
                                                </Trigger>
                                                <Trigger Property="IsMouseOver" Value="True">
                                                    <Setter Property="Stroke" Value="Black" />
                                                </Trigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Path.Style>
                                </Path>
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </Grid>

            </TabItem.Header>
         <TabItem.Content>
         </TabItem.Content>
</code>```

Body:
I have a WPF Tab Control..

i am adding tabs in that TabControl dynamically

Now i want to give a Close Button in every Tab of Tab Control..

So please tell me hopw to add Close button in that Tab Control..

Code for adding tab

private void AddTab(ITabbedMDI mdiChild)
    {
       if (_mdiChildren.ContainsKey(mdiChild.UniqueTabName))
        {
            //user control is already opened in tab.
            //So set focus to the tab item where the control hosted
            foreach (object item in tcMdi.Items)
            {
                TabItem ti = (TabItem)item;
                if (ti.Name == mdiChild.UniqueTabName)
                {
                    ucChildLoc = (UserControl)mdiChild;
                    ti.Focus();
                    //tcMdi.Width = this.ucChildLoc.Width;
                    //tcMdi.Height = this.ucChildLoc.Height;
                    break;
                }
            }
        }
   }

Code for Closing tab

private void CloseTab(ITabbedMDI tab, EventArgs e)
    {
        TabItem ti = null;
        foreach(TabItem item in tcMdi.Items)
        {
            if (tab.UniqueTabName == ((ITabbedMDI)item.Content).UniqueTabName)
            {
                ti = item;
                break;
            }
        }
        if (ti != null)
        {
            _mdiChildren.Remove(((ITabbedMDI)ti.Content).UniqueTabName);
            tcMdi.Items.Remove(ti);
        }
    }

I am using TabControl of this article

http://www.codeproject.com/Articles/32362/Tabbed-MDI-in-WPF

Thanks in Advance..

Body:
I have tried several solutions and struggled to find something that looked nice and also highlighted the "X" in the button when the mouse hovers. I finally ended with this one. It also does not require too much code. I hope it helps:

<TabControl>
        <TabItem>
            <TabItem.Header>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0">Output</TextBlock>
                    <Button Grid.Column="1" Name="button_close" Click="button_close_Click">
                  <Button.Template>
                            <ControlTemplate TargetType="Button">
                                <Path Data="M0,0 L8,8 M8,0 L0,8" StrokeThickness="3" VerticalAlignment="Center" Margin="5,4,0,2">
                                    <Path.Style>
                                        <Style TargetType="{x:Type Path}">
                                            <Style.Triggers>
                                                <Trigger Property="IsMouseOver" Value="False">
                                                    <Setter Property="Stroke" Value="LightGray" />
                                                </Trigger>
                                                <Trigger Property="IsMouseOver" Value="True">
                                                    <Setter Property="Stroke" Value="Black" />
                                                </Trigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Path.Style>
                                </Path>
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </Grid>

            </TabItem.Header>
         <TabItem.Content>
         </TabItem.Content>


问:
Lambdas, closed-over variables, display classes, serializability, and prevalence layers
I've implemented a prevalence layer for Compact Framework (including a BinaryFormatter-like serializer).  I'd like to be able to serialize the compiler-generated classes that result from such things as lambdas and iterators where appropriate, so that if (for example) a lambda and its closed-over variables (that is, the display class instance) is added to an event on a serializable object, and all the closed-over variables are serializable, then the resulting object graph is still fully serializable.

It's acceptable if instances of these classes can only be deserialized by the exact same build of the binaries that they were serialized from -- the prevalence layer is mostly to provide durability should the application be terminated unexpectedly (power failure and device reboot are distinct possibilities), and the serialized data stream is not expected to be either forward or backward compatible, or even for that matter compatible across two compiles of the same source code -- everything of consequence will be sent up to a server when we next talk to it anyway, and we're not going to update while disconnected.

Is it reasonable in this limited context for my formatter to treat these compiler-generated classes as if they were serializable?  The only alternative I see is to hand-implement what areotherwise compiler-supported patterns everywhere serializability is a concern, with consequences ranging from the overly verbose to the nearly unreadable.

答:
I see what you are getting at, but in my experience it is a much better idea to concentrate on serializing data, and handle the durability by rolling back/forward to a known state, perhaps using something like a local CQRS queue, or some other way of storing "how you got there".

Re the specific question, within the tight scope of the question (only working on the same build etc) I guess that should be OK, but it depends a lot on whether anything that is captured in those variables has no sensible serialization - i.e. something like a UI element (easily accidentally captured with an invisible this) that cannot be reconstructed (os handles, etc). If it is isolated data (by which I mean: the graph is just data from within your own code - no unmanaged dependencies), then I guess it should be OK.

The other issue is that CF lacks much of the stronger reflection available in the full framework, that might make this a bit more awkward than it might be on regular framework (GetUninitializedObject for example). Probably doable, but a bit more work.

ContentLicense: CC BY-SA 2.5


问:
Null propagation operator and foreach
Reading a lot about the Null propagation operator ?., I found no answer whether it is helpful in the following scenario.

Code that throws:

```<code>int[] values = null;

foreach ( var i in values ) // Throws since values is null.
{
    // ...
}
</code>```

To make this working, I have to add a null check before access to the values variable.

Most likely the above code is out of scope of the design considerations for the Null propagation operator. Still, to be sure, I have to ask.

My question:

Is the Null propagation operator helpful when trying to access null collections in a foreach loop?

答:
For List<T> you can use list?.ForEach(i => ...); and for other enumerables you can make your own ForEach extension like this:

```<code>public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {

    if (source == null) { return; }

    foreach (T item in source) {
        action(item);
    }
}
</code>```

You call it like this: myPossiblyNullEnumerable.ForEach(i => ...);

If you want your ForEach extension to throw when called for null enumerables, you can just leave the null check away, and call it with the same elvis syntax as the List's version: myPossiblyNullEnumerable?.ForEach(i => ...);

Title: Null propagation operator and foreach

Body:
Reading a lot about the Null propagation operator ?., I found no answer whether it is helpful in the following scenario.

Code that throws:

int[] values = null;

foreach ( var i in values ) // Throws since values is null.
{
    // ...
}

To make this working, I have to add a null check before access to the values variable.

Most likely the above code is out of scope of the design considerations for the Null propagation operator. Still, to be sure, I have to ask.

My question:

Is the Null propagation operator helpful when trying to access null collections in a foreach loop?

Body:
For List<T> you can use list?.ForEach(i => ...); and for other enumerables you can make your own ForEach extension like this:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {

    if (source == null) { return; }

    foreach (T item in source) {
        action(item);
    }
}

You call it like this: myPossiblyNullEnumerable.ForEach(i => ...);

If you want your ForEach extension to throw when called for null enumerables, you can just leave the null check away, and call it with the same elvis syntax as the List's version: myPossiblyNullEnumerable?.ForEach(i => ...);


问:
Datatables and retrieve a value of input field from footer
I've a problem with Datatables and probably cached variables.
I need to retrieve, on submit, #peso_totale_componenti to check it's validity.

Correct value in example is 15.4 like it's input value.

I've inserted an alert to check this input but I get 6.6 (which is value of the first row.)

```<code>  var peso_totale_componenti = $("#peso_totale_componenti").val();
  alert(peso_totale_componenti);
</code>```

I don't know why. But if I change tab-panel or resize window and i click the submit, this time the value in alert is correct (15.4).

It seems to be a problem with cache value of datatables?

UPDATE: ID is unique. I get the sum with a drawcallback in Datatables:

```<code>drawCallback: function () {
      var api = this.api();
      var index = 3; //colonna pesi
      $( api.column(index).footer() ).html( "<input type='hidden' id='peso_totale_componenti' value='" + api.column(index).data().sum() + "'>" + api.column(index).data().sum() ); //peso totale
    },
</code>```

UPDATE 2: Solved using:

```<code>    table.rows().invalidate('dom').draw(false);
</code>```

after every insert/remove of row.

答:
This is because you've used the same ID value twice. ID's should be unique to one element.

Use classes to target multiple elements that need the same styles/js applied then use ID's to target specific elements.

Body:
I've a problem with Datatables and probably cached variables.
I need to retrieve, on submit, #peso_totale_componenti to check it's validity.

Correct value in example is 15.4 like it's input value.

I've inserted an alert to check this input but I get 6.6 (which is value of the first row.)

  var peso_totale_componenti = $("#peso_totale_componenti").val();
  alert(peso_totale_componenti);

I don't know why. But if I change tab-panel or resize window and i click the submit, this time the value in alert is correct (15.4).

It seems to be a problem with cache value of datatables?

UPDATE: ID is unique. I get the sum with a drawcallback in Datatables:

drawCallback: function () {
      var api = this.api();
      var index = 3; //colonna pesi
      $( api.column(index).footer() ).html( "<input type='hidden' id='peso_totale_componenti' value='" + api.column(index).data().sum() + "'>" + api.column(index).data().sum() ); //peso totale
    },

UPDATE 2: Solved using:

    table.rows().invalidate('dom').draw(false);

after every insert/remove of row.


问:
Unable to delete data in CodeIgniter facing Fatal error
fetch_view.php
This is my fetch_view.php file through this file I am showing my html.

```<code><?php
    foreach ($h->result() as $row)
    { ?>
    <tr>
        <td><?php echo $row->fname; ?></td>
        <td><?php echo $row->lname; ?></td>
        <td><?php echo $row->email; ?></td>
        <td><?php echo $row->mobile; ?></td>
        <td><?php echo $row->message; ?></td>
        <td><a href="<?= site_url('home/form').'/'.$row->id ?>">Edit</a></td>

        <td><a href="<?= site_url('home/delete').'/'.$row->id ?>">Delete</a></td>
    </tr>
<?php } ?>
</code>```

select.php
This is my model in this task.

```<code>public function deleteuser($id)
{
     $this->load->database();
     $this->db->where('id', $id);
     $this->db->delete('student');
     return true;
}

**home.php**
</code>```

Controller function, In this file I am making a delete function.
, I have attached screenshot when I tried  to delete data I am facing that error.

```<code>public function delete()
{
     $this->load->model('select');
     $id=$this->input->get('id');
     if($this->select->deleteuser($id))
     {
         $data['data']=$this->select->getuser();
         $this->load->view('fetch_view', $data);
     }
}
</code>```

答:
Everything is working fine but you don't have a getuser() function defined in your model 'select'.

Note: When creating a model Please give name ending with "..._m" like "select_m" you will confuse about it later when your project will get larger.

Body:
fetch_view.php
This is my fetch_view.php file through this file I am showing my html.

<?php
    foreach ($h->result() as $row)
    { ?>

        <?php echo $row->fname; ?>
        <?php echo $row->lname; ?>
        <?php echo $row->email; ?>
        <?php echo $row->mobile; ?>
        <?php echo $row->message; ?>
        <a href="<?= site_url('home/form').'/'.$row->id ?>">Edit

        <a href="<?= site_url('home/delete').'/'.$row->id ?>">Delete

<?php } ?>

select.php
This is my model in this task.

public function deleteuser($id)
{
     $this->load->database();
     $this->db->where('id', $id);
     $this->db->delete('student');
     return true;
}

**home.php**

Controller function, In this file I am making a delete function.
, I have attached screenshot when I tried  to delete data I am facing that error.

public function delete()
{
     $this->load->model('select');
     $id=$this->input->get('id');
     if($this->select->deleteuser($id))
     {
         $data['data']=$this->select->getuser();
         $this->load->view('fetch_view', $data);
     }
}


问:
Vue router-link params
I have a problem with my router-link :to. My router-link doesn't render my template. here is my web routing, routes.js and vue template. I want to go after clik on img product to: 'product/1234' but it redirect me only 'product'. Where is my mistake?
Web:

```<code>     Route::get('/product/{id}', 'ProductController@show');
</code>```

routes.js:

```<code> {
        path: '/product/:id',
        name: 'ProductIndex',
        component: ProductIndex
    }
</code>```

and Vue template:

```<code> <div class="product" v-for="product in products">
            <router-link class="product-image" :to="{ path: 'product', params: { id: product.id}}">
                <img src="/static/shop/products/shoe-example.png"/>
            </router-link>
 </div>
</code>```

答:
You are linking to the path, try changing it to the name of your route:</p>

```<code><router-link class="product-image" :to="{ name: 'ProductIndex', params: { id: product.id}}">
      <img src="/static/shop/products/shoe-example.png"/>
</router-link>
</code>```

Title: Vue router-link params

Body:
I have a problem with my router-link :to. My router-link doesn't render my template. here is my web routing, routes.js and vue template. I want to go after clik on img product to: 'product/1234' but it redirect me only 'product'. Where is my mistake?
Web:

     Route::get('/product/{id}', 'ProductController@show');

routes.js:

 {
        path: '/product/:id',
        name: 'ProductIndex',
        component: ProductIndex
    }

and Vue template:

            <router-link class="product-image" :to="{ path: 'product', params: { id: product.id}}">

            </router-link>

Body:
You are linking to the path, try changing it to the name of your route:

<router-link class="product-image" :to="{ name: 'ProductIndex', params: { id: product.id}}">
      <img src="/static/shop/products/shoe-example.png"/>
</router-link>


问:
Greater of two columns of a groupby object in a pandas dataframe
I have a dataframe like so (minimum reproducible example):

```<code> Search_Term  Exit_Pages      Ratio_x Date_x   Ratio_y Date_y
 hello        /store/catalog  .20     8/30/17  .25     7/30/17
 hello        /store/product  .15     8/30/17  .10     7/30/17
 goodbye      /store/search   .35     8/30/17  .20     7/30/17
 goodbye      /store/product  .25     8/30/17  .40     7/30/17
</code>```

What I am attempting to do is to first group by the Search term and for each search term find the Greater of Ratio_x and Ratio_y (all while keeping all the remaining columns in the dataframe). So the output I would like to see is:

```<code>Search_Term   Exit_Pages  Ratio_x   Date_x   Ratio_y  Date_y  Highest_Ratio

 hello        /store/catalog  .20     8/30/17  .25     7/30/17  .25
 hello        /store/product  .15     8/30/17  .10     7/30/17
 goodbye      /store/search   .35     8/30/17  .20     7/30/17
 goodbye      /store/product  .25     8/30/17  .40     7/30/17  .40
</code>```

What I have tried to do is to create a groupby Search_Term and apply a Greater of the two columns function using apply as follows (I was afterwards going to join this dataframe to my original to contain the values above, however the error message prevented me from doing that step):

```<code>def Greater(Merge, maximumA, maximumB):
    a = Merge[maximumA]
    b = Merge[maximumB]
    return max(a,b)

Merger.groupby("Search_Term").apply(Greater, "Ratio_x","Ratio_y")

This gives me the error message: ValueError: The truth value of a Series is
ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

Is there some kind of small modification I can make to make my code work and if so, what would it be? If not, what exactly is the problem and how can I resolve this issue?

答:
Maybe a groupby + transform is what you want?

```<code>df['Highest_Ratio'] = df.groupby('Search_Term')\
            ['Ratio_x', 'Ratio_y'].transform('max').max(1)

df['Highest_Ratio']

0    0.25
1    0.25
2    0.40
3    0.40
Name: Highest_Ratio, dtype: float64
</code>```

You can perform one more step with np.where to get your exact output:

```<code>m = df['Highest_Ratio'].eq(df['Ratio_x']) | df['Highest_Ratio'].eq(df['Ratio_y'])
df['Highest_Ratio'] = np.where(m, df['Highest_Ratio'], '')

df

  Search_Term      Exit_Pages  Ratio_x   Date_x  Ratio_y   Date_y  \
0       hello  /store/catalog     0.20  8/30/17     0.25  7/30/17
1       hello  /store/product     0.15  8/30/17     0.10  7/30/17
2     goodbye   /store/search     0.35  8/30/17     0.20  7/30/17
3     goodbye  /store/product     0.25  8/30/17     0.40  7/30/17

  Highest_Ratio
0          0.25
1
2
3           0.4
</code>```

Keep in mind it's better to skip this step, since mixing strings and floats isn't the best idea in terms of performance.

Body:
I have a dataframe like so (minimum reproducible example):

 Search_Term  Exit_Pages      Ratio_x Date_x   Ratio_y Date_y
 hello        /store/catalog  .20     8/30/17  .25     7/30/17
 hello        /store/product  .15     8/30/17  .10     7/30/17
 goodbye      /store/search   .35     8/30/17  .20     7/30/17
 goodbye      /store/product  .25     8/30/17  .40     7/30/17

What I am attempting to do is to first group by the Search term and for each search term find the Greater of Ratio_x and Ratio_y (all while keeping all the remaining columns in the dataframe). So the output I would like to see is:

Search_Term   Exit_Pages  Ratio_x   Date_x   Ratio_y  Date_y  Highest_Ratio

 hello        /store/catalog  .20     8/30/17  .25     7/30/17  .25
 hello        /store/product  .15     8/30/17  .10     7/30/17
 goodbye      /store/search   .35     8/30/17  .20     7/30/17
 goodbye      /store/product  .25     8/30/17  .40     7/30/17  .40

What I have tried to do is to create a groupby Search_Term and apply a Greater of the two columns function using apply as follows (I was afterwards going to join this dataframe to my original to contain the values above, however the error message prevented me from doing that step):

def Greater(Merge, maximumA, maximumB):
    a = Merge[maximumA]
    b = Merge[maximumB]
    return max(a,b)

Merger.groupby("Search_Term").apply(Greater, "Ratio_x","Ratio_y")

This gives me the error message: ValueError: The truth value of a Series is
ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Is there some kind of small modification I can make to make my code work and if so, what would it be? If not, what exactly is the problem and how can I resolve this issue?

Body:
Maybe a groupby + transform is what you want?

df['Highest_Ratio'] = df.groupby('Search_Term')\
            ['Ratio_x', 'Ratio_y'].transform('max').max(1)

df['Highest_Ratio']

0    0.25
1    0.25
2    0.40
3    0.40
Name: Highest_Ratio, dtype: float64

You can perform one more step with np.where to get your exact output:

m = df['Highest_Ratio'].eq(df['Ratio_x']) | df['Highest_Ratio'].eq(df['Ratio_y'])
df['Highest_Ratio'] = np.where(m, df['Highest_Ratio'], '')

df

  Search_Term      Exit_Pages  Ratio_x   Date_x  Ratio_y   Date_y  \
0       hello  /store/catalog     0.20  8/30/17     0.25  7/30/17
1       hello  /store/product     0.15  8/30/17     0.10  7/30/17
2     goodbye   /store/search     0.35  8/30/17     0.20  7/30/17
3     goodbye  /store/product     0.25  8/30/17     0.40  7/30/17

  Highest_Ratio
0          0.25
1
2
3           0.4

Keep in mind it's better to skip this step, since mixing strings and floats isn't the best idea in terms of performance.


问:
problem signed char c++
This is the code:

```<code>int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1);
 }
}
</code>```

Why does this code work when I do or with 0X0A and not with 0xA0, as a number 0xA0 is to big to fit a signed char but why am I not allowed to set the bits for 0xA0?

When I print the loop it never breaks and it only print ones? How come?

答:
Your implementation must add a 1 in the most significant bit when right-shifting a negative number (the operator's behaviour is implementation defined, so usually depends on which CPU instructions are available).

```<code>0xA0 = 1010 0000 binary
</code>```

The first time you sample c & 1 - the least significant bit - it's actually a 0.  Then...

```<code>c = (c >> 1)
</code>```

...shifts this to 1101 0000, then 1110 1000, 1111 0111, 1111 1011, 1111 1101, 1111 1110, 1111 1111 - which is then stable and never changes further.  Hence, you keep printing 1s and never satisfy the termination condition of c == 0.

When I print the loop it never breaks and it only print ones? How come?

Well, it will have printed a few 0s at the very start, but your screen's probably scrolled past them in a blink and thereafter you only see the 1s.

Title: problem signed char c++

Body:
This is the code:

int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1);
 }
}

Why does this code work when I do or with 0X0A and not with 0xA0, as a number 0xA0 is to big to fit a signed char but why am I not allowed to set the bits for 0xA0?

When I print the loop it never breaks and it only print ones? How come?

Body:
Your implementation must add a 1 in the most significant bit when right-shifting a negative number (the operator's behaviour is implementation defined, so usually depends on which CPU instructions are available).

0xA0 = 1010 0000 binary

The first time you sample c & 1 - the least significant bit - it's actually a 0.  Then...

c = (c >> 1)

...shifts this to 1101 0000, then 1110 1000, 1111 0111, 1111 1011, 1111 1101, 1111 1110, 1111 1111 - which is then stable and never changes further.  Hence, you keep printing 1s and never satisfy the termination condition of c == 0.

When I print the loop it never breaks and it only print ones? How come?

Well, it will have printed a few 0s at the very start, but your screen's probably scrolled past them in a blink and thereafter you only see the 1s.


问:
Add column to the right jQuery table
I have this code that I tried so far but it is not giving me the results that I want.

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;//=$('.optionsForm tr:first').html();
    trow='
Class
sdfg

sdfg

sdfg

sdfg

';
    $('.optionsForm ').append(trow);
  });
});```
<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>
<body>

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body></code>```

When I click the button the colon is added just fine the th and other td but I want all this to be added to the right side something like this

```<code>Name    Class
sdg     sdg
sdfg    sdfg
sdgds   sdfgds
</code>```

and not like this :

```<code>Name
sdg
sdfg
sdgds

Class
sdfg
sdfg
sdfg
sdfg
</code>```

Can someone please give me a little help with this.

答:
It's because you append whole html
Class
sdfg

sdfg

sdfg

sdfg

. You should append each th/td separately in thid tr you want. for example

```<code>$('.optionsForm tr:eq(0)').append('<th>Class</th>');
$('.optionsForm tr:eq(1)').append('<td>sdfg</td>');
</code>```

$(document).ready(function(){
  $(".get_attr").click(function (){
    $('.optionsForm tr:eq(0)').append('Class	');
    $('.optionsForm tr:eq(1)').append('sdfg	');
    $('.optionsForm tr:eq(2)').append('sdfg	');
    $('.optionsForm tr:eq(3)').append('sdfg	');
  });
});```
<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>
<body>

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body></code>```

Title: Add column to the right jQuery table

Body:
I have this code that I tried so far but it is not giving me the results that I want.

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;//=$('.optionsForm tr:first').html();
    trow='
Class
sdfg

sdfg

sdfg

sdfg

';
    $('.optionsForm ').append(trow);
  });
});

Name

sdg

sdfg

sdgds

  <button type="button" data-id="5" class="get_attr" >Click Me</button>

When I click the button the colon is added just fine the th and other td but I want all this to be added to the right side something like this

Name    Class
sdg     sdg
sdfg    sdfg
sdgds   sdfgds

and not like this :

Name
sdg
sdfg
sdgds

Class
sdfg
sdfg
sdfg
sdfg

Can someone please give me a little help with this.

Body:
It's because you append whole html <tr><th>Class</th><tr><td>sdfg</td></tr><tr><td>sdfg</td></tr><tr><td>sdfg</td></tr><tr><td>sdfg</td></tr></tr>. You should append each th/td separately in thid tr you want. for example

$('.optionsForm tr:eq(0)').append('<th>Class</th>');
$('.optionsForm tr:eq(1)').append('<td>sdfg</td>');

$(document).ready(function(){
  $(".get_attr").click(function (){
    $('.optionsForm tr:eq(0)').append('<th>Class</th>');
    $('.optionsForm tr:eq(1)').append('<td>sdfg</td>');
    $('.optionsForm tr:eq(2)').append('<td>sdfg</td>');
    $('.optionsForm tr:eq(3)').append('<td>sdfg</td>');
  });
});

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

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body>


问:
CSS - Apply conditional style to table row
I have a requirement where i have to apply conditional style for my table rows but the style never gets applied.

.test1 {
  background-color: '#ffbf00';
}
.test2 {
  background-color: '#92D050';
}
.test3 {
  background-color: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
  <tr styleClass="test1">
    <td></td>
    <td></td>
  </tr>
</table></code>```

But the styling will never be applied. something i am missing?

答:
target to td

```<code>.test1 td
    {
        background-color: #ffbf00;
    }
    .test2 td
    {
        background-color: #92D050;
    }
    .test3 td
    {
        background-color: none;
    }
</code>```

Body:
I have a requirement where i have to apply conditional style for my table rows but the style never gets applied.

.test1 {
  background-color: '#ffbf00';
}
.test2 {
  background-color: '#92D050';
}
.test3 {
  background-color: ' ';
}

But the styling will never be applied. something i am missing?

Body:
target to td

.test1 td
    {
        background-color: #ffbf00;
    }
    .test2 td
    {
        background-color: #92D050;
    }
    .test3 td
    {
        background-color: none;
    }


答:
You can try to increase the specificity number of the selector by using the following selector;

```<code>var peso_totale_componenti = $("table tfoot tr th input#peso_totale_componenti").val();
alert(peso_totale_componenti);
</code>```

Other elements may have the same id in the dom

Title: Datatables and retrieve a value of input field from footer

Body:
You can try to increase the specificity number of the selector by using the following selector;

var peso_totale_componenti = $("table tfoot tr th input#peso_totale_componenti").val();
alert(peso_totale_componenti);

Other elements may have the same id in the dom


问:
django can't visit "models class object" object
My English is poor,maybe my descriptions were have many grammar wrong.

My Pycharm told me a error.Pycharm can not let me visit models class object object.

But,The code can run.I very confuse.Thanks everybody

This is view.py

This is models.py

The code can run,and I use Python3.6 and Django 1.11.7.Pycharm version is 2017.4 pro

答:
Your queries looks ok. The warning from PyCharm about objects is a limitation of PyCharm, you can ignore it.

Note that the recommended approach in Django is to name your models Problem and ProblemAddr, to match the PEP8 style guide.


问:
Regular Express to filter base on character until end
I would like to use regex to get some data from my existing html , my html is as below

```<code><h2 style="text-align: center;"><strong>Title/strong></h2>
<h1 style="text-align: center;">Latest Update : 11-12-209</h1>
<h1 style="text-align: center;"><strong>Comics</strong></h1>

<hr />

<a href="" alt="" width="300" height="169" class="" /></a>

<strong>Ttile: Book1</strong>
<strong>ISBN : 1234567ND</strong>

<hr />
<a href="" src="" alt="" width="200" height="300" /></a> <a href=""><img class="" src="" alt="" width="300" height="225" /></a>

   <strong>Ttile: Book2</strong>
<strong>ISBN : 12345678ND</strong>

<hr />
</code>```

My Expected data would be from the first
 to the last
 ,

I try regex ^ to last
.

What is the correct regex that allow me to get my expected result

答:
Here is a working example:

var html = '
Title/strong>
\

Latest Update : 11-12-209
\

Comics
\

\
\
Ttile: Book1\
ISBN : 1234567ND\

\
 \
Ttile: Book2\
ISBN : 12345678ND\

';

console.log( html.match(/
(.*)
/i)[1] );```

Body:
I would like to use regex to get some data from my existing html , my html is as below

Title/strong>

Latest Update : 11-12-209

Comics

Ttile: Book1
ISBN : 1234567ND

   Ttile: Book2
ISBN : 12345678ND

My Expected data would be from the first
 to the last
 ,

I try regex ^ to last
.

What is the correct regex that allow me to get my expected result

Body:
Here is a working example:

var html = '<h2 style="text-align: center;"><strong>Title/strong></h2>\
<h1 style="text-align: center;">Latest Update : 11-12-209</h1>\
<h1 style="text-align: center;"><strong>Comics</strong></h1>\
<hr />\
<a href="" alt="" width="300" height="169" class="" /></a>\
<strong>Ttile: Book1</strong>\
<strong>ISBN : 1234567ND</strong>\
<hr />\
<a href="" src="" alt="" width="200" height="300" /></a> <a href=""><img class="" src="" alt="" width="300" height="225" /></a>\
<strong>Ttile: Book2</strong>\
<strong>ISBN : 12345678ND</strong>\
<hr />';

console.log( html.match(/<hr \/>(.*)<hr \/>/i)[1] );


问:
Qt QML Singleton Intellisense
Qt QML, they do work, but no intellisense in QML references. Can I achieve intellisense?

```<code>pragma Singleton
import QtQuick 2.0
import QtQuick.Window 2.3

Item {
    property int iMode: 0
    property bool bSwapLeftRight: false
</code>```

Registering it:

```<code>qmlRegisterSingletonType(QUrl(QLatin1String("qrc:/GlobalSettings.qml")), "ncs.global", 1, 0, "SingletonSettings" );
</code>```

Second example;:

```<code>ctxt->setContextProperty("someModel", QVariant::fromValue(ownModel));
ctxt->setContextProperty("globalControl", QVariant::fromValue(globalControl.Get()));
</code>```

First one i achieve IntelliSense in QML whilst using, the second one is the singleton, I do not achieve IntelliSense. Planning to expose some c++ defined enums to QML through this one, but looses value when no IntelliSense is provided..

Question is basically, do Qt Quick and Creator support IntelliSense for singleton classes ? Worthwhile investigating further?

Adding some more details, main question is NOT about enum's, but IntelliSense (auto-complete):

```<code>A few snippets:

main.cpp:
    //Regular Pointer
        SomeModel* ownModel = new SomeModel();
    //Custom Singleton implementation
        GlobalControlSP globalControl = GlobalControl::GetInstance();

    //I did not really want this line. GlobalControl should be singleton, how would this be threated?
        qmlRegisterType<GlobalControl>("ncs.global", 1, 0, "Global");

    //Registering a "Pragma Singleton" file, Intellisense do not work
        qmlRegisterSingletonType(QUrl(QLatin1String("qrc:/GlobalSettings.qml")), "ncs.global", 1, 0, "SingletonSettings" );

        QQmlApplicationEngine engine;
        QQmlContext* ctxt = engine.rootContext();

    //Regular context property, not singleton. Intellisense works
        ctxt->setContextProperty("ownModel", QVariant::fromValue(ownModel));

    //Registering the singleton as context property, Intellisense do not work
        ctxt->setContextProperty("globalControl", QVariant::fromValue(globalControl.Get()));

        engine.load(QUrl(QLatin1String("qrc:/main.qml")));

globalcontrol.h:
class GlobalControl : public QObject,
{
    Q_OBJECT
    Q_PROPERTY(QString backcolor READ backcolor NOTIFY backcolorChanged)
    ....

public:
    GlobalControl(QObject *parent = nullptr);
    QString backcolor() const { return m_backColor; }
    ....
    enum EnButton
    {
        DEVICE_START,
        DEVICE_IR,
        .....
    };
    Q_ENUM(EnButton)

public slots:
    void changeMode(int mode);
    void buttonPressed(int button);

some qml file:

//This implementation works:
    NcsButton {
        property int valuent
        id:ir
        text: qsTr("IR")
        width: 66 * widthScaling
        Layout.row: 4
        Layout.column: 1
        fontColor: bIr ? valueColor : textColor
        onClicked: {
            globalControl.buttonPressed(Global.DEVICE_IR)

//This does not work:
    NcsButton {
        id:ir
        text: qsTr("IR")
        width: 66 * widthScaling
        Layout.row: 4
        Layout.column: 1
        fontColor: bIr ? valueColor : textColor
        onClicked: {
            globalControl.buttonPressed(globalControl.DEVICE_IR)
</code>```

答:
Solution or workaround:

For QML defined singleton, add to Qt compiler QML library a generated file

```<code>..\..\..\bin\qmlplugindump -relocatable ncs.global 1.0 > plugins.qmltypes
</code>```

For c++ registered singleton, make a "fake" pointer of normal class type. Register. To retrieve the enum from same singleton class, create a UncreatableType:

```<code>    GlobalControlSP globalControlOrig = GlobalControl::GetInstance();
    GlobalControl* globalControl = globalControlOrig.Get();
    ctxt->setContextProperty("globalControl", QVariant::fromValue(globalControl));
    qmlRegisterUncreatableType<GlobalControl>("ncs.global", 1, 0, "Global", "Singleton");
</code>```

Title: Qt QML Singleton Intellisense

Body:
Qt QML, they do work, but no intellisense in QML references. Can I achieve intellisense?

pragma Singleton
import QtQuick 2.0
import QtQuick.Window 2.3

Item {
    property int iMode: 0
    property bool bSwapLeftRight: false

Registering it:

qmlRegisterSingletonType(QUrl(QLatin1String("qrc:/GlobalSettings.qml")), "ncs.global", 1, 0, "SingletonSettings" );

Second example;:

ctxt->setContextProperty("someModel", QVariant::fromValue(ownModel));
ctxt->setContextProperty("globalControl", QVariant::fromValue(globalControl.Get()));

First one i achieve IntelliSense in QML whilst using, the second one is the singleton, I do not achieve IntelliSense. Planning to expose some c++ defined enums to QML through this one, but looses value when no IntelliSense is provided..

Question is basically, do Qt Quick and Creator support IntelliSense for singleton classes ? Worthwhile investigating further?

Adding some more details, main question is NOT about enum's, but IntelliSense (auto-complete):

A few snippets:

main.cpp:
    //Regular Pointer
        SomeModel* ownModel = new SomeModel();
    //Custom Singleton implementation
        GlobalControlSP globalControl = GlobalControl::GetInstance();

    //I did not really want this line. GlobalControl should be singleton, how would this be threated?
        qmlRegisterType<GlobalControl>("ncs.global", 1, 0, "Global");

    //Registering a "Pragma Singleton" file, Intellisense do not work
        qmlRegisterSingletonType(QUrl(QLatin1String("qrc:/GlobalSettings.qml")), "ncs.global", 1, 0, "SingletonSettings" );

        QQmlApplicationEngine engine;
        QQmlContext* ctxt = engine.rootContext();

    //Regular context property, not singleton. Intellisense works
        ctxt->setContextProperty("ownModel", QVariant::fromValue(ownModel));

    //Registering the singleton as context property, Intellisense do not work
        ctxt->setContextProperty("globalControl", QVariant::fromValue(globalControl.Get()));

        engine.load(QUrl(QLatin1String("qrc:/main.qml")));

globalcontrol.h:
class GlobalControl : public QObject,
{
    Q_OBJECT
    Q_PROPERTY(QString backcolor READ backcolor NOTIFY backcolorChanged)
    ....

public:
    GlobalControl(QObject *parent = nullptr);
    QString backcolor() const { return m_backColor; }
    ....
    enum EnButton
    {
        DEVICE_START,
        DEVICE_IR,
        .....
    };
    Q_ENUM(EnButton)

public slots:
    void changeMode(int mode);
    void buttonPressed(int button);

some qml file:

//This implementation works:
    NcsButton {
        property int valuent
        id:ir
        text: qsTr("IR")
        width: 66 * widthScaling
        Layout.row: 4
        Layout.column: 1
        fontColor: bIr ? valueColor : textColor
        onClicked: {
            globalControl.buttonPressed(Global.DEVICE_IR)

//This does not work:
    NcsButton {
        id:ir
        text: qsTr("IR")
        width: 66 * widthScaling
        Layout.row: 4
        Layout.column: 1
        fontColor: bIr ? valueColor : textColor
        onClicked: {
            globalControl.buttonPressed(globalControl.DEVICE_IR)

Body:
Solution or workaround:

For QML defined singleton, add to Qt compiler QML library a generated file

..\..\..\bin\qmlplugindump -relocatable ncs.global 1.0 > plugins.qmltypes

For c++ registered singleton, make a "fake" pointer of normal class type. Register. To retrieve the enum from same singleton class, create a UncreatableType:

    GlobalControlSP globalControlOrig = GlobalControl::GetInstance();
    GlobalControl* globalControl = globalControlOrig.Get();
    ctxt->setContextProperty("globalControl", QVariant::fromValue(globalControl));
    qmlRegisterUncreatableType<GlobalControl>("ncs.global", 1, 0, "Global", "Singleton");


问:
GCC refuses list initialisation of parameter
I have the following code:

```<code>#include <initializer_list>
#include <utility>

enum class Classification
{
  Unspecified,
  Primary,
  Secondary
};

class ClassificationMap
{
public:
  ClassificationMap(std::initializer_list<std::pair<const Classification, int>> content = {});
};

void foo(ClassificationMap) {}

int main()
{
    foo({{Classification::Unspecified, 42}});
}
</code>```

Visual Studio 2013 & 2017 and Clang 3.4.1 (and above) both compile the code just fine. From my POV, it should be fine as well. However, GCC 5.1 refuses to compile it, with the following error:

```<code><source>: In function 'int main()':
<source>:22:44: error: could not convert '{{Unspecified, 42}}' from '<brace-enclosed initializer list>' to 'ClassificationMap'
     foo({{Classification::Unspecified, 42}});
</code>```

[Live example]

(I am passing the correct standard flag (-std=c++11) to both GCC and Clang).

Is there a problem in my code, or is this actually a GCC bug?

Supplemental info: in my real code, the initialiser list is used to initialise an unordered map member of the ClassificationMap class (that's why its type is what it is). I need the code to work in VS2013 & GCC 5.1

答:
Here is a good workaround for the issue (abandon default value):

```<code>class ClassificationMap
{
public:
    ClassificationMap(std::initializer_list<std::pair<const Classification, int>> content);
    ClassificationMap() : ClassificationMap({}) {}

};
</code>```

You will have exact behavior you want and it compiles everywhere.

https://godbolt.org/g/WUuMzP

Body:
I have the following code:

#include <initializer_list>
#include <utility>

enum class Classification
{
  Unspecified,
  Primary,
  Secondary
};

class ClassificationMap
{
public:
  ClassificationMap(std::initializer_list<std::pair<const Classification, int>> content = {});
};

void foo(ClassificationMap) {}

int main()
{
    foo({{Classification::Unspecified, 42}});
}

Visual Studio 2013 & 2017 and Clang 3.4.1 (and above) both compile the code just fine. From my POV, it should be fine as well. However, GCC 5.1 refuses to compile it, with the following error:

<source>: In function 'int main()':
<source>:22:44: error: could not convert '{{Unspecified, 42}}' from '<brace-enclosed initializer list>' to 'ClassificationMap'
     foo({{Classification::Unspecified, 42}});

[Live example]

(I am passing the correct standard flag (-std=c++11) to both GCC and Clang).

Is there a problem in my code, or is this actually a GCC bug?

Supplemental info: in my real code, the initialiser list is used to initialise an unordered map member of the ClassificationMap class (that's why its type is what it is). I need the code to work in VS2013 & GCC 5.1

Body:
Here is a good workaround for the issue (abandon default value):

class ClassificationMap
{
public:
    ClassificationMap(std::initializer_list<std::pair<const Classification, int>> content);
    ClassificationMap() : ClassificationMap({}) {}

};

You will have exact behavior you want and it compiles everywhere.

https://godbolt.org/g/WUuMzP


问:
GNU Screen terminal line settings
I want to use GNU screen to monitor to a serial USB port like this:

```<code>$ screen /dev/ttyUSB0 115200
</code>```

But I need to tweak a few terminal line settings. I have made several attempts but none seem to work. For example, to send NL+CR for a newline character, not just NL, the terminal line setting is onlcr.

Attempt 1 - without any special settings:

```<code>$ screen /dev/ttyUSB0 115200
# only sends NL
</code>```

Attempt 2 - via screen:

```<code>$ screen /dev/ttyUSB0 115200,onlcr
# still only sends NL
</code>```

Attempt 3 - via ssty:

```<code>$ stty -F /dev/ttyUSB0 onlcr
$ screen /dev/ttyUSB0 115200
# still only sends NL
</code>```

Attempt 4 - via both:

```<code>$ stty -F /dev/ttyUSB0 onlcr
$ screen /dev/ttyUSB0 115200,onlcr
# still only sends NL
</code>```

Attempt 5 - in the other order:

```<code>$ screen /dev/ttyUSB0 115200,onlcr
# then ctrl+a, ctrl+z to pause the screen session
$ stty -F /dev/ttyUSB0 onlcr
stty: /dev/ttyUSB0: Device or resource busy
</code>```

In all cases, if I run stty to check the terminal line settings I get this:

Before running screen - note the -onlcr is present:

```<code>$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
kill = ^H; min = 100; time = 2;
-icrnl -imaxbel
-opost -onlcr
-isig -icanon -echo
</code>```

Changing the stty setting - note the -onlcr has gone:

```<code>$ stty -F /dev/ttyUSB0 onlcr
$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
kill = ^H; min = 100; time = 2;
-icrnl -imaxbel
-opost
-isig -icanon -echo
</code>```

After running screen - note the -onlcr is back again:

```<code>$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
kill = ^H; min = 100; time = 2;
-icrnl -imaxbel
-opost -onlcr
-isig -icanon -echo
</code>```

It's as if screen ignores any stty settings and resets them to it's own defaults. And this the same on both machines I tested it on; Debain 8.7 and macOS Sierra 10.12.4

I have seen posts with other people facing similar problems but none give a definitive answer. Many people end up recommending an alternative to screen like minicom but now I'm interested.

Can stty settings, like onlcr, be used with screen?

答:
I just went through much the same process, only to find out the screen clobbers the stty settings no matter what.  One comment here suggests changing the screen source code:
How to toggle CR/LF in gnu screen?

In the end, I was very happy to find a more minimal dumb-terminal program that allows passing stty-style arguments on the command line:
https://github.com/npat-efault/picocom

It also pretty-prints the serial port settings when it starts so you can easily check them.

Packages exist in Debian-derived distros (sudo apt-get install picocom), and for others it seems that compilation is straightforward.  One dependency is the linenoise library, which can be disabled.

Title: GNU Screen terminal line settings

Body:
I want to use GNU screen to monitor to a serial USB port like this:

$ screen /dev/ttyUSB0 115200

But I need to tweak a few terminal line settings. I have made several attempts but none seem to work. For example, to send NL+CR for a newline character, not just NL, the terminal line setting is onlcr.

Attempt 1 - without any special settings:

$ screen /dev/ttyUSB0 115200
# only sends NL

Attempt 2 - via screen:

$ screen /dev/ttyUSB0 115200,onlcr
# still only sends NL

Attempt 3 - via ssty:

$ stty -F /dev/ttyUSB0 onlcr
$ screen /dev/ttyUSB0 115200
# still only sends NL

Attempt 4 - via both:

$ stty -F /dev/ttyUSB0 onlcr
$ screen /dev/ttyUSB0 115200,onlcr
# still only sends NL

Attempt 5 - in the other order:

$ screen /dev/ttyUSB0 115200,onlcr
# then ctrl+a, ctrl+z to pause the screen session
$ stty -F /dev/ttyUSB0 onlcr
stty: /dev/ttyUSB0: Device or resource busy

In all cases, if I run stty to check the terminal line settings I get this:

Before running screen - note the -onlcr is present:

$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
kill = ^H; min = 100; time = 2;
-icrnl -imaxbel
-opost -onlcr
-isig -icanon -echo

Changing the stty setting - note the -onlcr has gone:

$ stty -F /dev/ttyUSB0 onlcr
$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
kill = ^H; min = 100; time = 2;
-icrnl -imaxbel
-opost
-isig -icanon -echo

After running screen - note the -onlcr is back again:

$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
kill = ^H; min = 100; time = 2;
-icrnl -imaxbel
-opost -onlcr
-isig -icanon -echo

It's as if screen ignores any stty settings and resets them to it's own defaults. And this the same on both machines I tested it on; Debain 8.7 and macOS Sierra 10.12.4

I have seen posts with other people facing similar problems but none give a definitive answer. Many people end up recommending an alternative to screen like minicom but now I'm interested.

Can stty settings, like onlcr, be used with screen?


问:
Win32 console problem
is it possible to create a program that works as console application if started from the console and works as windows program (with GUI) when started otherwise?

If it is possible - how can I do that?

regards
Tobias

答:
If you need the program to act as a console application (e.g. print the usage information to the console) you must complile as a console application. A windows application will not have access to the console and cmd.exe will not wait for it to finish before printing the prompt and accepting the next command.

The best solution is to have two versions, one for command line and one for the GUI (which users usually run via a link on the desktop or start menu).

If you insist on using a single binary you will have to live with a console window appearing, at least for a short time.   You can get rid of the console window using

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

You can tell that your application was run from GUI if it is the only process attached to the console.  You can use GetConsoleProcessList to find the list of processes attached to the console.

Title: Win32 console problem

Body:
If you need the program to act as a console application (e.g. print the usage information to the console) you must complile as a console application. A windows application will not have access to the console and cmd.exe will not wait for it to finish before printing the prompt and accepting the next command.

The best solution is to have two versions, one for command line and one for the GUI (which users usually run via a link on the desktop or start menu).

If you insist on using a single binary you will have to live with a console window appearing, at least for a short time.   You can get rid of the console window using

FreeConsole();

You can tell that your application was run from GUI if it is the only process attached to the console.  You can use GetConsoleProcessList to find the list of processes attached to the console.


问:
How to restore spinnaker on reboot?
I am at my wits end and have been searching everywhere for a solution to this problem but it seems like I am the only one with it.

I have done multiple different methods of spinnaker installs and have tried multiple versions of it but I cannot seem to restore the state of my spinnaker installation after I reboot the machine. I ssh in

```<code>gcloud compute ssh $HALYARD_HOST     --project=$GCP_PROJECT     -- -L 9000:localhost:9000 -L 8084:localhost:8084
</code>```

I then redirect my browser to the spinnaker UI

```<code>http://localhost:9000
</code>```

But I get the following showing up on the ssh terminal:

```<code>channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 6: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
</code>```

It just continues like that as long as I keep the gui open which just sits at the following screen:

It sometimes lets me proceed past this point, but then the UI is completely useless. Clicking on different menu options just shows a massive spinner which doesn't go anywhere and everything I did before the reboot is now gone.

I have tried the prebaked system provided by google 1-click deploy. I have also tried both the spinnaker computer and container codelabs provided by spinnaker. I have searched a whole host of github questions but no one seems to be running into this problem.

答:
TL;DR; On Google's kubernetes environment install and configure halyard as root and install your spinnaker instance to the cluster and not the halyard VM.

So I figured out the issue. I did not notice that the gcloud ssh command creates a new user on login when I changed workstations. My users at all of my different machines have different usernames (Windows, Linux, Mac, home, office environments)

Secondly, I completed the installation by installing spinnaker directly to the kubernetes cluster from the halyard VM. The halyard installation and configuration I conducted as root.

After trawling a whole log of GitHub questions and answers I noticed that my spinnaker installation was done by the initial user that I logged into the machine as and often I would end up reconnecting to the instance as a different user and end up crying as to why nothing was suddenly working.

Title: How to restore spinnaker on reboot?

Body:
I am at my wits end and have been searching everywhere for a solution to this problem but it seems like I am the only one with it.

I have done multiple different methods of spinnaker installs and have tried multiple versions of it but I cannot seem to restore the state of my spinnaker installation after I reboot the machine. I ssh in

gcloud compute ssh $HALYARD_HOST     --project=$GCP_PROJECT     -- -L 9000:localhost:9000 -L 8084:localhost:8084

I then redirect my browser to the spinnaker UI

http://localhost:9000

But I get the following showing up on the ssh terminal:

channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 6: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused

It just continues like that as long as I keep the gui open which just sits at the following screen:

It sometimes lets me proceed past this point, but then the UI is completely useless. Clicking on different menu options just shows a massive spinner which doesn't go anywhere and everything I did before the reboot is now gone.

I have tried the prebaked system provided by google 1-click deploy. I have also tried both the spinnaker computer and container codelabs provided by spinnaker. I have searched a whole host of github questions but no one seems to be running into this problem.


问:
Merge XML nodes into one comma separated node
I have an XML structure and I'd like to transform this with XSLT. However, it's important to make this as dynamic as possible. I believe it's possible to make a copy of the feed, and then just select a specific section and transform this. When a new node is added to the original XML, no changed should be necessary in the XSLT to have this new node included in the output of the XSLT.

Example of original XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <option>
          <value_local>Verguld</value_local>
          <value_en>Gold-plated</value_en>
          <slug_value>1750-verguld</slug_value>
        </option>
        <option>
          <value_local>Zilver</value_local>
          <value_en>Silver</value_en>
          <slug_value>1751-silver</slug_value>
        </option>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>
</code>```

Desired output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <value_local>Verguld,Silver</value_local>
        <value_en>Gold-plated,Silver</value_en>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>
</code>```

I came across a SO question that pretty much does what I'm aiming for, but I need to define the complete XML structure in this XSLT. As we might add other XML nodes in a later stage and this XSLT will be used in various places, I want to make this as low maintenance as possible.

I think this SO question shows a low maintenance version but frankly I'm not able to understand how the second xsl:template works.

All help is much appreciated. If XSLT is provided, I'd appreciate it if you could include some comments of what you're doing where.

答:
I would try copying everything except for the option element.  Iterate through option elements and group on the items you need to merge.  For example:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xsl:param name="pGroupElems" as="xs:string *" select="'value_local', 'value_en'" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="case_material">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
            <xsl:for-each-group select="option/*" group-by="local-name()[ . = $pGroupElems]">
                <xsl:copy>
                    <xsl:sequence select="string-join(current-group(), ',')" />
                </xsl:copy>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="option" />

</xsl:stylesheet>
</code>```

Body:
I have an XML structure and I'd like to transform this with XSLT. However, it's important to make this as dynamic as possible. I believe it's possible to make a copy of the feed, and then just select a specific section and transform this. When a new node is added to the original XML, no changed should be necessary in the XSLT to have this new node included in the output of the XSLT.

Example of original XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <option>
          <value_local>Verguld</value_local>
          <value_en>Gold-plated</value_en>
          <slug_value>1750-verguld</slug_value>
        </option>
        <option>
          <value_local>Zilver</value_local>
          <value_en>Silver</value_en>
          <slug_value>1751-silver</slug_value>
        </option>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>

Desired output:

<?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <value_local>Verguld,Silver</value_local>
        <value_en>Gold-plated,Silver</value_en>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>

I came across a SO question that pretty much does what I'm aiming for, but I need to define the complete XML structure in this XSLT. As we might add other XML nodes in a later stage and this XSLT will be used in various places, I want to make this as low maintenance as possible.

I think this SO question shows a low maintenance version but frankly I'm not able to understand how the second xsl:template works.

All help is much appreciated. If XSLT is provided, I'd appreciate it if you could include some comments of what you're doing where.

Body:
I would try copying everything except for the option element.  Iterate through option elements and group on the items you need to merge.  For example:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xsl:param name="pGroupElems" as="xs:string *" select="'value_local', 'value_en'" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="case_material">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
            <xsl:for-each-group select="option/*" group-by="local-name()[ . = $pGroupElems]">
                <xsl:copy>
                    <xsl:sequence select="string-join(current-group(), ',')" />
                </xsl:copy>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="option" />

</xsl:stylesheet>


问:
Conversion XML => JSON => XML based on a XSD Schema
I saw lots of threads on this topic but not one with an answer.
Is there actually a JAVA library which can make a conversion XML => JSON => XML using an XSD Schema to better handle the problematic of single element in XML.

(a single element in XML can be an array or a single object depending of the XSD schema)

Example for XML :

```<code>    <root><person><name>test</name></person></root>
</code>```

JSON can be :

```<code>    {"root": [{"person": [{"name": "test"}]}]}
</code>```

or anything with object instead of array :

```<code>    {"root": {"person": {"name": "test"}}}
</code>```

But with XSD we would know from the maxoccurs parameters that root is unique, person is an array and name is unique, so the good transformation would be :

```<code>    {"root": {"person":
        [{"name": "foofdo"}]
    }}
</code>```

Thx in advance

答:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

```<code>import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/root/person")
        .attribute("name")
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}
</code>```

It will return a Jackson ObjectNode, with the following json:

```<code>{"name":"test"}
</code>```

Array Example

Alternativly if you have multiple person, you can have it return a Jackson ArrayNode

```<code>import com.fasterxml.jackson.databind.node.ArrayNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ArrayNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ArrayNode> parser = parsing.arr("/root/person")
        .attribute("name")
        .build();

    ArrayNode result = parser.apply(document);
    return result;
  }
}
</code>```

This will create the following json for your input:

```<code>[{"name":"test"}]
</code>```

Body:
I saw lots of threads on this topic but not one with an answer.
Is there actually a JAVA library which can make a conversion XML => JSON => XML using an XSD Schema to better handle the problematic of single element in XML.

(a single element in XML can be an array or a single object depending of the XSD schema)

Example for XML :

    <root><person><name>test</name></person></root>

JSON can be :

    {"root": [{"person": [{"name": "test"}]}]}

or anything with object instead of array :

    {"root": {"person": {"name": "test"}}}

But with XSD we would know from the maxoccurs parameters that root is unique, person is an array and name is unique, so the good transformation would be :

    {"root": {"person":
        [{"name": "foofdo"}]
    }}

Thx in advance

Body:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/root/person")
        .attribute("name")
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}

It will return a Jackson ObjectNode, with the following json:

{"name":"test"}

Array Example

Alternativly if you have multiple person, you can have it return a Jackson ArrayNode

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ArrayNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ArrayNode> parser = parsing.arr("/root/person")
        .attribute("name")
        .build();

    ArrayNode result = parser.apply(document);
    return result;
  }
}

This will create the following json for your input:

[{"name":"test"}]


问:
How can I make a dictionary (dict) from separate lists of keys and values?
I want to combine these:

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
```
<p>Into a single dictionary:</p>
<pre class="lang-py prettyprint-override"><code>{'name': 'Monty', 'age': 42, 'food': 'spam'}
</code>```

答:
you can use this below code:

```<code>dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))
</code>```

But make sure that length of the lists will be same.if length is not same.then zip function turncate the longer one.

OwnerDisplayName: Guido García

ContentLicense: CC BY-SA 4.0

Body:
I want to combine these:

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']

Into a single dictionary:

{'name': 'Monty', 'age': 42, 'food': 'spam'}

LastEditorDisplayName: J.F. Sebastian

Body:
you can use this below code:

dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))

But make sure that length of the lists will be same.if length is not same.then zip function turncate the longer one.


问:
How to call webservice in HTML page using JQuery?
i have WebService that get 2 string and return if they equals

WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/

```<code>[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
     [WebMethod(Description = "Validate the login credentials")]
     public bool Validate(string UserName, string Password)
     {
          if (Password == "test" && UserName == "test")
              return true;
          else
              return false;
     }
}
</code>```

and i have html page that call this WebService and need to return the Result

```<code><html  lang="en-US">
    <head>
        <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
        <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
        <script type="text/javascript" language="javascript">

        var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";

        $(document).ready(function () {
            $("input#submit").click(function (event) {
                //var uid = document.getElementById("UserName").value;
                //var pwd = document.getElementById("Password").value;

                var uid = "test";
                var pwd = "test";

                var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";

                $.ajax({
                    ServiceCallID: 1,
                    url: Surl,
                    type: 'POST',
                    data: dataString,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",

                    success: function (result) {
                        returnVal = result.d;
                        alert(returnVal);
                    },

                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        returnVal = '';
                    }
                });
            });
        });

</script>

</head>
    <body >
        <form method=post runat="server">
            <input  type="submit" />Connet to my WS
        </form>
    </body>
</html>
</code>```

this what i get:

and i try this, still same problem....

```<code><script>
    function XX() {
        alert("in");
        $.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
            response; // Here is response
            alert(response);
        });
    }
</script>

</head>
    <body >
         <form method=post runat="server">
            <input  type="submit" onclick="XX();" />Connet to my WS2
         </form>
    </body>
</html>
</code>```

i try with $.get - and same.... Nothing happens....

from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,

but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>

Request format is unrecognized for URL unexpectedly ending in '/Validate'.

I swear to God that for several days I break my head and can not figure out why it does not work

):

thanks,

答:
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)

Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).

```<code><!DOCTYPE html>
<html lang="en-US">
    <head>
        <script type="text/javascript">
            var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";

            function submitMyForm(){
                // Define your datas
                var uid = "test";
                var pwd = "test";
                var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";

                // Create and send the request
                var request = new XMLHttpRequest();
                request.onreadystatechange = function() {
                    // Log with console.log() or alert if you want...
                    console.log('State of my request changed! ');
                    if (XMLHttpRequest.DONE === request.readyState) {
                        console.log(request.responseText);
                    }
                }
                request.open('POST', myUrl, true);
                request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                request.send(data);
            }
        </script>
    </head>
    <body>
        <form>
            <button onclick="submitMyForm()" >Connect to my WS</button>
        </form>
    </body>
</html>
</code>```

I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).

For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.

I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).

Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum

Hope I help you.

Body:
i have WebService that get 2 string and return if they equals

WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
     [WebMethod(Description = "Validate the login credentials")]
     public bool Validate(string UserName, string Password)
     {
          if (Password == "test" && UserName == "test")
              return true;
          else
              return false;
     }
}

and i have html page that call this WebService and need to return the Result

        <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />

        <form method=post runat="server">
            <input  type="submit" />Connet to my WS
        </form>

this what i get:

and i try this, still same problem....

         <form method=post runat="server">
            <input  type="submit" onclick="XX();" />Connet to my WS2
         </form>

i try with $.get - and same.... Nothing happens....

from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,

but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>

Request format is unrecognized for URL unexpectedly ending in '/Validate'.

I swear to God that for several days I break my head and can not figure out why it does not work

):

thanks,

Body:
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)

Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <script type="text/javascript">
            var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";

            function submitMyForm(){
                // Define your datas
                var uid = "test";
                var pwd = "test";
                var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";

                // Create and send the request
                var request = new XMLHttpRequest();
                request.onreadystatechange = function() {
                    // Log with console.log() or alert if you want...
                    console.log('State of my request changed! ');
                    if (XMLHttpRequest.DONE === request.readyState) {
                        console.log(request.responseText);
                    }
                }
                request.open('POST', myUrl, true);
                request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                request.send(data);
            }
        </script>
    </head>
    <body>
        <form>
            <button onclick="submitMyForm()" >Connect to my WS</button>
        </form>
    </body>
</html>

I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).

For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.

I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).

Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum

Hope I help you.


问:
Install a specific version of angular-cli
I changed my laptop from windows 7 to windows 10 and i can't install a specific version of the angular cli.

I tried this:

```<code>npm install -g @angular/cli@4.1.0
</code>```

I also tried:

```<code>npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@4.1.0
</code>```

I consistently get:

```<code>npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli@4.1.0"
npm ERR! node v7.9.0
npm ERR! npm  v4.2.0

npm ERR! Cannot read property 'path' of null
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     D:\Users\ihazan\AppData\Roaming\npm-cache\_logs\2017-11-16T13_04_39_665Z-debug.log
</code>```

Node version: 7.9.0

NPM version: 4.2.0

答:
After some investigation, it's actually a stupid error. Nevertheless sharing it as the error message provided above is not clear at all.

It turns out that there is no angular-cli with version 4.1.0.

Re-running with the right version as follows did the trick:

```<code>npm install -g @angular/cli@1.2.4
</code>```

Body:
I changed my laptop from windows 7 to windows 10 and i can't install a specific version of the angular cli.

I tried this:

npm install -g @angular/cli@4.1.0

I also tried:

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@4.1.0

I consistently get:

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli@4.1.0"
npm ERR! node v7.9.0
npm ERR! npm  v4.2.0

npm ERR! Cannot read property 'path' of null
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     D:\Users\ihazan\AppData\Roaming\npm-cache\_logs\2017-11-16T13_04_39_665Z-debug.log

Node version: 7.9.0

NPM version: 4.2.0

Body:
After some investigation, it's actually a stupid error. Nevertheless sharing it as the error message provided above is not clear at all.

It turns out that there is no angular-cli with version 4.1.0.

Re-running with the right version as follows did the trick:

npm install -g @angular/cli@1.2.4


问:
Unreachable statement in colorAnimation
Before I start, I just want to let you know I'm new to Android programming so this question might actually be a bit silly.

In my mainActivity.java file I've got a tabbed layout using 3 viewPager fragments: fragment1, fragment2, and fragment3.

I want the background color of the window to change smoothly when the second fragment comes in and to do that I've got a valueAnimator from the color animation:

```<code>public class fragment2 extends Fragment {
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmentlayout2, null);

        int colorFrom = getResources().getColor(R.color.white);
        int colorTo = getResources().getColor(R.color.colorFrame2);
        ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
        colorAnimation.setDuration(250); // milliseconds
        colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                getView().findViewById(R.layout.fragmentlayout2).setBackgroundColor((int) animator.getAnimatedValue());

            }

        });
        colorAnimation.start();
    }
}
</code>```

When I try to run the program it returns an unreachable statement error about the colorFrom statement. I've tried solving it but it just won't go away! Any help appreciated!

答:
Move return at the end of onCreateView because return will send back the control and won't go further

```<code> @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        int colorFrom = getResources().getColor(R.color.white);
        int colorTo = getResources().getColor(R.color.colorFrame2);
        ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
        colorAnimation.setDuration(250); // milliseconds
        colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                getView().findViewById(R.layout.fragmentlayout2).setBackgroundColor((int) animator.getAnimatedValue());

            }

        });
        colorAnimation.start();
    return inflater.inflate(R.layout.fragmentlayout2, null);
    // ^^^^^^^^
    }
</code>```

Title: Unreachable statement in colorAnimation

Body:
Before I start, I just want to let you know I'm new to Android programming so this question might actually be a bit silly.

In my mainActivity.java file I've got a tabbed layout using 3 viewPager fragments: fragment1, fragment2, and fragment3.

I want the background color of the window to change smoothly when the second fragment comes in and to do that I've got a valueAnimator from the color animation:

public class fragment2 extends Fragment {
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmentlayout2, null);

        int colorFrom = getResources().getColor(R.color.white);
        int colorTo = getResources().getColor(R.color.colorFrame2);
        ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
        colorAnimation.setDuration(250); // milliseconds
        colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                getView().findViewById(R.layout.fragmentlayout2).setBackgroundColor((int) animator.getAnimatedValue());

            }

        });
        colorAnimation.start();
    }
}

When I try to run the program it returns an unreachable statement error about the colorFrom statement. I've tried solving it but it just won't go away! Any help appreciated!

Body:
Move return at the end of onCreateView because return will send back the control and won't go further

 @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        int colorFrom = getResources().getColor(R.color.white);
        int colorTo = getResources().getColor(R.color.colorFrame2);
        ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
        colorAnimation.setDuration(250); // milliseconds
        colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                getView().findViewById(R.layout.fragmentlayout2).setBackgroundColor((int) animator.getAnimatedValue());

            }

        });
        colorAnimation.start();
    return inflater.inflate(R.layout.fragmentlayout2, null);
    // ^^^^^^^^
    }