问:
FREE TEXT SQL extract from fullname
```<code>Need help with extracting the firstname, middlename and lastname from a
freetext fullname. How to extract them out with all these formats?
Need to figure out how to handle format 2,5,9,7

--fullname sample data
DECLARE @name TABLE
(fullname VARCHAR(100))
INSERT INTO @name SELECT
'Malone,Susan M' UNION ALL SELECT --1
'Conn,Chris G'  UNION ALL SELECT --2
'Van Pess,Wen B' UNION ALL SELECT --3
'DESHPANDE, ANN W.' UNION ALL SELECT --4
'Asif,LEE' UNION ALL SELECT --5
'CERVANTES MANDY'UNION ALL SELECT --6
'Bill, Dave' UNION ALL SELECT --7
'SMITH,ANN M'  UNION ALL SELECT --8
'BHULLER,  MATT'  UNION ALL SELECT  --9
'KIM (DAUM), GAIL' UNION ALL SELECT  --10
'John.Mills'--11

DECLARE @DELIMITER1 varchar(5), @DELIMITER2 varchar(5), @DELIMITER3
varchar(5),@MAX_LENGTH int
SET @DELIMITER1 = ','
SET @DELIMITER2 = ' '
SET @MAX_LENGTH = 50

--LastName
SELECT   fullname,
case when
 CHARINDEX(@DELIMITER2, fullname) >=1
 then replace(SUBSTRING(fullname, 1, CHARINDEX(@DELIMITER2, fullname)
),',','')--replace to empty string if contains a ","
 when
 CHARINDEX(@DELIMITER2, fullname) =0
 then replace(SUBSTRING(fullname, 1, CHARINDEX(@DELIMITER1, fullname)
),',','')--replace to empty string if contains a ","
 else null
 end as Lastname,

--Middle Name
CASE
-- Middle fullname follows two-fullname first fullnames like Mary Ann
   WHEN LEN(SUBSTRING(fullname, CHARINDEX(@DELIMITER1,fullname)+
2,@MAX_LENGTH)) - LEN(REPLACE(SUBSTRING(fullname,
CHARINDEX(@DELIMITER1,fullname)+ 2,@MAX_LENGTH), @DELIMITER2, '')) > 0
--when len is greater than 0
     THEN SUBSTRING(fullname, LEN(fullname) - CHARINDEX(@DELIMITER2,
REVERSE(fullname))+2, @MAX_LENGTH)
        ELSE NULL
END AS Middlefullname,

--First Name
CASE
-- Count the number of @DELIMITER2. Choose the string between the

   WHEN LEN(SUBSTRING(fullname, CHARINDEX(@DELIMITER1,fullname)+
2,@MAX_LENGTH)) - LEN(REPLACE(SUBSTRING(fullname,
CHARINDEX(@DELIMITER1,fullname)+ 2,@MAX_LENGTH), @DELIMITER2, '')) > 0 --
--when len is greater than 0
     Then replace(ltrim(SUBSTRING(fullname, CHARINDEX(@DELIMITER1,fullname)+
1,
---need help here
(LEN(SUBSTRING(fullname, CHARINDEX(@DELIMITER1,fullname)+ 2,@MAX_LENGTH))-
LEN(SUBSTRING(fullname, LEN(fullname) - CHARINDEX(@DELIMITER2,
REVERSE(fullname))+2, @MAX_LENGTH))))),'-','') --replace the "-" to empty
string
        ELSE ltrim(SUBSTRING(fullname,CHARINDEX(@DELIMITER1,fullname)+
    1,@MAX_LENGTH))--trimmed leading spaces
END AS Firstname
FROM @name
order by fullname
</code>```

答:
First logic to concatenate the "name parts" with dots. Note my comments.

```<code>--fullname sample data
DECLARE @name TABLE
(nameid int identity, fullname VARCHAR(100))
INSERT INTO @name SELECT
'Malone,Susan M' UNION ALL SELECT --1
'Conn,Chris G'  UNION ALL SELECT --2
'Van Pess,Wen B' UNION ALL SELECT --3
'DESHPANDE, ANN W.' UNION ALL SELECT --4
'Asif,LEE' UNION ALL SELECT --5
'CERVANTES MANDY'UNION ALL SELECT --6
'Bill, Dave' UNION ALL SELECT --7
'SMITH,ANN M'  UNION ALL SELECT --8
'BHULLER,  MATT'  UNION ALL SELECT  --9
'KIM (DAUM), GAIL' UNION ALL SELECT  --10
'John.Mills';--11

select original = fullname, prepped = dotted.fn, total.spaces
from @name
cross apply (values (patindex('%(%),%',fullname),fullname)) prep1(x,fn) -- check for parentheses:
cross apply (values ( -- remove parentheses if they exist, replace commas w/ dots, dots w/ spaces:
  case
    when prep1.x > 1 then substring(fn,1,x-1) + substring(fn,charindex(',',fn,x)+1,8000)
    else replace(replace(fn, ',', '.'),'.',' ')
  end)) prep(fn)
cross apply (values (replace(rtrim(ltrim(replace(prep.fn,'  ',' '))),'  ',' '))) clean(fn)
cross apply (values (len(clean.fn)-len(replace(clean.fn,' ','')))) total(spaces) -- count spaces
cross apply (values (replace(clean.fn, ' ','.'))) dotted(fn); -- replace spaces with dots
</code>```

This returns

```<code>original                 prepped              spaces
------------------------ -------------------- -------
Malone,Susan M           Malone.Susan.M       2
Conn,Chris G             Conn.Chris.G         2
Van Pess,Wen B           Van.Pess.Wen.B       3
DESHPANDE, ANN W.        DESHPANDE.ANN.W      2
Asif,LEE                 Asif.LEE             1
CERVANTES MANDY          CERVANTES.MANDY      1
Bill, Dave               Bill.Dave            1
SMITH,ANN M              SMITH.ANN.M          2
BHULLER,  MATT           BHULLER.MATT         1
KIM (DAUM), GAIL         KIM.GAIL             1
John.Mills               John.Mills           1
</code>```

The rest can be done using parsename like so:

```<code>--fullname sample data
DECLARE @name TABLE
(nameid int identity, fullname VARCHAR(100))
INSERT INTO @name SELECT
'Malone,Susan M' UNION ALL SELECT --1
'Conn,Chris G'  UNION ALL SELECT --2
'Van Pess,Wen B' UNION ALL SELECT --3
'DESHPANDE, ANN W.' UNION ALL SELECT --4
'Asif,LEE' UNION ALL SELECT --5
'CERVANTES MANDY'UNION ALL SELECT --6
'Bill, Dave' UNION ALL SELECT --7
'SMITH,ANN M'  UNION ALL SELECT --8
'BHULLER,  MATT'  UNION ALL SELECT  --9
'KIM (DAUM), GAIL' UNION ALL SELECT  --10
'John.Mills';--11

with clean as
(
  select original = fullname, prepped = dotted.fn, total.spaces
  from @name
  cross apply (values (patindex('%(%),%',fullname),fullname)) prep1(x,fn) -- check for parentheses:
  cross apply (values ( -- remove parentheses if they exist, replace commas w/ dots, dots w/ spaces:
    case
      when prep1.x > 1 then substring(fn,1,x-1) + substring(fn,charindex(',',fn,x)+1,8000)
      else replace(replace(fn, ',', '.'),'.',' ')
    end)) prep(fn)
  cross apply (values (replace(rtrim(ltrim(replace(prep.fn,'  ',' '))),'  ',' '))) clean(fn)
  cross apply (values (len(clean.fn)-len(replace(clean.fn,' ','')))) total(spaces) -- count spaces
  cross apply (values (replace(clean.fn, ' ','.'))) dotted(fn)
)
select  original, cleaned =
  case spaces
    when 1 then parsename(prepped,1)+' '+parsename(prepped,2)
    when 2 then parsename(prepped,2)+' '+parsename(prepped,1)+' '+parsename(prepped,3)
    when 3 then parsename(prepped,2)+' '+parsename(prepped,1)+' '+parsename(prepped,3)+
            ' '+parsename(prepped,4)
  end
from clean
</code>```

Returns:

```<code>original             cleaned
-------------------- ------------------
Malone,Susan M       Susan M Malone
Conn,Chris G         Chris G Conn
Van Pess,Wen B       Wen B Pess Van
DESHPANDE, ANN W.    ANN W DESHPANDE
Asif,LEE             LEE Asif
CERVANTES MANDY      MANDY CERVANTES
Bill, Dave           Dave Bill
SMITH,ANN M          ANN M SMITH
BHULLER,  MATT       MATT BHULLER
KIM (DAUM), GAIL     GAIL KIM
John.Mills           Mills John
</code>```

Alternatively you can use a regex clr (mdq.regexreplace). Note my post on SSC a few years ago.

Title: FREE TEXT SQL extract from fullname

Body:
First logic to concatenate the "name parts" with dots. Note my comments.

--fullname sample data
DECLARE @name TABLE
(nameid int identity, fullname VARCHAR(100))
INSERT INTO @name SELECT
'Malone,Susan M' UNION ALL SELECT --1
'Conn,Chris G'  UNION ALL SELECT --2
'Van Pess,Wen B' UNION ALL SELECT --3
'DESHPANDE, ANN W.' UNION ALL SELECT --4
'Asif,LEE' UNION ALL SELECT --5
'CERVANTES MANDY'UNION ALL SELECT --6
'Bill, Dave' UNION ALL SELECT --7
'SMITH,ANN M'  UNION ALL SELECT --8
'BHULLER,  MATT'  UNION ALL SELECT  --9
'KIM (DAUM), GAIL' UNION ALL SELECT  --10
'John.Mills';--11

select original = fullname, prepped = dotted.fn, total.spaces
from @name
cross apply (values (patindex('%(%),%',fullname),fullname)) prep1(x,fn) -- check for parentheses:
cross apply (values ( -- remove parentheses if they exist, replace commas w/ dots, dots w/ spaces:
  case
    when prep1.x > 1 then substring(fn,1,x-1) + substring(fn,charindex(',',fn,x)+1,8000)
    else replace(replace(fn, ',', '.'),'.',' ')
  end)) prep(fn)
cross apply (values (replace(rtrim(ltrim(replace(prep.fn,'  ',' '))),'  ',' '))) clean(fn)
cross apply (values (len(clean.fn)-len(replace(clean.fn,' ','')))) total(spaces) -- count spaces
cross apply (values (replace(clean.fn, ' ','.'))) dotted(fn); -- replace spaces with dots

This returns

original                 prepped              spaces
------------------------ -------------------- -------
Malone,Susan M           Malone.Susan.M       2
Conn,Chris G             Conn.Chris.G         2
Van Pess,Wen B           Van.Pess.Wen.B       3
DESHPANDE, ANN W.        DESHPANDE.ANN.W      2
Asif,LEE                 Asif.LEE             1
CERVANTES MANDY          CERVANTES.MANDY      1
Bill, Dave               Bill.Dave            1
SMITH,ANN M              SMITH.ANN.M          2
BHULLER,  MATT           BHULLER.MATT         1
KIM (DAUM), GAIL         KIM.GAIL             1
John.Mills               John.Mills           1

The rest can be done using parsename like so:

--fullname sample data
DECLARE @name TABLE
(nameid int identity, fullname VARCHAR(100))
INSERT INTO @name SELECT
'Malone,Susan M' UNION ALL SELECT --1
'Conn,Chris G'  UNION ALL SELECT --2
'Van Pess,Wen B' UNION ALL SELECT --3
'DESHPANDE, ANN W.' UNION ALL SELECT --4
'Asif,LEE' UNION ALL SELECT --5
'CERVANTES MANDY'UNION ALL SELECT --6
'Bill, Dave' UNION ALL SELECT --7
'SMITH,ANN M'  UNION ALL SELECT --8
'BHULLER,  MATT'  UNION ALL SELECT  --9
'KIM (DAUM), GAIL' UNION ALL SELECT  --10
'John.Mills';--11

with clean as
(
  select original = fullname, prepped = dotted.fn, total.spaces
  from @name
  cross apply (values (patindex('%(%),%',fullname),fullname)) prep1(x,fn) -- check for parentheses:
  cross apply (values ( -- remove parentheses if they exist, replace commas w/ dots, dots w/ spaces:
    case
      when prep1.x > 1 then substring(fn,1,x-1) + substring(fn,charindex(',',fn,x)+1,8000)
      else replace(replace(fn, ',', '.'),'.',' ')
    end)) prep(fn)
  cross apply (values (replace(rtrim(ltrim(replace(prep.fn,'  ',' '))),'  ',' '))) clean(fn)
  cross apply (values (len(clean.fn)-len(replace(clean.fn,' ','')))) total(spaces) -- count spaces
  cross apply (values (replace(clean.fn, ' ','.'))) dotted(fn)
)
select  original, cleaned =
  case spaces
    when 1 then parsename(prepped,1)+' '+parsename(prepped,2)
    when 2 then parsename(prepped,2)+' '+parsename(prepped,1)+' '+parsename(prepped,3)
    when 3 then parsename(prepped,2)+' '+parsename(prepped,1)+' '+parsename(prepped,3)+
            ' '+parsename(prepped,4)
  end
from clean

Returns:

original             cleaned
-------------------- ------------------
Malone,Susan M       Susan M Malone
Conn,Chris G         Chris G Conn
Van Pess,Wen B       Wen B Pess Van
DESHPANDE, ANN W.    ANN W DESHPANDE
Asif,LEE             LEE Asif
CERVANTES MANDY      MANDY CERVANTES
Bill, Dave           Dave Bill
SMITH,ANN M          ANN M SMITH
BHULLER,  MATT       MATT BHULLER
KIM (DAUM), GAIL     GAIL KIM
John.Mills           Mills John

Alternatively you can use a regex clr (mdq.regexreplace). Note my post on SSC a few years ago.


来源: stackexchange

问:
Azure Cosmos DB Implementation Failure
I'm having a problem whenever I try to create a new Cosmos DB database through Azure Portal. I'm using a free subscription so I do not have access to CosmosDB support.

Basically, all values seem to be valid but after creation everything fails. I'm doing the following:

Input a unique ID with no spaces or uppercases or symbols.

Chose "Azure Table" as API type.

Use my "Free Trial" subscription.

Create a new resource group (again with no spaces or uppercases of symbols).

Choose a server in either "South UK" and "North Europe" (tried both on different tries).

Whenever I click finish, after some seconds, I get the following message:

Invalid capability EnableTable. ActivityId: ...

  Microsoft.Azure.Documents.Common/1.10.106.1 (Code: BadRequest)

Error Message:

{
   "code": "BadRequest",
 "message": "Invalid capability
  EnableTable.\r\nActivityId: 9cb0e2eb-3b62-4bda-a0f9-e3945eb8148b,
  Microsoft.Azure.Documents.Common/1.19.106.1"
}

I also tried Edge and Chrome and neither work. I find funny that Microsoft says that we can try Azure's CosmosDB for free but in fact we can't because creation fails and they offer no support for free.

答:
Problem Solved

Not really sure if this can be considered an answer, but my problem has solved itself somehow. Apparently the solution is to keep trying multiple times till it works.

If it helps the only different thing I did this time was:

Create first an Azure Cosmos MongoDB, including creating a new resource group

Create now the Azure Table DB using the existing resource group used by Mongo DB.

It worked.

Not sure if it was this or and Azure error or subscription issue, since I created my account today, so It could not be properly configured.

ContentLicense: CC BY-SA 3.0

Title: Azure Cosmos DB Implementation Failure


问:
Drag on Drop onto a composite User Control with multiple text boxes
I have a user control that contains two text boxes, as well as some other controls. I want to be able to drag/drop a complex type onto this control, and I want the entire control to be a drop target, including the textboxes and space around the composited controls. When the data is dropped, it is split apart into component fields, each represented by the controls in the user control.

The problem I am having is that the textboxes  (if I set AllowDrop to true) are trying to do their own drag drop thing, and will individually accept only the text format of the drop data. If I set AllowDrop to false on the textboxes, the drop is disabled the for the textboxes altogether. I can drag my complex data to labels, checkboxes etc, and it behaves exactly like I expect it should.

In addition the space around the other controls does not seem to be considered a valid drop target.

Any ideas how to make the text boxes behave as the controls (such as the labels, checkbox or combobox), and why the grid is not being considered a valid drop target?

Source for the user control:

```<code><UserControl x:Class="DragDropTester.CompositeControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="226" d:DesignWidth="428" AllowDrop="True">
    <Grid AllowDrop="True">
        <TextBox Height="23" Margin="115,12,12,0" Name="textBox1" VerticalAlignment="Top" AllowDrop="False" />
        <Label Content="TextBox 1:" Height="28" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" Width="97" />
        <TextBox Height="23" Margin="115,41,12,0" Name="textBox2" VerticalAlignment="Top" AllowDrop="False" />
        <Label Content="TextBox 2:" Height="28" HorizontalAlignment="Left" Margin="12,41,0,0" Name="label2" VerticalAlignment="Top" Width="97" />
        <CheckBox Content="CheckBox" Height="16" Margin="115,70,150,0" Name="checkBox1" VerticalAlignment="Top" />
        <ComboBox Height="23" Margin="115,92,12,0" Name="comboBox1" VerticalAlignment="Top" />
    </Grid>
</UserControl>
</code>```

and code behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DragDropTester {
    /// <summary>
    /// Interaction logic for CompositeControl.xaml
    /// </summary>
    public partial class CompositeControl : UserControl {

        public CompositeControl() {
            InitializeComponent();

            PreviewDragEnter += new DragEventHandler(CompositeControl_DragEnter);
            this.PreviewDragOver += new DragEventHandler(CompositeControl_DragEnter);

            Drop += new DragEventHandler(CompositeControl_Drop);
        }

        void CompositeControl_Drop(object sender, DragEventArgs e) {
            var complex = e.Data.GetData("ComplexDragData") as ComplexDragData;
            if (complex != null) {
                this.textBox1.Text = complex.Text1;
                this.textBox2.Text = complex.Text2;
                this.checkBox1.IsChecked = complex.BoolValue;
            }
        }

        void CompositeControl_DragEnter(object sender, DragEventArgs e) {
            var complex = e.Data.GetData("ComplexDragData") as ComplexDragData;
            if (complex != null) {
                e.Effects = DragDropEffects.Link;
            } else {
                e.Effects = DragDropEffects.None;
            }

            e.Handled = true;
        }
    }
}
</code>```

And for the main window that hosts the user control and a drag source...

XAML:

```<code><Window x:Class="DragDropTester.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:DragDropTester"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="40" />
        </Grid.RowDefinitions>
        <src:CompositeControl />
        <Label Content="Drag Source" Grid.Row="1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Margin="5" Background="LightGray" Name="lblDragSource" />
    </Grid>
</Window>
</code>```

C# code behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DragDropTester {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {

        private Point _startPoint;
        private bool _IsDragging;

        public MainWindow() {
            InitializeComponent();

            lblDragSource.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(lblDragSource_PreviewMouseLeftButtonDown);
            lblDragSource.PreviewMouseMove += new MouseEventHandler(lblDragSource_PreviewMouseMove);
        }

        void lblDragSource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
            _startPoint = e.GetPosition(sender as IInputElement);
        }

        void lblDragSource_PreviewMouseMove(object sender, MouseEventArgs e) {

            if (_startPoint == null) {
                return;
            }

            if (e.LeftButton == MouseButtonState.Pressed && !_IsDragging) {
                Point position = e.GetPosition(sender as IInputElement);
                if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance) {
                    StartDrag(sender as DependencyObject);
                }
            }
        }

        private void StartDrag(DependencyObject dragSource) {
            var data = new DataObject();
            var dragData = new ComplexDragData { Text1 = "This is text1", Text2 = "This is text2", BoolValue = true };
            data.SetData("ComplexDragData", dragData);
            data.SetData(DataFormats.Text, dragData.ToString());

            try {
                _IsDragging = true;
                DragDrop.DoDragDrop(dragSource, data, DragDropEffects.Copy | DragDropEffects.Link);
            } finally {
                _IsDragging = false;
            }

        }
    }

    public class ComplexDragData {
        public String Text1 { get; set; }
        public String Text2 { get; set; }
        public bool BoolValue { get; set; }

        public override string ToString() {
            return string.Format("text1: {0} text2: {1} Bool: {2}", Text1, Text2, BoolValue );
        }
    }
}
</code>```

答:
Its looks like I can get the behavior I want by hooking the drag/drop events of the text boxes individually:</p>

```<code>    public CompositeControl() {
        InitializeComponent();

        PreviewDragEnter += new DragEventHandler(CompositeControl_DragEnter);
        PreviewDragOver += new DragEventHandler(CompositeControl_DragEnter);

        textBox1.PreviewDragEnter += new DragEventHandler(textBox_PreviewDragEnter);
        textBox1.PreviewDragOver += new DragEventHandler(textBox_PreviewDragEnter);
        textBox1.PreviewDrop += new DragEventHandler(CompositeControl_Drop);

        textBox2.PreviewDragEnter += new DragEventHandler(textBox_PreviewDragEnter);
        textBox2.PreviewDragOver += new DragEventHandler(textBox_PreviewDragEnter);
        textBox2.PreviewDrop += new DragEventHandler(CompositeControl_Drop);

        Drop += new DragEventHandler(CompositeControl_Drop);
    }

    void textBox_PreviewDragEnter(object sender, DragEventArgs e) {
        e.Handled = true;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a user control that contains two text boxes, as well as some other controls. I want to be able to drag/drop a complex type onto this control, and I want the entire control to be a drop target, including the textboxes and space around the composited controls. When the data is dropped, it is split apart into component fields, each represented by the controls in the user control.

The problem I am having is that the textboxes  (if I set AllowDrop to true) are trying to do their own drag drop thing, and will individually accept only the text format of the drop data. If I set AllowDrop to false on the textboxes, the drop is disabled the for the textboxes altogether. I can drag my complex data to labels, checkboxes etc, and it behaves exactly like I expect it should.

In addition the space around the other controls does not seem to be considered a valid drop target.

Any ideas how to make the text boxes behave as the controls (such as the labels, checkbox or combobox), and why the grid is not being considered a valid drop target?

Source for the user control:

<UserControl x:Class="DragDropTester.CompositeControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="226" d:DesignWidth="428" AllowDrop="True">
    <Grid AllowDrop="True">
        <TextBox Height="23" Margin="115,12,12,0" Name="textBox1" VerticalAlignment="Top" AllowDrop="False" />

        <TextBox Height="23" Margin="115,41,12,0" Name="textBox2" VerticalAlignment="Top" AllowDrop="False" />

        <CheckBox Content="CheckBox" Height="16" Margin="115,70,150,0" Name="checkBox1" VerticalAlignment="Top" />
        <ComboBox Height="23" Margin="115,92,12,0" Name="comboBox1" VerticalAlignment="Top" />
    </Grid>
</UserControl>

and code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DragDropTester {
    ///
    /// Interaction logic for CompositeControl.xaml
    ///
    public partial class CompositeControl : UserControl {

        public CompositeControl() {
            InitializeComponent();

            PreviewDragEnter += new DragEventHandler(CompositeControl_DragEnter);
            this.PreviewDragOver += new DragEventHandler(CompositeControl_DragEnter);

            Drop += new DragEventHandler(CompositeControl_Drop);
        }

        void CompositeControl_Drop(object sender, DragEventArgs e) {
            var complex = e.Data.GetData("ComplexDragData") as ComplexDragData;
            if (complex != null) {
                this.textBox1.Text = complex.Text1;
                this.textBox2.Text = complex.Text2;
                this.checkBox1.IsChecked = complex.BoolValue;
            }
        }

        void CompositeControl_DragEnter(object sender, DragEventArgs e) {
            var complex = e.Data.GetData("ComplexDragData") as ComplexDragData;
            if (complex != null) {
                e.Effects = DragDropEffects.Link;
            } else {
                e.Effects = DragDropEffects.None;
            }

            e.Handled = true;
        }
    }
}

And for the main window that hosts the user control and a drag source...

XAML:

<Window x:Class="DragDropTester.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:DragDropTester"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="40" />
        </Grid.RowDefinitions>
        <src:CompositeControl />

    </Grid>
</Window>

C# code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DragDropTester {
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window {

        private Point _startPoint;
        private bool _IsDragging;

        public MainWindow() {
            InitializeComponent();

            lblDragSource.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(lblDragSource_PreviewMouseLeftButtonDown);
            lblDragSource.PreviewMouseMove += new MouseEventHandler(lblDragSource_PreviewMouseMove);
        }

        void lblDragSource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
            _startPoint = e.GetPosition(sender as IInputElement);
        }

        void lblDragSource_PreviewMouseMove(object sender, MouseEventArgs e) {

            if (_startPoint == null) {
                return;
            }

            if (e.LeftButton == MouseButtonState.Pressed && !_IsDragging) {
                Point position = e.GetPosition(sender as IInputElement);
                if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance) {
                    StartDrag(sender as DependencyObject);
                }
            }
        }

        private void StartDrag(DependencyObject dragSource) {
            var data = new DataObject();
            var dragData = new ComplexDragData { Text1 = "This is text1", Text2 = "This is text2", BoolValue = true };
            data.SetData("ComplexDragData", dragData);
            data.SetData(DataFormats.Text, dragData.ToString());

            try {
                _IsDragging = true;
                DragDrop.DoDragDrop(dragSource, data, DragDropEffects.Copy | DragDropEffects.Link);
            } finally {
                _IsDragging = false;
            }

        }
    }

    public class ComplexDragData {
        public String Text1 { get; set; }
        public String Text2 { get; set; }
        public bool BoolValue { get; set; }

        public override string ToString() {
            return string.Format("text1: {0} text2: {1} Bool: {2}", Text1, Text2, BoolValue );
        }
    }
}

Body:
Its looks like I can get the behavior I want by hooking the drag/drop events of the text boxes individually:

    public CompositeControl() {
        InitializeComponent();

        PreviewDragEnter += new DragEventHandler(CompositeControl_DragEnter);
        PreviewDragOver += new DragEventHandler(CompositeControl_DragEnter);

        textBox1.PreviewDragEnter += new DragEventHandler(textBox_PreviewDragEnter);
        textBox1.PreviewDragOver += new DragEventHandler(textBox_PreviewDragEnter);
        textBox1.PreviewDrop += new DragEventHandler(CompositeControl_Drop);

        textBox2.PreviewDragEnter += new DragEventHandler(textBox_PreviewDragEnter);
        textBox2.PreviewDragOver += new DragEventHandler(textBox_PreviewDragEnter);
        textBox2.PreviewDrop += new DragEventHandler(CompositeControl_Drop);

        Drop += new DragEventHandler(CompositeControl_Drop);
    }

    void textBox_PreviewDragEnter(object sender, DragEventArgs e) {
        e.Handled = true;
    }


问:
Calculating 95% confidence intervals in quantile regression in R using rq function
I would like to get 95% confidence intervals for the regression coefficients of a quantile regression. You can calculate quantile regressions using the rq function of the quantreg package in R (compared to an OLS model):

```<code>library(quantreg)
LM<-lm(mpg~disp, data = mtcars)
QR<-rq(mpg~disp, data = mtcars, tau=0.5)
</code>```

I am able to get 95% confidence intervals for the linear model using the confint function:

```<code>confint(LM)
</code>```

When I use quantile regression I understand that the following code produces bootstrapped standard errors:

```<code>summary.rq(QR,se="boot")
</code>```

But actually I would like something like 95% confidence intervals. That is, something to interprete like: "with a probability of 95%, the interval [...] includes the true coefficient". When I calculate standard errors using summary.lm() I would just multiply SE*1.96 and get similar results as from confint(). But this is not possible using bootstrapped standard errors.
So my question is how get 95% confidence intervals for quantile regression coefficients?

答:
You could also simply retrieve the vcov from the object, setting covariance=TRUE. This amounts to using boostrapped standard errors in your CI:

```<code>vcov.rq <- function(x, se = "iid") {
 vc <- summary.rq(x, se=se, cov=TRUE)$cov
 dimnames(vc) <- list(names(coef(x)), names(coef(x)))
 vc
}

confint(QR)
</code>```

But yes, the better way to do this is to use a studentized bootstrap.

Body:
I would like to get 95% confidence intervals for the regression coefficients of a quantile regression. You can calculate quantile regressions using the rq function of the quantreg package in R (compared to an OLS model):

library(quantreg)
LM<-lm(mpg~disp, data = mtcars)
QR<-rq(mpg~disp, data = mtcars, tau=0.5)

I am able to get 95% confidence intervals for the linear model using the confint function:

confint(LM)

When I use quantile regression I understand that the following code produces bootstrapped standard errors:

summary.rq(QR,se="boot")

But actually I would like something like 95% confidence intervals. That is, something to interprete like: "with a probability of 95%, the interval [...] includes the true coefficient". When I calculate standard errors using summary.lm() I would just multiply SE*1.96 and get similar results as from confint(). But this is not possible using bootstrapped standard errors.
So my question is how get 95% confidence intervals for quantile regression coefficients?

Body:
You could also simply retrieve the vcov from the object, setting covariance=TRUE. This amounts to using boostrapped standard errors in your CI:

vcov.rq <- function(x, se = "iid") {
 vc <- summary.rq(x, se=se, cov=TRUE)$cov
 dimnames(vc) <- list(names(coef(x)), names(coef(x)))
 vc
}

confint(QR)

But yes, the better way to do this is to use a studentized bootstrap.


问:
Creating new worksheet and renaming from a list but also to insert a value from the list to the new worksheet
Hoping for help with something I am working on.
1. I would like to create a vba code that creates new worksheets against a "template worksheet" and rename them based on a separate "List worksheet" that contains a list of serial numbers. I have managed to find a vba code that does this.
2. I will like to automatically copy each serial number from the same "List worksheet" to the Column D5 of each newly created worksheet.
For example, the first created worksheet is renamed as "12345" and the worksheet should have 12345 copied in column "D5".

This is the vba that does the first action. But I really need a kind soul to help advice the 2nd action.

```<code>Sub NewSheets()
Dim i As Integer
Dim ws As Worksheet
Dim sh As Worksheet
Set ws = Sheets("Template")
Set sh = Sheets("List")
Application.ScreenUpdating = 0

For i = 2 To Range("A" & Rows.Count).End(xlUp).Row
        Sheets("Template").Copy After:=sh
        ActiveSheet.Name = sh.Range("A" & i).Value
Next i
End Sub
</code>```

答:
You simply need to set the value in cell D5 of the new worksheet:</p>

```<code>Sub NewSheets()
Dim i As Integer
Dim ws As Worksheet
Dim sh As Worksheet
Set ws = Sheets("Template")
Set sh = Sheets("List")
Application.ScreenUpdating = 0

For i = 2 To Range("A" & Rows.Count).End(xlUp).Row
        Sheets("Template").Copy After:=sh
        ActiveSheet.Name = sh.Range("A" & i).Value
        ActiveSheet.Range("D5").Value = sh.Range("A" & i).Value
Next i
End Sub
</code>```

Body:
Hoping for help with something I am working on.
1. I would like to create a vba code that creates new worksheets against a "template worksheet" and rename them based on a separate "List worksheet" that contains a list of serial numbers. I have managed to find a vba code that does this.
2. I will like to automatically copy each serial number from the same "List worksheet" to the Column D5 of each newly created worksheet.
For example, the first created worksheet is renamed as "12345" and the worksheet should have 12345 copied in column "D5".

This is the vba that does the first action. But I really need a kind soul to help advice the 2nd action.

Sub NewSheets()
Dim i As Integer
Dim ws As Worksheet
Dim sh As Worksheet
Set ws = Sheets("Template")
Set sh = Sheets("List")
Application.ScreenUpdating = 0

For i = 2 To Range("A" & Rows.Count).End(xlUp).Row
        Sheets("Template").Copy After:=sh
        ActiveSheet.Name = sh.Range("A" & i).Value
Next i
End Sub

Body:
You simply need to set the value in cell D5 of the new worksheet:

Sub NewSheets()
Dim i As Integer
Dim ws As Worksheet
Dim sh As Worksheet
Set ws = Sheets("Template")
Set sh = Sheets("List")
Application.ScreenUpdating = 0

For i = 2 To Range("A" & Rows.Count).End(xlUp).Row
        Sheets("Template").Copy After:=sh
        ActiveSheet.Name = sh.Range("A" & i).Value
        ActiveSheet.Range("D5").Value = sh.Range("A" & i).Value
Next i
End Sub


问:
SQL Access Sentence
I been trying to use this sentences that i made in SQL Server Management Studio, on access with no luck, after hours googling, i think they use different languages, can someone help me turn these in Access language?

```<code>select c.id_client 'Client ID',
c.client_name 'First Name'
c.client_lname 'Last Name'
from client c join bills b
on c.id_client = b.id_client join bill_detail d
on d.bill_num=b.bill_num
where month (b.date)=3
and year(b.date)= year(getdate())
group by c.id_client, c.client_name,c.client_lname
having d.price > (select avg(prirce) from bill_detail)

select s.id_seller 'Seller ID',
s.seller_name 'First Name',
s.seller_lname 'Last Name',
avg(quantity*d.price),
from sellers s join bills b
on v.id_seller=b.id_seller join bill_detail d
on b.bill_num = d.bill_num
group by s.id_seller, s.seller_name, s.seller_lname
having avg (quantity*d.price) < (select avg(quantity*d.price) from
bill_detail)

select date 'Date',
sum(quantity) 'Tickets Sold',
sum(quantity*d.price) 'Total Amount Sold',
avg(quantity*d.price) 'Average Amount Sold',
from bills b join bill_detail d
on b.bill_num = d.bill_num
group by date
</code>```

Sry, they were in spanish, hence the awfull english. And thanks in advance.

答:
```<code>having d.price > (select avg(prirce) from bill_detail)
</code>```

I think you should change it to avg(price) instead of avg(prirce).
(Must be spelling mistake only)

Title: SQL Access Sentence

Body:
I been trying to use this sentences that i made in SQL Server Management Studio, on access with no luck, after hours googling, i think they use different languages, can someone help me turn these in Access language?

select c.id_client 'Client ID',
c.client_name 'First Name'
c.client_lname 'Last Name'
from client c join bills b
on c.id_client = b.id_client join bill_detail d
on d.bill_num=b.bill_num
where month (b.date)=3
and year(b.date)= year(getdate())
group by c.id_client, c.client_name,c.client_lname
having d.price > (select avg(prirce) from bill_detail)

select s.id_seller 'Seller ID',
s.seller_name 'First Name',
s.seller_lname 'Last Name',
avg(quantity*d.price),
from sellers s join bills b
on v.id_seller=b.id_seller join bill_detail d
on b.bill_num = d.bill_num
group by s.id_seller, s.seller_name, s.seller_lname
having avg (quantity*d.price) < (select avg(quantity*d.price) from
bill_detail)

select date 'Date',
sum(quantity) 'Tickets Sold',
sum(quantity*d.price) 'Total Amount Sold',
avg(quantity*d.price) 'Average Amount Sold',
from bills b join bill_detail d
on b.bill_num = d.bill_num
group by date

Sry, they were in spanish, hence the awfull english. And thanks in advance.

Body:
having d.price > (select avg(prirce) from bill_detail)

I think you should change it to avg(price) instead of avg(prirce).
(Must be spelling mistake only)


问:
Ping hosts using Ansible
I understand that we can ping hosts with Ansible using the ping module. However, the ping module tries to ssh into the host in order to ping it. Is there a way to do this without having to ssh? Kind of like a liveness check?</p>

答:
You want to see that a port is up? Sure, you want wait_for.

```<code>- name: is your fridge running?
  wait_for:
    host: 1.2.3.4 # or hostvars[inventory_hostname]['ansible_default_ipv4']['address']
    port: 22
    timeout: 300 # will try for 5 mins
    state: present
</code>```

Title: Ping hosts using Ansible

Body:
You want to see that a port is up? Sure, you want wait_for.

- name: is your fridge running?
  wait_for:
    host: 1.2.3.4 # or hostvars[inventory_hostname]['ansible_default_ipv4']['address']
    port: 22
    timeout: 300 # will try for 5 mins
    state: present


问:
How to add a database retrieved value custom claim to JWT Token using ServiceStack
In AppHost.Configure I have the following code:

```<code>Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = "HS256",
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = _configuration["AuthSettings:JwtAuthKeyBase64"],//Settings.Value.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),  // JWT Token Expiry
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()), // Refresh Token Expiry,
            CreatePayloadFilter = (payload,session) => {
                    payload["ZipCode"] = "value_from_database_for_user";
            }
        },
        new CustomCredentialsAuthProvider(), //HTML Form post of User/Pass
    }));
</code>```

The above code is standard ServiceStack JwtAuthProvider code.

You can see in the above code that the implementation for the anonymous function bound to CreatePayloadFilter would like to retrieve a value from the database, the user's ZipCode is the value and add that as a custom claim to the token.

For many obvious reasons, implementing the retrieval of the user's ZipCode in the AppHost is not easy, elegant or system/architecturally sound. Also it is not even possible, as I will not have the UserId, AppHost is just startup configuration code ran when the service starts.

You can also see in the above code that I have implemented a CustomCredentialsAuthProvider, I can load session data for the logged in user in CustomCredentialsAuthProvider and ServiceStack will map the session values to hydrate the appropriate JWT claims but I cannot add a custom claim via the ServiceStack session object, here is the implementation of CustomCredentialsAuthProvider:

```<code>public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService,
        string userName, string password)
    {
        return true;
        //throw new NotImplementedException();
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService,
        IAuthSession session, IAuthTokens tokens,
        Dictionary<string, string> authInfo)
    {
        //Fill IAuthSession with data you want to retrieve in the app eg:
        session.FirstName = "some_firstname_from_db";
        session.LastName = "some_lastname_from_db";
        session.Roles = new List<string> {"role1", "role2"};
        session.Permissions = new List<string> { "permission1", "permission2" };
        session.Email = "test@test.com";
        session.AuthProvider = "credentials";

        //...

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);

        //Alternatively avoid built-in behavior and explicitly save session with
        //authService.SaveSession(session, SessionExpiry);
        //return null;
    }
}
</code>```

How can I add a custom claim to the ServiceStack framework created JWT, the value of that claim coming from the database and this implementation of this code not be function binding in AppHost.cs where I do not even have the UserId to retrieve the value anyways?

答:
It sounds like you want to use a Custom UserSession to hold the additional metadata, you can tell ServiceStack to use your Custom Session when you register the AuthFeature, e.g:

```<code>Plugins.Add(new AuthFeature(() => new CustomUserSession(), ...)
</code>```

After which you can cast the UserSession to your CustomUserSession to access the additional properties.

To add additional metadata to the JWT Token you'd use CreatePayloadFilter to add the data to the JWT Token and a corresponding PopulateSessionFilter to populate your Custom UserSession with the additional data.

Body:
In AppHost.Configure I have the following code:

Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = "HS256",
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = _configuration["AuthSettings:JwtAuthKeyBase64"],//Settings.Value.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),  // JWT Token Expiry
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()), // Refresh Token Expiry,
            CreatePayloadFilter = (payload,session) => {
                    payload["ZipCode"] = "value_from_database_for_user";
            }
        },
        new CustomCredentialsAuthProvider(), //HTML Form post of User/Pass
    }));

The above code is standard ServiceStack JwtAuthProvider code.

You can see in the above code that the implementation for the anonymous function bound to CreatePayloadFilter would like to retrieve a value from the database, the user's ZipCode is the value and add that as a custom claim to the token.

For many obvious reasons, implementing the retrieval of the user's ZipCode in the AppHost is not easy, elegant or system/architecturally sound. Also it is not even possible, as I will not have the UserId, AppHost is just startup configuration code ran when the service starts.

You can also see in the above code that I have implemented a CustomCredentialsAuthProvider, I can load session data for the logged in user in CustomCredentialsAuthProvider and ServiceStack will map the session values to hydrate the appropriate JWT claims but I cannot add a custom claim via the ServiceStack session object, here is the implementation of CustomCredentialsAuthProvider:

public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService,
        string userName, string password)
    {
        return true;
        //throw new NotImplementedException();
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService,
        IAuthSession session, IAuthTokens tokens,
        Dictionary<string, string> authInfo)
    {
        //Fill IAuthSession with data you want to retrieve in the app eg:
        session.FirstName = "some_firstname_from_db";
        session.LastName = "some_lastname_from_db";
        session.Roles = new List<string> {"role1", "role2"};
        session.Permissions = new List<string> { "permission1", "permission2" };
        session.Email = "test@test.com";
        session.AuthProvider = "credentials";

        //...

        //Call base method to Save Session and fire Auth/Session callbacks:
        return base.OnAuthenticated(authService, session, tokens, authInfo);

        //Alternatively avoid built-in behavior and explicitly save session with
        //authService.SaveSession(session, SessionExpiry);
        //return null;
    }
}

How can I add a custom claim to the ServiceStack framework created JWT, the value of that claim coming from the database and this implementation of this code not be function binding in AppHost.cs where I do not even have the UserId to retrieve the value anyways?

Body:
It sounds like you want to use a Custom UserSession to hold the additional metadata, you can tell ServiceStack to use your Custom Session when you register the AuthFeature, e.g:

Plugins.Add(new AuthFeature(() => new CustomUserSession(), ...)

After which you can cast the UserSession to your CustomUserSession to access the additional properties.

To add additional metadata to the JWT Token you'd use CreatePayloadFilter to add the data to the JWT Token and a corresponding PopulateSessionFilter to populate your Custom UserSession with the additional data.


问:
Increasing and decreasing value of the clicks of the button
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="Button" id="bt" /></code>```

答: You need to maintain a counter per each button individually - use an array to keep track of how many times a button has been clicked. If you don't the clicks var in your code will be two when you select 2 buttons and reset. </p>

Body:
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}

<input type="Button" id="bt" />


问:
"error libnfc.driver.acr122_usb Unable to write to USB (Connection timed out)"
I installed required package to use my ACR122U contactless smart card reader in Ubuntu-14-LTS. Fortunately it's work fine:

```<code>ebrahim@ubuntu:~$ pcsc_scan
PC/SC device scanner
V 1.4.22 (c) 2001-2011, Ludovic Rousseau <ludovic.rousseau@free.fr>
Compiled with PC/SC lite version: 1.8.10
Using reader plug'n play mechanism
Scanning present readers...
0: ACS ACR122U 00 00

Mon Jun 29 05:16:00 2015
Reader 0: ACS ACR122U 00 00
  Card state: Card removed,
</code>```

But when I want to use my reader with mfoc tool, I receive the following error and my reader disable (Its LED freeze and absence or presence of the card doesn't create any beep, Normally the LED change to green and red when I move a card inside or outside of its range + generating a beep voice)

```<code>^C
ebrahim@ubuntu:~$ mfoc -O test.mfd
error   libnfc.driver.acr122_usb    Unable to write to USB (Connection timed out)
No NFC device found.
ebrahim@ubuntu:~$
</code>```

How can I solve this issue?

答:
You will have to boot Kali from a USB to get this to work.  That does not solve the problem of running it in a VM, but it does allow you to do what you needed to do (two and a half years ago).

https://github.com/nfc-tools/libnfc/issues/369

Body:
I installed required package to use my ACR122U contactless smart card reader in Ubuntu-14-LTS. Fortunately it's work fine:

ebrahim@ubuntu:~$ pcsc_scan
PC/SC device scanner
V 1.4.22 (c) 2001-2011, Ludovic Rousseau <ludovic.rousseau@free.fr>
Compiled with PC/SC lite version: 1.8.10
Using reader plug'n play mechanism
Scanning present readers...
0: ACS ACR122U 00 00

Mon Jun 29 05:16:00 2015
Reader 0: ACS ACR122U 00 00
  Card state: Card removed,

But when I want to use my reader with mfoc tool, I receive the following error and my reader disable (Its LED freeze and absence or presence of the card doesn't create any beep, Normally the LED change to green and red when I move a card inside or outside of its range + generating a beep voice)

^C
ebrahim@ubuntu:~$ mfoc -O test.mfd
error   libnfc.driver.acr122_usb    Unable to write to USB (Connection timed out)
No NFC device found.
ebrahim@ubuntu:~$

How can I solve this issue?


问:
Counting DISTINCT values in T-SQL
I am trying to count the number of distinct email addresses in a view, but I can't figure out the syntax... Here's what I have:

```<code>BEGIN
  SELECT COUNT(*) AS UserCount FROM (
    SELECT DISTINCT EmailAddress
    FROM viewCohortsAuthorizedByContractor
    WHERE (ListAccess = 1) AND (ContractorId = @id)
  )
END
</code>```

The inner select works fine, but if I try adding the COUNT, I get the following error: Msg 156, Level 15, State 1, Procedure rptContractorUsersWithListUserCount, Line 23 [Batch Start Line 15]
Incorrect syntax near the keyword 'END'.

I'm sure there's a simple solution, I just can't figure it out...

答:
You don't need the subquery. Try this:</p>

```<code>SELECT count(DISTINCT EmailAddress) as UserCount
FROM viewCohortsAuthorizedByContractor
WHERE (ListAccess = 1) AND (ContractorId = @id)
</code>```

Title: Counting DISTINCT values in T-SQL

Body:
I am trying to count the number of distinct email addresses in a view, but I can't figure out the syntax... Here's what I have:

BEGIN
  SELECT COUNT(*) AS UserCount FROM (
    SELECT DISTINCT EmailAddress
    FROM viewCohortsAuthorizedByContractor
    WHERE (ListAccess = 1) AND (ContractorId = @id)
  )
END

The inner select works fine, but if I try adding the COUNT, I get the following error: Msg 156, Level 15, State 1, Procedure rptContractorUsersWithListUserCount, Line 23 [Batch Start Line 15]
Incorrect syntax near the keyword 'END'.

I'm sure there's a simple solution, I just can't figure it out...

Body:
You don't need the subquery. Try this:

SELECT count(DISTINCT EmailAddress) as UserCount
FROM viewCohortsAuthorizedByContractor
WHERE (ListAccess = 1) AND (ContractorId = @id)


问:
ListView with horizontally scrollable views
I'm currently developing an app in android.
I have a really basic listview that has 3 elements in his adapter:
1 imageview and 2 textviews.
These 3 items are inside a constraint layout.

All i ask is if i can make this layout (imgview + 2 tview) scrollable horizontally.

I've tried adding the layout to a horizontalscrollview, it works but i can't take the list onclicklistener.

答: I assume you want to be able to click on a list item? You could try adding a click listener to the scrollView. You probably also need to set clickable = true on the scrollview (not sure which is the default) and also just in case set clickable = false to all 3 child elements so they don't "eat" the click instead of the scrollView.</p>


问:
Ambiguous Lexer rules in Antlr
I have an antlr grammar with multiple lexer rules that match the same word. It can't be resolved during lexing, but with the grammar, it becomes unambiguous.

Example:

```<code>conversion: NUMBER UNIT CONVERT UNIT;
NUMBER: [0-9]+;
UNIT: 'in' | 'meters' | ......;
CONVERT: 'in';
</code>```

Input: 1 in in meters

The word "in" matches the lexer rules UNIT and CONVERT.

How can this be solved while keeping the grammar file readable?

答:
When an input matches two lexer rules, ANTLR chooses either the longest or the first, see disambiguate. With your grammar, in will be interpreted as UNIT, never CONVERT, and the rule

```<code>conversion: NUMBER UNIT CONVERT UNIT;
</code>```

can't work because there are three UNIT tokens :

```<code>$ grun Question question -tokens -diagnostics input.txt
[@0,0:0='1',<NUMBER>,1:0]
[@1,1:1=' ',<WS>,channel=1,1:1]
[@2,2:3='in',<UNIT>,1:2]
[@3,4:4=' ',<WS>,channel=1,1:4]
[@4,5:6='in',<UNIT>,1:5]
[@5,7:7=' ',<WS>,channel=1,1:7]
[@6,8:13='meters',<UNIT>,1:8]
[@7,14:14='\n',<NL>,1:14]
[@8,15:14='<EOF>',<EOF>,2:0]
Question last update 0159
line 1:5 missing 'in' at 'in'
line 1:8 mismatched input 'meters' expecting <EOF>
</code>```

What you can do is to have only ID or TEXT tokens and distinguish them with a label, like this :

```<code>grammar Question;

question
@init {System.out.println("Question last update 0132");}
    :   conversion NL EOF
    ;

conversion
    :   NUMBER unit1=ID convert=ID unit2=ID
        {System.out.println("Quantity " + $NUMBER.text + " " + $unit1.text +
         " to convert " + $convert.text + " " + $unit2.text);}
    ;

ID      : LETTER ( LETTER | DIGIT | '_' )* ; // or TEXT : LETTER+ ;
NUMBER  : DIGIT+ ;

NL      : [\r\n] ;
WS      : [ \t] -> channel(HIDDEN) ; // -> skip ;

fragment LETTER : [a-zA-Z] ;
fragment DIGIT  : [0-9] ;
</code>```

Execution :

```<code>$ grun Question question -tokens -diagnostics input.txt
[@0,0:0='1',<NUMBER>,1:0]
[@1,1:1=' ',<WS>,channel=1,1:1]
[@2,2:3='in',<ID>,1:2]
[@3,4:4=' ',<WS>,channel=1,1:4]
[@4,5:6='in',<ID>,1:5]
[@5,7:7=' ',<WS>,channel=1,1:7]
[@6,8:13='meters',<ID>,1:8]
[@7,14:14='\n',<NL>,1:14]
[@8,15:14='<EOF>',<EOF>,2:0]
Question last update 0132
Quantity 1 in to convert in meters
</code>```

Labels are available from the rule's context in the visitor, so it is easy to distinguish tokens of the same type.

Title: Ambiguous Lexer rules in Antlr

Body:
I have an antlr grammar with multiple lexer rules that match the same word. It can't be resolved during lexing, but with the grammar, it becomes unambiguous.

Example:

conversion: NUMBER UNIT CONVERT UNIT;
NUMBER: [0-9]+;
UNIT: 'in' | 'meters' | ......;
CONVERT: 'in';

Input: 1 in in meters

The word "in" matches the lexer rules UNIT and CONVERT.

How can this be solved while keeping the grammar file readable?

Body:
When an input matches two lexer rules, ANTLR chooses either the longest or the first, see disambiguate. With your grammar, in will be interpreted as UNIT, never CONVERT, and the rule

conversion: NUMBER UNIT CONVERT UNIT;

can't work because there are three UNIT tokens :

$ grun Question question -tokens -diagnostics input.txt
[@0,0:0='1',<NUMBER>,1:0]
[@1,1:1=' ',<WS>,channel=1,1:1]
[@2,2:3='in',<UNIT>,1:2]
[@3,4:4=' ',<WS>,channel=1,1:4]
[@4,5:6='in',<UNIT>,1:5]
[@5,7:7=' ',<WS>,channel=1,1:7]
[@6,8:13='meters',<UNIT>,1:8]
[@7,14:14='\n',<NL>,1:14]
[@8,15:14='<EOF>',<EOF>,2:0]
Question last update 0159
line 1:5 missing 'in' at 'in'
line 1:8 mismatched input 'meters' expecting <EOF>

What you can do is to have only ID or TEXT tokens and distinguish them with a label, like this :

grammar Question;

question
@init {System.out.println("Question last update 0132");}
    :   conversion NL EOF
    ;

conversion
    :   NUMBER unit1=ID convert=ID unit2=ID
        {System.out.println("Quantity " + $NUMBER.text + " " + $unit1.text +
         " to convert " + $convert.text + " " + $unit2.text);}
    ;

ID      : LETTER ( LETTER | DIGIT | '_' )* ; // or TEXT : LETTER+ ;
NUMBER  : DIGIT+ ;

NL      : [\r\n] ;
WS      : [ \t] -> channel(HIDDEN) ; // -> skip ;

fragment LETTER : [a-zA-Z] ;
fragment DIGIT  : [0-9] ;

Execution :

$ grun Question question -tokens -diagnostics input.txt
[@0,0:0='1',<NUMBER>,1:0]
[@1,1:1=' ',<WS>,channel=1,1:1]
[@2,2:3='in',<ID>,1:2]
[@3,4:4=' ',<WS>,channel=1,1:4]
[@4,5:6='in',<ID>,1:5]
[@5,7:7=' ',<WS>,channel=1,1:7]
[@6,8:13='meters',<ID>,1:8]
[@7,14:14='\n',<NL>,1:14]
[@8,15:14='<EOF>',<EOF>,2:0]
Question last update 0132
Quantity 1 in to convert in meters

Labels are available from the rule's context in the visitor, so it is easy to distinguish tokens of the same type.


问:
Do html and php use the same css file?
for example: you created a website and in that website you want to create a login page using php. Do you use the css file that you design your website with, to design login page?</p>

答:
PHP actually runs on the server and it renders html (usually).

So if the template you're rendering with php has the same css file included you could use the same css for both pages.

Now for your needs, the login page has possibly some css that your other pages don't need. I would suggest creating a common.css file with everything that both pages will have and another with the login page specific styles.

I hope that's what your looking for.

Title: Do html and php use the same css file?


问:
Sum of dot products
How to transform 100 of 8 element vectors into 10 16 element vectors using 1000 different (8,16) weight matrices? Each of the 10 output vectors is a sum of 100 dot products:

```<code>A = np.random.randn(100,8)
W = np.random.randn(1000,8,16)
B = []

for i in range(10):
  sum = np.zeros((1,16))
  for j in range(100):
    sum += np.dot(A[j], W[i*100+j])
  B.append(sum)
B = np.asarray(B)     #B.shape=(10,16)
</code>```

Is there a function in Numpy or TensorFlow for that? I looked at dot, tensordot, einsum, and matmul in Numpy, and I'm still not sure which one is the right option.

EDIT: I just realized that I actually want to produce an intermediate result before summing dot products: (100,8)x(10,100,8,16) -> (10,100,16).

I'm guessing this could be done with reshaping (100,8) to (1,100,1,8) and (1000,8,16) to (10,100,8,16), and doing np.einsum('ijkl,ijlm->ijm', A, B)  But I'm not sure if it will broadcast 1 to 10 correctly.

Per @Divakar comment, np.einsum('jk,ijkl->ijl', V, W.reshape(10,100,8,16)) does the trick.

答:
In one line, it's

```<code>B1 = np.einsum('ij,ikjl', A, np.reshape(W, (100, 10, 8, 16), order='F'))
</code>```

Test it with np.allclose(B.squeeze(), B1) where you need .squeeze because your B has an extra dimension of size 1.

Explanation: your W has ugly shape, its first dimension of size 1000 should really be separated in 10 blocks of size 100 (as you in effect do with index manipulation in a loop). This is what reshape is for. The Fortran-style order is needed because we want to take out elements of W by changing the first index the fastest.

After that it's straightforward Einstein summation: over j to have matrix multiplication, over i to add 100 results.

Title: Sum of dot products

Body:
How to transform 100 of 8 element vectors into 10 16 element vectors using 1000 different (8,16) weight matrices? Each of the 10 output vectors is a sum of 100 dot products:

A = np.random.randn(100,8)
W = np.random.randn(1000,8,16)
B = []

for i in range(10):
  sum = np.zeros((1,16))
  for j in range(100):
    sum += np.dot(A[j], W[i*100+j])
  B.append(sum)
B = np.asarray(B)     #B.shape=(10,16)

Is there a function in Numpy or TensorFlow for that? I looked at dot, tensordot, einsum, and matmul in Numpy, and I'm still not sure which one is the right option.

EDIT: I just realized that I actually want to produce an intermediate result before summing dot products: (100,8)x(10,100,8,16) -> (10,100,16).

I'm guessing this could be done with reshaping (100,8) to (1,100,1,8) and (1000,8,16) to (10,100,8,16), and doing np.einsum('ijkl,ijlm->ijm', A, B)  But I'm not sure if it will broadcast 1 to 10 correctly.

Per @Divakar comment, np.einsum('jk,ijkl->ijl', V, W.reshape(10,100,8,16)) does the trick.

Body:
In one line, it's

B1 = np.einsum('ij,ikjl', A, np.reshape(W, (100, 10, 8, 16), order='F'))

Test it with np.allclose(B.squeeze(), B1) where you need .squeeze because your B has an extra dimension of size 1.

Explanation: your W has ugly shape, its first dimension of size 1000 should really be separated in 10 blocks of size 100 (as you in effect do with index manipulation in a loop). This is what reshape is for. The Fortran-style order is needed because we want to take out elements of W by changing the first index the fastest.

After that it's straightforward Einstein summation: over j to have matrix multiplication, over i to add 100 results.


问:
Ajax double forms, first form with select then classic form
So I have one form in frontend. And second form in process file.
With first form i calling second form with products information.

FIRST FORM

```<code>      $izmena_proizvoda = $conn->query("SELECT * FROM proizvodi");
      $izmena_proizvoda->execute();
      echo '<form method="POST">';
      echo '<select class="form-control" name="izmena_proizvoda" id="izaberi_proizvod" onchange="izmena_proizvoda_ajax(this.value);">';
      echo '<option>Izaberite proizvod</option>';
            while($izmena_proizvoda_o=$izmena_proizvoda->fetch()){
                echo '<option value="'.$izmena_proizvoda_o['id_sata'].'">';
                echo $izmena_proizvoda_o['nazivsata'];
                echo '</option>';
            }
      echo '</select>';
      echo '</form>';
</code>```

And ajax for this form

```<code>    function izmena_proizvoda_ajax(val){
    $.ajax({
        url: "../sadrzaj/stranice/izmenaproizvoda.php",
        type: 'POST',
        data: {
            izmena_proizvoda:val
        },
        success: function (response) {
            document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
            console.log(response)

        }
    });
}
</code>```

In process file i have this one.

```<code>if(isset($_POST['izmena_proizvoda'])){
$izmena_proizvoda_forma = $conn->prepare("SELECT * FROM proizvodi WHERE id_sata = :id_sata");
$izmena_proizvoda_forma->bindParam(':id_sata', $_POST['izmena_proizvoda'], PDO::PARAM_INT);
$izmena_proizvoda_forma->execute();
echo '<hr>';
echo '<form method="post" action="#" id="izmena_proizvoda_update_form" class="ajax" >';
while($izmena_proizvoda_forma_o=$izmena_proizvoda_forma->fetch()){
    echo'
              <input type="hidden" name="slika_za_brisanje" value="'.$izmena_proizvoda_forma_o['slika'].'">
              <input type="hidden" name="id_izmena" value="'.$izmena_proizvoda_forma_o['id_sata'].'">
              <label for="naslov_izmena">Naziv sata</label>
              <input type="text" id="naslov_izmena" name="naslov_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['nazivsata'].'">
              <label for="cena_izmena">Cena</label>
              <input id="cena_izmena" type="text" name="cena_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['cenasata'].'"><br>
              <label for="vodootpornost">Vodootpornost</label>
              <input id="vodootpornost" type="text" name="vodootpornost" class="form-control" value="'.$izmena_proizvoda_forma_o['vodootpornost'].'"><br>
              <label for="zalihe">Zalihe</label>
              <input id="zalihe" type="text" name="zalihe" class="form-control" value="'.$izmena_proizvoda_forma_o['zalihe'].'"><br>
              <label for="pol">Pol sata</label>
              <input id="pol" type="text" name="pol" class="form-control" value="'.$izmena_proizvoda_forma_o['pol'].'"><br>
              <label for="opissata_izmena"></label>';
    echo '  <textarea id="opissata_izmena" rows="10" name="opissata_izmena">'.$izmena_proizvoda_forma_o['opissata'].'</textarea><br>';

    echo '<input type="submit" name="izmena_proizvoda_potvrda" value="Sacuvaj izmene" class="btn btn-info">';
}
echo '</form>';
}
</code>```

So when i do that on frontend. works fine. But when i try to do another ajax for form2 i have a problems. I dont know how i can run a ajax for another form.
I try to put ajax code in forntend page but didnt work. Also i tryed to put ajax in process file below the form. To call both together. also didnt fork.
How I can make some trigger for ajax 2 from ajax 1 like

Ajax1: Hey ajax2 i do my job. You now have a form. When user click submit, do your job and dont refres a page.

Sorry beacuse my bad english.

答:
You get rid of your onchange handler, keep your <form> tags and attach your event handler to all forms instead of a specific form. Then use $(this) to reference the values of the form which generates the submission event.

```<code>$("form").on("submit", function(event) {
  event.preventDefault();
  var data = $(this).serialize(); // Grabs all data from the form being submitted
  $.ajax({
    url: "../sadrzaj/stranice/izmenaproizvoda.php",
    type: 'POST',
    data: data,
    success: function(response) {
      document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
      console.log(response);
      // If you need to alter success handlers you can add data elements to your form HTML and reference them here
      // Same is true if you need to alter submission URL or whatever
    }
  });
});
</code>```

Body:
So I have one form in frontend. And second form in process file.
With first form i calling second form with products information.

FIRST FORM

      $izmena_proizvoda = $conn->query("SELECT * FROM proizvodi");
      $izmena_proizvoda->execute();
      echo '<form method="POST">';
      echo '<select class="form-control" name="izmena_proizvoda" id="izaberi_proizvod" onchange="izmena_proizvoda_ajax(this.value);">';
      echo '<option>Izaberite proizvod</option>';
            while($izmena_proizvoda_o=$izmena_proizvoda->fetch()){
                echo '<option value="'.$izmena_proizvoda_o['id_sata'].'">';
                echo $izmena_proizvoda_o['nazivsata'];
                echo '</option>';
            }
      echo '</select>';
      echo '</form>';

And ajax for this form

    function izmena_proizvoda_ajax(val){
    $.ajax({
        url: "../sadrzaj/stranice/izmenaproizvoda.php",
        type: 'POST',
        data: {
            izmena_proizvoda:val
        },
        success: function (response) {
            document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
            console.log(response)

        }
    });
}

In process file i have this one.

if(isset($_POST['izmena_proizvoda'])){
$izmena_proizvoda_forma = $conn->prepare("SELECT * FROM proizvodi WHERE id_sata = :id_sata");
$izmena_proizvoda_forma->bindParam(':id_sata', $_POST['izmena_proizvoda'], PDO::PARAM_INT);
$izmena_proizvoda_forma->execute();
echo '
';
echo '<form method="post" action="#" id="izmena_proizvoda_update_form" class="ajax" >';
while($izmena_proizvoda_forma_o=$izmena_proizvoda_forma->fetch()){
    echo'
              <input type="hidden" name="slika_za_brisanje" value="'.$izmena_proizvoda_forma_o['slika'].'">
              <input type="hidden" name="id_izmena" value="'.$izmena_proizvoda_forma_o['id_sata'].'">
              Naziv sata
              <input type="text" id="naslov_izmena" name="naslov_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['nazivsata'].'">
              Cena
              <input id="cena_izmena" type="text" name="cena_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['cenasata'].'">

              Vodootpornost
              <input id="vodootpornost" type="text" name="vodootpornost" class="form-control" value="'.$izmena_proizvoda_forma_o['vodootpornost'].'">

              Zalihe
              <input id="zalihe" type="text" name="zalihe" class="form-control" value="'.$izmena_proizvoda_forma_o['zalihe'].'">

              Pol sata
              <input id="pol" type="text" name="pol" class="form-control" value="'.$izmena_proizvoda_forma_o['pol'].'">

              ';
    echo '  <textarea id="opissata_izmena" rows="10" name="opissata_izmena">'.$izmena_proizvoda_forma_o['opissata'].'</textarea>
';

    echo '<input type="submit" name="izmena_proizvoda_potvrda" value="Sacuvaj izmene" class="btn btn-info">';
}
echo '</form>';
}

So when i do that on frontend. works fine. But when i try to do another ajax for form2 i have a problems. I dont know how i can run a ajax for another form.
I try to put ajax code in forntend page but didnt work. Also i tryed to put ajax in process file below the form. To call both together. also didnt fork.
How I can make some trigger for ajax 2 from ajax 1 like

Ajax1: Hey ajax2 i do my job. You now have a form. When user click submit, do your job and dont refres a page.

Sorry beacuse my bad english.

Body:
You get rid of your onchange handler, keep your <form> tags and attach your event handler to all forms instead of a specific form. Then use $(this) to reference the values of the form which generates the submission event.

$("form").on("submit", function(event) {
  event.preventDefault();
  var data = $(this).serialize(); // Grabs all data from the form being submitted
  $.ajax({
    url: "../sadrzaj/stranice/izmenaproizvoda.php",
    type: 'POST',
    data: data,
    success: function(response) {
      document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
      console.log(response);
      // If you need to alter success handlers you can add data elements to your form HTML and reference them here
      // Same is true if you need to alter submission URL or whatever
    }
  });
});


问:
jQuery - Change class in HTML through Javascript by if/else if
I have a bootstrap validation form which is working perfectly and also changing the inputField colour on error & success.

The problem is, I want to change the text-color and border-color of Label. I have tried various JavaScript code but no one works for me as I am not familiar with javascript.

HTML

```<code><form action="" class="form-horizontal form-bordered storyForm" novalidate>

<div class="form-body">
    <div class="form-group" id="form-group">
        <div class="controls">
            <label class="control-label" id="label" for="email">Email</label>
            <input type="email" id="email" class="form-control" name="email" required data-validation-required-message="This field is required">
        </div>
    </div>
    <div class="form-group" id="form-group">
        <div class="controls">
            <label class="control-label" id="label" for="password">Password</label>
            <input type="password" id="password" class="form-control" name="password" required data-validation-required-message="This field is required">
        </div>
    </div>
</div>

<div class="form-actions">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="offset-sm-3 col-md-9">
                    <button type="submit" id="submit" class="btn btn-success"> <i class="fa fa-check"></i> Submit</button>
                    <button type="button" class="btn btn-inverse">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

CSS

```<code>form.storyForm label{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #000;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid rgba(0,0,0,.15);
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.error{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #ef5350;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #ef5350;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.validate{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #26dad2;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #26dad2;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
</code>```

The javascript code which I'm trying to add/remove the class

```<code><script>
$(document).ready(function() {
    $("#submit").click(function() {
        if ($("#form-group").hasClass("error")) {
            $("#label").addClass("error");
        } else if ($("#form-group").hasClass("validate")) {
            $("#label").removeClass("error");
            $("#label").addClass("validate");
        }
    });
});
</script>
</code>```

I also checked throught class but it was also not working for me

```<code><script>
$(document).ready(function() {
 $("#submit").click(function() {
    if ($(".form-group").hasClass("error")) {
        $(".control-label").addClass("error");
    } else if ($("#form-group").hasClass("validate")) {
        $(".control-label").removeClass("error");
        $(".control-label").addClass("validate");
    }
 });
});
</script>
</code>```

答:
You are using '$' inside the JavaScript, make sure you've included the JQuery library. '$' is the primary base object (or function) for JQuery. If you are not using JQuery, you need to use JavaScript methods such as .getElementById() or .querySelector() and pass your id value as parameters to these methods.

Also, using querySelector is a better way to address this functionality.

Here is the link to MDN getElementById() documentation and MDN querySelector() documentation.

I hope this helps! Good Luck!

Body:
I have a bootstrap validation form which is working perfectly and also changing the inputField colour on error & success.

The problem is, I want to change the text-color and border-color of Label. I have tried various JavaScript code but no one works for me as I am not familiar with javascript.

HTML

<form action="" class="form-horizontal form-bordered storyForm" novalidate>

            Email
            <input type="email" id="email" class="form-control" name="email" required data-validation-required-message="This field is required">

            Password
            <input type="password" id="password" class="form-control" name="password" required data-validation-required-message="This field is required">

                    <button type="submit" id="submit" class="btn btn-success">  Submit</button>
                    <button type="button" class="btn btn-inverse">Cancel</button>

CSS

form.storyForm label{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #000;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid rgba(0,0,0,.15);
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.error{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #ef5350;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #ef5350;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.validate{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #26dad2;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #26dad2;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}

The javascript code which I'm trying to add/remove the class

I also checked throught class but it was also not working for me


问:
Calculate how often specific daytime is contained in time range
I have a time range starting with a start date and end date represented in milliseconds since 1970:

```<code>long start;
long end;
</code>```

And I want to know if and how often a specific daytime is contained in this range. So let's say the daytime is 09.00 am DST - how often is it contained in the range.

Is there an easy and elegant way to calculate this in Java?

答:
If you're using Java 8, you could use java.time.OffsetDateTime, starting from your start point, adjusting the time based on toOffsetTime, then repeatedly using plusDays until you've exceeded your end time.

If not, then you can achieve something similar with Joda's DateTime class.

Don't try it without a library that handles calendars properly.

Body:
I have a time range starting with a start date and end date represented in milliseconds since 1970:

long start;
long end;

And I want to know if and how often a specific daytime is contained in this range. So let's say the daytime is 09.00 am DST - how often is it contained in the range.

Is there an easy and elegant way to calculate this in Java?


问:
How to not allow user to skip video
Is there a way to let the user watch a video  without skipping any part? Basically something along the lines, where they have to watch the entire video to go to the next process. </p>

答:
Short answer: No

Long answer: All you can do is hiding the controls or using other analytical methods to determine whether a skip has occurred. But at the end, keep in mind that your code depends on a client side interpreter. If a user really wants to skip it, there will always be a way to do it.

Title: How to not allow user to skip video


问:
Bind modal to corresponding button after a v-for
I'm trying to bind a vue bootstrap modal to its button after displaying multiple ones with v-for:

here is my code:

```<code><template>
  <div>
    <b-container fluid>
      <b-row>
        <b-col xs="12" sm="12" md="6" lg="4" v-for="project in projects" v-bind:key="project.id">
          <p>
           {{ project.body }}
          </p>
          <b-button variant="primary" v-b-modal.myModal>Go somewhere</b-button>
          <b-modal id="myModal" size="lg" title="Large Modal" centered >
            Hello Modal!
          </b-modal>
        </b-col>
      </b-row>
  </b-container>
  </div>
</template>

<script>
  import jsonProjects from '@/data/projects.json'

  export default {
    name: 'Grid',
    data () {
      return {
        projects: jsonProjects
      }
    }
  }
</script>
</code>```

With this this setup when I click on a single button all modals are open so my issue is how to bind "v-b-modal.myModal" to the id="myModal" dynamically with the data id for example.

The data is a simple json format.

Thank you all.

答:
You should use unique ids, as Belmin said.

Dynamic v-b-modal value

Dynamic id

```<code><template>
    <div>
        <b-container fluid>
            <b-row>
                <b-col xs="12" sm="12" md="6" lg="4" v-for="project in projects" v-bind:key="project.id">
                    <p>
                        {{ project.body }}
                    </p>
                    <b-button variant="primary" v-b-modal="'myModal' + project.id">Go somewhere</b-button>
                    <b-modal :id="'myModal' + project.id" size="lg" title="Large Modal" centered >
                        Hello Modal!
                    </b-modal>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>
</code>```

Body:
I'm trying to bind a vue bootstrap modal to its button after displaying multiple ones with v-for:

here is my code:

<template>

           {{ project.body }}

          Go somewhere

            Hello Modal!

</template>

With this this setup when I click on a single button all modals are open so my issue is how to bind "v-b-modal.myModal" to the id="myModal" dynamically with the data id for example.

The data is a simple json format.

Thank you all.

Body:
You should use unique ids, as Belmin said.

Dynamic v-b-modal value <b-button v-b-modal="'myModal' + project.id">

Dynamic id <b-modal :id="'myModal' + project.id">

<template>
    <div>
        <b-container fluid>
            <b-row>
                <b-col xs="12" sm="12" md="6" lg="4" v-for="project in projects" v-bind:key="project.id">
                    <p>
                        {{ project.body }}
                    </p>
                    <b-button variant="primary" v-b-modal="'myModal' + project.id">Go somewhere</b-button>
                    <b-modal :id="'myModal' + project.id" size="lg" title="Large Modal" centered >
                        Hello Modal!
                    </b-modal>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>


问:
ASP Edit GridView Style
Using the examples posted here, I have everything working. The problem is the style. When the gridview loads, it looks amazing. I press Edit, the font, column height, width, etc, all change. How can I edit the style when the EDIT button is pressed to look exactly like the previous style when loaded?</p>

```<code><asp:GridView ID="GridView1" runat="server" DataKeyNames="CustomerId" OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
</asp:GridView>
</code>```

答:
You can use the gridview itself:

```<code><asp:GridView ID="GridView1" runat="server">
    <EditRowStyle BackColor="Green" />
</asp:GridView>
</code>```

Use the gridview with a stylesheet:

```<code><asp:GridView ID="GridView1" runat="server">
    <EditRowStyle CssClass="myClass" />
</asp:GridView>
</code>```

or use a stylesheet:

```<code>#GridView1 input { width: 100%; }
</code>```

Title: ASP Edit GridView Style

Body:
Using the examples posted here, I have everything working. The problem is the style. When the gridview loads, it looks amazing. I press Edit, the font, column height, width, etc, all change. How can I edit the style when the EDIT button is pressed to look exactly like the previous style when loaded?

<asp:GridView ID="GridView1" runat="server" DataKeyNames="CustomerId" OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
</asp:GridView>

Body:
You can use the gridview itself:

<asp:GridView ID="GridView1" runat="server">
    <EditRowStyle BackColor="Green" />
</asp:GridView>

Use the gridview with a stylesheet:

<asp:GridView ID="GridView1" runat="server">
    <EditRowStyle CssClass="myClass" />
</asp:GridView>

or use a stylesheet:

#GridView1 input { width: 100%; }


问:
Why does javascript ssh2 get stuck in infinite loop when using shell
I am trying to get my application to execute a sudo command on another system by utilizing the ssh2 npm package. I have the end result working, but for some reason the code is getting stuck in an infinite loop. I don't understand how this is possible as I thought that closing the connection with conn.end would prevent this from happening. Can anyone help shed some light on why I am getting stuck in an infinite loop here?

Primary Code being executed:

```<code>function sshRunSudoCommand(user, pass, lanIP, command) {

  return new Promise((resolve, reject) => {
    var Connection  = require('ssh2');
    var pwSent      = false;
    var sudosu      = false;
    var password    = pass;
    var conn        = new Connection();

    conn.on('ready', function() {
      console.log('Sudo Connection :: ready');
      conn.shell( function(err, stream) {
        if (err) throw err;
        stream
          .on('close', function() {
          console.log('Sudo Stream :: close');
          conn.end();
          resolve();
        })
          .on('data', function(data) {
          //handle sudo password prompt
          stream.write(password + '\n');
          stream.write(command + '\n');
          console.log('Sudo STDOUT: ' + data);
          resolve(data);
        })
          .on('exit', function(code, signal) {
          let exitCode = 'Stream :: exit :: code: ' + code + ', signal: ' + signal;
          conn.end();
          resolve(exitCode);
        })
          .on('end', function() {
            conn.end();
            resolve('end');
          })
          .stderr.on('data', function(data) {
          console.log('STDERR: ' + data);
          conn.end();
          resolve(data);
        });

      });
    })
      .on('keyboard-interactive',
        function(name, instructions, instructionsLang, prompts, finish) {
          // Pass answers to `prompts` to `finish()`. Typically `prompts.length === 1`
          // with `prompts[0] === "Password: "`
          console.log('pass before finish is ', pass);
          finish([pass]);
        }).on('ready', function() {
    }).connect({
      host: lanIP,
      port: 22,
      username: user,
      password: pass,
      readyTimeout: 99999,
      tryKeyboard: true // this attempts keyboard-interactive auth
    });
  };
}
</code>```

Result: (Repeated over and over forever)

```<code>Sudo STDOUT: activedash:~ activeadmin$ s
Sudo STDOUT: udo
Sudo STDOUT: profiles -I -
Sudo STDOUT: F /Users/S
Sudo STDOUT: hared/Sym
Sudo STDOUT: ply/activ
Sudo STDOUT: e-uuid.
onfigpr
Sudo STDOUT: ofile

Sudo STDOUT: active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles
</code>```

答:
So what I found was there was 2 things I needed to do to prevent the repeating action.

I needed to add and 'exit' command to the stream.write to tell the shell to end the session I had created with conn.shell

Then I could move my resolve() callback down to the .on('exit) section of code to only come back after I had run the exit command successfully.

The final code looks like this:

```<code>function sshRunSudoCommand(user, pass, lanIP, command) {

  return new Promise((resolve, reject) => {
    var Connection  = require('ssh2');
    var password    = pass;
    var conn        = new Connection();

    conn.on('ready', function() {
      console.log('Sudo Connection :: ready');
      conn.shell( function(err, stream) {
        if (err) throw err;
        stream
          .on('close', function() {
          console.log('Sudo Stream :: close');
          conn.end();
          resolve();
        })
          .on('data', function(data) {
          //handle sudo password prompt
          stream.write(password + '\n');
          stream.write(command + '\n');
          stream.write('exit\n');
        })
          .on('exit', function(code, signal) {
          let exitCode = 'Stream :: exit :: code: ' + code + ', signal: ' + signal;
          conn.end();
          resolve(exitCode);
        })
          .on('end', function() {
            conn.end();
            resolve('end');
          })
          .stderr.on('data', function(data) {
          console.log('STDERR: ' + data);
          conn.end();
          resolve(data);
        });

      });
    })
      .on('keyboard-interactive',
        function(name, instructions, instructionsLang, prompts, finish) {
          // Pass answers to `prompts` to `finish()`. Typically `prompts.length === 1`
          // with `prompts[0] === "Password: "`
          console.log('pass before finish is ', pass);
          finish([pass]);
        }).on('ready', function() {
    }).connect({
      host: lanIP,
      port: 22,
      username: user,
      password: pass,
      readyTimeout: 99999,
      tryKeyboard: true // this attempts keyboard-interactive auth
    });
  };
}
</code>```

Body:
I am trying to get my application to execute a sudo command on another system by utilizing the ssh2 npm package. I have the end result working, but for some reason the code is getting stuck in an infinite loop. I don't understand how this is possible as I thought that closing the connection with conn.end would prevent this from happening. Can anyone help shed some light on why I am getting stuck in an infinite loop here?

Primary Code being executed:

function sshRunSudoCommand(user, pass, lanIP, command) {

  return new Promise((resolve, reject) => {
    var Connection  = require('ssh2');
    var pwSent      = false;
    var sudosu      = false;
    var password    = pass;
    var conn        = new Connection();

    conn.on('ready', function() {
      console.log('Sudo Connection :: ready');
      conn.shell( function(err, stream) {
        if (err) throw err;
        stream
          .on('close', function() {
          console.log('Sudo Stream :: close');
          conn.end();
          resolve();
        })
          .on('data', function(data) {
          //handle sudo password prompt
          stream.write(password + '\n');
          stream.write(command + '\n');
          console.log('Sudo STDOUT: ' + data);
          resolve(data);
        })
          .on('exit', function(code, signal) {
          let exitCode = 'Stream :: exit :: code: ' + code + ', signal: ' + signal;
          conn.end();
          resolve(exitCode);
        })
          .on('end', function() {
            conn.end();
            resolve('end');
          })
          .stderr.on('data', function(data) {
          console.log('STDERR: ' + data);
          conn.end();
          resolve(data);
        });

      });
    })
      .on('keyboard-interactive',
        function(name, instructions, instructionsLang, prompts, finish) {
          // Pass answers to `prompts` to `finish()`. Typically `prompts.length === 1`
          // with `prompts[0] === "Password: "`
          console.log('pass before finish is ', pass);
          finish([pass]);
        }).on('ready', function() {
    }).connect({
      host: lanIP,
      port: 22,
      username: user,
      password: pass,
      readyTimeout: 99999,
      tryKeyboard: true // this attempts keyboard-interactive auth
    });
  };
}

Result: (Repeated over and over forever)

Sudo STDOUT: activedash:~ activeadmin$ s
Sudo STDOUT: udo
Sudo STDOUT: profiles -I -
Sudo STDOUT: F /Users/S
Sudo STDOUT: hared/Sym
Sudo STDOUT: ply/activ
Sudo STDOUT: e-uuid.
onfigpr
Sudo STDOUT: ofile

Sudo STDOUT: active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles -I -F /Users/Shared/Symply/active-uuid.configprofile
active
sudo profiles

Body:
So what I found was there was 2 things I needed to do to prevent the repeating action.

I needed to add and 'exit' command to the stream.write to tell the shell to end the session I had created with conn.shell

Then I could move my resolve() callback down to the .on('exit) section of code to only come back after I had run the exit command successfully.

The final code looks like this:

function sshRunSudoCommand(user, pass, lanIP, command) {

  return new Promise((resolve, reject) => {
    var Connection  = require('ssh2');
    var password    = pass;
    var conn        = new Connection();

    conn.on('ready', function() {
      console.log('Sudo Connection :: ready');
      conn.shell( function(err, stream) {
        if (err) throw err;
        stream
          .on('close', function() {
          console.log('Sudo Stream :: close');
          conn.end();
          resolve();
        })
          .on('data', function(data) {
          //handle sudo password prompt
          stream.write(password + '\n');
          stream.write(command + '\n');
          stream.write('exit\n');
        })
          .on('exit', function(code, signal) {
          let exitCode = 'Stream :: exit :: code: ' + code + ', signal: ' + signal;
          conn.end();
          resolve(exitCode);
        })
          .on('end', function() {
            conn.end();
            resolve('end');
          })
          .stderr.on('data', function(data) {
          console.log('STDERR: ' + data);
          conn.end();
          resolve(data);
        });

      });
    })
      .on('keyboard-interactive',
        function(name, instructions, instructionsLang, prompts, finish) {
          // Pass answers to `prompts` to `finish()`. Typically `prompts.length === 1`
          // with `prompts[0] === "Password: "`
          console.log('pass before finish is ', pass);
          finish([pass]);
        }).on('ready', function() {
    }).connect({
      host: lanIP,
      port: 22,
      username: user,
      password: pass,
      readyTimeout: 99999,
      tryKeyboard: true // this attempts keyboard-interactive auth
    });
  };
}


答:
You need other way to assign the event to your new HTML elements.

This way assign an event to any dynamic HTML element.

```<code>$(function() {

  //Assign event to input submit with name izmena_proizvoda_potvrda
  $(document).on('click', 'input[name=izmena_proizvoda_potvrda]',
    function(e) {
      e.preventDefault();
      //Ajax request

    }); //end function()

})
</code>```

Title: Ajax double forms, first form with select then classic form

Body:
You need other way to assign the event to your new HTML elements.

This way assign an event to any dynamic HTML element.

$(function() {

  //Assign event to input submit with name izmena_proizvoda_potvrda
  $(document).on('click', 'input[name=izmena_proizvoda_potvrda]',
    function(e) {
      e.preventDefault();
      //Ajax request

    }); //end function()

})


问:
AngularFIRE Property 'subscribe' does not exist on type 'AngularFireList<{}>'
I'm following this tutorial about how to connect angular with firebase database. But in minute 17:30 I'm getting this error:

Property 'subscribe' does not exist  on type 'AngularFireList<{}>'

my AppComponent:

```<code>import { Component } from '@angular/core';
import {AngularFireDatabase, AngularFireDatabaseModule} from 'angularfire2/database';

import {AngularFireAuth, AngularFireAuthModule} from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
import { Country } from './models/country';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  countries: any[];

  constructor(db: AngularFireDatabase )
  {
     db.list('/Country/countries')
     .subscribe(countries => { //  <--ERROR IS HERE
      this.countries = countries;
      console.log(this.countries);
      });
  }
}
</code>```

My model:

```<code>export class Country {
     // --ATTRIB--
     id: string;
     name: string;
     code: string;
     urlFlag: string;
}
</code>```

Cant find anything about this error. I'm beginner in angular. Thanks if can help me.

答:
A simpler change would to be add  valueChanges() before .subscribe()

```<code>db.list('/Country/countries').valueChanges().subscribe(countries => {
    this.countries = countries;
    console.log(this.countries);
});
</code>```

Body:
I'm following this tutorial about how to connect angular with firebase database. But in minute 17:30 I'm getting this error:

Property 'subscribe' does not exist  on type 'AngularFireList<{}>'

my AppComponent:

import { Component } from '@angular/core';
import {AngularFireDatabase, AngularFireDatabaseModule} from 'angularfire2/database';

import {AngularFireAuth, AngularFireAuthModule} from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
import { Country } from './models/country';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  countries: any[];

  constructor(db: AngularFireDatabase )
  {
     db.list('/Country/countries')
     .subscribe(countries => { //  <--ERROR IS HERE
      this.countries = countries;
      console.log(this.countries);
      });
  }
}

My model:

export class Country {
     // --ATTRIB--
     id: string;
     name: string;
     code: string;
     urlFlag: string;
}

Cant find anything about this error. I'm beginner in angular. Thanks if can help me.

Body:
A simpler change would to be add  valueChanges() before .subscribe()

db.list('/Country/countries').valueChanges().subscribe(countries => {
    this.countries = countries;
    console.log(this.countries);
});


问:
Perl print vietnamese characters
I tried to read the vietnamese address from Mysql databases through perl program. But it display some special characters which is not recognize. When i see the string in phpMyAdmin is ok. And using php to retrieve and print the string also no problem. Just only using perl to print out the string will become weird.

Original word

```<code>QL37, Phố Vôi, tt. Vôi, Lạng Giang, Bắc Giang, Vietnam
</code>```

After print become

```<code>QL37, Pho├í Vo├ói, tt. Vo├ói, La├»ng Giang, Ba├⌐c Giang, Vietnam
</code>```

The database structure

```<code>CREATE TABLE `address` (
    `Address_Id` int(11) NOT NULL,
    `Coordinate_Lat` float(15,6) NOT NULL,
    `Coordinate_Long` float(15,6) NOT NULL,
    `Address` varchar(300) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```

Perl Code

```<code>my $sql = "SELECT * FROM `address`";
my $sth = $DBIconnect->prepare($sql);
$sth->execute or die "SQL Error: $DBIconnect::errstr\n";
while (my $row = $sth->fetchrow_hashref) {
    print $row->{'Address'};
}
</code>```

Print Screen

LINK1 - PHPMyAdmin look fine

LINK2 - Retrieve and print out error

答:
You need to add -C to the cmdline. perldoc perlrun

Or add #!/usr/bin/perl -C as first line to enable Unicode output.

Title: Perl print vietnamese characters

Body:
I tried to read the vietnamese address from Mysql databases through perl program. But it display some special characters which is not recognize. When i see the string in phpMyAdmin is ok. And using php to retrieve and print the string also no problem. Just only using perl to print out the string will become weird.

Original word

QL37, Phố Vôi, tt. Vôi, Lạng Giang, Bắc Giang, Vietnam

After print become

QL37, Pho├í Vo├ói, tt. Vo├ói, La├»ng Giang, Ba├⌐c Giang, Vietnam

The database structure

CREATE TABLE `address` (
    `Address_Id` int(11) NOT NULL,
    `Coordinate_Lat` float(15,6) NOT NULL,
    `Coordinate_Long` float(15,6) NOT NULL,
    `Address` varchar(300) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Perl Code

my $sql = "SELECT * FROM `address`";
my $sth = $DBIconnect->prepare($sql);
$sth->execute or die "SQL Error: $DBIconnect::errstr\n";
while (my $row = $sth->fetchrow_hashref) {
    print $row->{'Address'};
}

Print Screen

LINK1 - PHPMyAdmin look fine

LINK2 - Retrieve and print out error