问:
Understanding Generics and Reflection in Java to Make Array Generic
I am trying to model a train with a Java program.

Currently I have four classes:

Train,

BoxCar,

Cargo,

Person.

The BoxCar class has an array of Person and an array of Cargo. A BoxCar can only hold one type so when that type is given from the constructor,

I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set.
They wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code.

How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time.
Can someone map out the right approach to take?

BoxCar:

```<code>class BoxCar {
    String boxType;
    int boxID;
    int count;
    boolean isEmpty;
    Cargo cargo[];
    Person people[];
    int capacity;

    BoxCar(String box_type, int ID, int cap) {
        boxType = box_type;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }
}
</code>```

Person:

```<code>class Person {
    String government_ID, name;
    int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }
}
</code>```

Cargo:

```<code>class Cargo {
    String cargo_ID;
    int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }
}
</code>```

答:
I misunderstood your question previously. Here is what it should be:

```<code>public class BoxCarContents {
    ...
}

public class Person extends BoxCarContents {
    ...
}

public class Cargo extends BoxCarContents {
    ...
}

public class BoxCar<E extends BoxCarContents> {
    E[] contents;

    public BoxCar(int capacity) {
        contents = new E[n];
    }
    ...
}

//Alternative way
public class BoxCar {
    BoxCarContents[] contents;

    public BoxCar(BoxCarContents[] boxContents) {
        contents = boxContents;
    }
    ...
}
</code>```

Basically the <E extends BoxCarContents> means E can be anything that extends BoxCarContents.

Body:
I am trying to model a train with a Java program.

Currently I have four classes:

Train,

BoxCar,

Cargo,

Person.

The BoxCar class has an array of Person and an array of Cargo. A BoxCar can only hold one type so when that type is given from the constructor,

I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set.
They wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code.

How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time.
Can someone map out the right approach to take?

BoxCar:

class BoxCar {
    String boxType;
    int boxID;
    int count;
    boolean isEmpty;
    Cargo cargo[];
    Person people[];
    int capacity;

    BoxCar(String box_type, int ID, int cap) {
        boxType = box_type;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }
}

Person:

class Person {
    String government_ID, name;
    int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }
}

Cargo:

class Cargo {
    String cargo_ID;
    int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }
}

Body:
I misunderstood your question previously. Here is what it should be:

public class BoxCarContents {
    ...
}

public class Person extends BoxCarContents {
    ...
}

public class Cargo extends BoxCarContents {
    ...
}

public class BoxCar<E extends BoxCarContents> {
    E[] contents;

    public BoxCar(int capacity) {
        contents = new E[n];
    }
    ...
}

//Alternative way
public class BoxCar {
    BoxCarContents[] contents;

    public BoxCar(BoxCarContents[] boxContents) {
        contents = boxContents;
    }
    ...
}

Basically the <E extends BoxCarContents> means E can be anything that extends BoxCarContents.


来源: stackexchange

问:
ftp_nlist(): data_accept: SSL/TLS handshake failed
Once upon a time, there was a normalish error in PHP land:

Warning: ftp_nlist(): data_accept: SSL/TLS handshake failed in [path] on line 29

But here's the catch, "line 29" is not the connection or login, note how it referenced the ftp_nlist() function:

```<code>$ftp = ftp_ssl_connect($cred['host'], $cred['port'], 180);
if (!ftp_login($ftp, $cred['user'], $cred['pass'])) {die("Login Failed");}
ftp_pasv($ftp, true);

$files = ftp_nlist($ftp, '');
</code>```

OpenSSL is compiled and enabled in phpinfo() as suggested here:
ftp_login() : SSL/TLS handshake failed

Other posts I've seen all seem to reference error in the ftp_ssl_connect() or ftp_login() commands which work for me. What can I check when ftp_login() returns true?

Or... are there any logs to get more details on what is wrong?

I'm using php 5.3.29. The code does work properly on my desktop (php 7), but I'm hoping I don't have to upgrade the server to 7 for this to work

12-28-2017 update:
Upgrading to 5.6 resolved, so looks like Martin is on point.

答:
The ftp_nlist opens a data connection. That connection needs TLS/SSL handshake too.

As the control connection handshake succeeded, the problem indeed cannot be with an absent TLS/SSL support in PHP. Neither the problem can be with anything like the server and PHP not being able to find a cipher to agree on.

When TLS/SSL handshake on data connection fails after handshake on control connection succeeded, it's quite usually because the client (PHP) did not reuse TLS/SSL session from control connection on the data connection (see Why is session reuse useful in FTPS?). Some servers do require that. PHP supports the reuse only since 5.6.26. See PHP Bug 70195. So make sure you use that version of PHP at least.

ContentLicense: CC BY-SA 4.0

Body:
Once upon a time, there was a normalish error in PHP land:

Warning: ftp_nlist(): data_accept: SSL/TLS handshake failed in [path] on line 29

But here's the catch, "line 29" is not the connection or login, note how it referenced the ftp_nlist() function:

$ftp = ftp_ssl_connect($cred['host'], $cred['port'], 180);
if (!ftp_login($ftp, $cred['user'], $cred['pass'])) {die("Login Failed");}
ftp_pasv($ftp, true);

$files = ftp_nlist($ftp, '');

OpenSSL is compiled and enabled in phpinfo() as suggested here:
ftp_login() : SSL/TLS handshake failed

Other posts I've seen all seem to reference error in the ftp_ssl_connect() or ftp_login() commands which work for me. What can I check when ftp_login() returns true?

Or... are there any logs to get more details on what is wrong?

I'm using php 5.3.29. The code does work properly on my desktop (php 7), but I'm hoping I don't have to upgrade the server to 7 for this to work

12-28-2017 update:
Upgrading to 5.6 resolved, so looks like Martin is on point.

ContentLicense: CC BY-SA 3.0


问:
WPF+PRISM How to make the popup window owner as main window
I am having trouble setting the owner of Popup window to Application Main window.

Here what I did.

Created a Main Window with custom PopupWindow.

```<code><Window x:Class="MainWindow"
    ...

    <Window.Resources>
        <Style x:Key="MessageWindowStyle" TargetType="{x:Type Window}">
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="WindowStyle" Value="None" />
            <Setter Property="ResizeMode" Value="NoResize" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="SnapsToDevicePixels" Value="True" />
            <Setter Property="ShowInTaskbar" Value="False"/>
            <Setter Property="AllowsTransparency" Value="True"/>
        </Style>
    </Window.Resources>

    <i:Interaction.Triggers>
        <interactionRequest:InteractionRequestTrigger SourceObject="{Binding MessageRequest, Mode=OneWay}">
            <interactionRequest:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True" WindowStyle="{StaticResource MessageWindowStyle}" >
                <interactionRequest:PopupWindowAction.WindowContent>
                    <controls:PageCustomPopup />
                </interactionRequest:PopupWindowAction.WindowContent>
            </interactionRequest:PopupWindowAction>
        </interactionRequest:InteractionRequestTrigger>
    </i:Interaction.Triggers>

    ...
</Window>
</code>```

PageCustomPopup.xaml

This is basic xaml for the popup window.

```<code>    <UserControl x:Class="PageCustomPopup"
        ...
    </UserControl>
</code>```

PageCustomPopup.xaml.cs

In this page code-behind, I tried to set the parent, when the popup window is loaded. But it throws exception.

```<code>    public partial class PageCustomPopup : UserControl,  InteractionRequestAware, INotifyPropertyChanged
    {
        public PageCustomPopup()
        {
            Loaded += (sender, args) =>
            {
                try
                {
                    var parentWindow = this.Parent as Window;
                    if (parentWindow != null)
                    {
                        // This line fails with "Cannot set the Owner after the window is displayed."
                        //parentWindow.Owner = Application.Current.MainWindow;

                        // First, default to the main window's dimensions
                        parentWindow.Width = Application.Current.MainWindow.Width;
                        parentWindow.Height = Application.Current.MainWindow.Height;
                        parentWindow.Left = Application.Current.MainWindow.Left;
                        parentWindow.Top = Application.Current.MainWindow.Top;
                    }
                }
            }
        }
    }
</code>```

MainWindow code behind.

```<code>public InteractionRequest<Notification> MessageRequest { get; private set; }

public MainWindow()
{
    ...

    MessageRequest = new InteractionRequest<Notification>();

    ...
}

void Button_OnClick(object sender, EventArgs e)
{
    MessageRequest.Raise(new Notification(){ Title = "Title Text", Content = "Message to Display"});
}
</code>```

When the Custom popup window is displayed, it shows correctly in the center of the main window.

But the issue is, when all the windows are minimized, if the Application icon on the taskbar is clicked, the Application main window is displayed, and inavtive. Cannot select anything.

The popup window is hidden and cannot bring to front.

The only way to bring the Popup window in front, is using "Alt+Tab" keys.

My question is, how to set the Custom popup window owner to Application.Current.MainWindow?
So that, by selecting taskbar icon or Alt+Tab, displays both Mainwindow and popup window.

答:
Just updating @Szabolcs's Answer. Actually, I found some of the functions are not available in my PRISM's version. Also, trivial thing is that my dialog's style was not preserved so this code solved my problem.

```<code>protected override Window GetWindow(INotification notification)
        {
            Window wrapperWindow;
            if (this.WindowContent != null)
            {
                wrapperWindow = new Window();
                if (wrapperWindow == null)
                    throw new NullReferenceException("CreateWindow cannot return null");
                wrapperWindow.Owner = WindowOwner;
                wrapperWindow.DataContext = (object)notification;
                wrapperWindow.Title = notification.Title;
                this.PrepareContentForWindow(notification, wrapperWindow);
            }
            else
                wrapperWindow = this.CreateDefaultWindow(notification);
            return wrapperWindow;
        }
</code>```

Following set of lines was not compiling because (may be due to different version of PRISM's asselblies). So I initialized with   wrapperWindow = new Window() and applied style on Loaded event in behavior class as follows.

```<code>AssociatedObject.Loaded += (sender, e) =>
            {
                // get the window
                Window window = Window.GetWindow((UserControl)sender);
                if (window != null)
                {
                    window.WindowStyle = WindowStyle.None;
                    window.ResizeMode = ResizeMode.NoResize;
                    window.Background = Brushes.Transparent;
                    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                }
            };
</code>```

I had to change the xaml part also because my main windnow element name was not available

```<code><presentBehaviors:PopupChildWindowAction IsModal="False" CenterOverAssociatedObject="True" WindowOwner="{Binding RelativeSource={RelativeSource AncestorType=Window}}">
</code>```

Body:
I am having trouble setting the owner of Popup window to Application Main window.

Here what I did.

Created a Main Window with custom PopupWindow.

<Window x:Class="MainWindow"
    ...

    <Window.Resources>

    </Window.Resources>

        <interactionRequest:InteractionRequestTrigger SourceObject="{Binding MessageRequest, Mode=OneWay}">
            <interactionRequest:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True" WindowStyle="{StaticResource MessageWindowStyle}" >
                <interactionRequest:PopupWindowAction.WindowContent>
                    <controls:PageCustomPopup />
                </interactionRequest:PopupWindowAction.WindowContent>
            </interactionRequest:PopupWindowAction>
        </interactionRequest:InteractionRequestTrigger>

    ...
</Window>

PageCustomPopup.xaml

This is basic xaml for the popup window.

    <UserControl x:Class="PageCustomPopup"
        ...
    </UserControl>

PageCustomPopup.xaml.cs

In this page code-behind, I tried to set the parent, when the popup window is loaded. But it throws exception.

    public partial class PageCustomPopup : UserControl,  InteractionRequestAware, INotifyPropertyChanged
    {
        public PageCustomPopup()
        {
            Loaded += (sender, args) =>
            {
                try
                {
                    var parentWindow = this.Parent as Window;
                    if (parentWindow != null)
                    {
                        // This line fails with "Cannot set the Owner after the window is displayed."
                        //parentWindow.Owner = Application.Current.MainWindow;

                        // First, default to the main window's dimensions
                        parentWindow.Width = Application.Current.MainWindow.Width;
                        parentWindow.Height = Application.Current.MainWindow.Height;
                        parentWindow.Left = Application.Current.MainWindow.Left;
                        parentWindow.Top = Application.Current.MainWindow.Top;
                    }
                }
            }
        }
    }

MainWindow code behind.

public InteractionRequest<Notification> MessageRequest { get; private set; }

public MainWindow()
{
    ...

    MessageRequest = new InteractionRequest<Notification>();

    ...
}

void Button_OnClick(object sender, EventArgs e)
{
    MessageRequest.Raise(new Notification(){ Title = "Title Text", Content = "Message to Display"});
}

When the Custom popup window is displayed, it shows correctly in the center of the main window.

But the issue is, when all the windows are minimized, if the Application icon on the taskbar is clicked, the Application main window is displayed, and inavtive. Cannot select anything.

The popup window is hidden and cannot bring to front.

The only way to bring the Popup window in front, is using "Alt+Tab" keys.

My question is, how to set the Custom popup window owner to Application.Current.MainWindow?
So that, by selecting taskbar icon or Alt+Tab, displays both Mainwindow and popup window.

Body:
Just updating @Szabolcs's Answer. Actually, I found some of the functions are not available in my PRISM's version. Also, trivial thing is that my dialog's style was not preserved so this code solved my problem.

protected override Window GetWindow(INotification notification)
        {
            Window wrapperWindow;
            if (this.WindowContent != null)
            {
                wrapperWindow = new Window();
                if (wrapperWindow == null)
                    throw new NullReferenceException("CreateWindow cannot return null");
                wrapperWindow.Owner = WindowOwner;
                wrapperWindow.DataContext = (object)notification;
                wrapperWindow.Title = notification.Title;
                this.PrepareContentForWindow(notification, wrapperWindow);
            }
            else
                wrapperWindow = this.CreateDefaultWindow(notification);
            return wrapperWindow;
        }

Following set of lines was not compiling because (may be due to different version of PRISM's asselblies). So I initialized with   wrapperWindow = new Window() and applied style on Loaded event in behavior class as follows.

AssociatedObject.Loaded += (sender, e) =>
            {
                // get the window
                Window window = Window.GetWindow((UserControl)sender);
                if (window != null)
                {
                    window.WindowStyle = WindowStyle.None;
                    window.ResizeMode = ResizeMode.NoResize;
                    window.Background = Brushes.Transparent;
                    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                }
            };

I had to change the xaml part also because my main windnow element name was not available

<presentBehaviors:PopupChildWindowAction IsModal="False" CenterOverAssociatedObject="True" WindowOwner="{Binding RelativeSource={RelativeSource AncestorType=Window}}">


问:
Paramiko connection issue
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...

```<code>#connect.py

import user, db
import paramiko, time, os

paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
    def __init__(self):
        #Call DB Functions
        database = db.Database()
        #Set Transport
        self.transport = paramiko.Transport((user.hostname, user.port))

        #User Credentials
        username = user.username
        password = user.password
        self.transport.connect(username = username, password = password)

        self.sftp = paramiko.SFTPClient.from_transport(self.transport)

        print "Set your credentials in user.py for now!"
        msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
        print msg

    def disconnect(self):
        print "Closing connection..."
        self.sftp.close()
        self.transport.close()
        print "Connection closed."
</code>```

Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)

```<code>#main.py

import connect
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        windowWidth = 550
        windowHeight = 350

        self.establishedConnection = ""

        connectButton = self.createButton("&Connect", self.conn)
        disconnectButton = self.createButton("&Disconnect", self.disconnect)
        grid = QtGui.QGridLayout()
        grid.addWidget(connectButton, 3, 3)
        grid.addWidget(disconnectButton, 4, 3)
        grid.addWidget(self.createList(), 1, 0, 1, 4)

        self.setLayout(grid)

        self.resize(windowWidth, windowHeight)
        self.setWindowTitle("FTP Program")

    def conn(self):
        connection = connect.Connection()
        self.establishedConnection = connection

    def disconnect(self):
        self.establishedConnection.disconnect()

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    gui = Window()
    gui.show()
    sys.exit(app.exec_())
</code>```

The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.

Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).

No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.

Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.

Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.

答: You are not calling conn() in the constructor. </p>

ContentLicense: CC BY-SA 2.5

Title: Paramiko connection issue

Body:
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...

#connect.py

import user, db
import paramiko, time, os

paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
    def __init__(self):
        #Call DB Functions
        database = db.Database()
        #Set Transport
        self.transport = paramiko.Transport((user.hostname, user.port))

        #User Credentials
        username = user.username
        password = user.password
        self.transport.connect(username = username, password = password)

        self.sftp = paramiko.SFTPClient.from_transport(self.transport)

        print "Set your credentials in user.py for now!"
        msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
        print msg

    def disconnect(self):
        print "Closing connection..."
        self.sftp.close()
        self.transport.close()
        print "Connection closed."

Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)

#main.py

import connect
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        windowWidth = 550
        windowHeight = 350

        self.establishedConnection = ""

        connectButton = self.createButton("&Connect", self.conn)
        disconnectButton = self.createButton("&Disconnect", self.disconnect)
        grid = QtGui.QGridLayout()
        grid.addWidget(connectButton, 3, 3)
        grid.addWidget(disconnectButton, 4, 3)
        grid.addWidget(self.createList(), 1, 0, 1, 4)

        self.setLayout(grid)

        self.resize(windowWidth, windowHeight)
        self.setWindowTitle("FTP Program")

    def conn(self):
        connection = connect.Connection()
        self.establishedConnection = connection

    def disconnect(self):
        self.establishedConnection.disconnect()

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    gui = Window()
    gui.show()
    sys.exit(app.exec_())

The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.

Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).

No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.

Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.

Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.


问:
SQL left join multiple product id's
I have a SQL table and need to join some data.  In table 2 there a multiple product ID's some with the but with differnt dates.

eg

```<code>Table 1 (Master)
Product
</code>```

left join

Table 2

```<code>Product | Date 1
AA      | 01/01/2018
AA      | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018
AC      | 01/02/2018
</code>```

What im looking for is to have the data looking like:

```<code>Product | Date 1     | Date 2
AA      | 01/01/2018 | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018 | 01/02/2018
</code>```

Any suggestions would be a great help.

Thank you

Chris

答:
```<code>SELECT t1.Product,
   MIN(Date) AS Date1,
   CASE WHEN COUNT(t1.Product) > 1 THEN MAX(Date) END AS Date2
   FROM Table1 AS t1
   LEFT JOIN Table2 AS t2 ON t1.Product = t2.Product
   GROUP BY t1.Product
</code>```

Try not use * in sql queries

Title: SQL left join multiple product id's

Body:
I have a SQL table and need to join some data.  In table 2 there a multiple product ID's some with the but with differnt dates.

eg

Table 1 (Master)
Product

left join

Table 2

Product | Date 1
AA      | 01/01/2018
AA      | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018
AC      | 01/02/2018

What im looking for is to have the data looking like:

Product | Date 1     | Date 2
AA      | 01/01/2018 | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018 | 01/02/2018

Any suggestions would be a great help.

Thank you

Chris

Body:
SELECT t1.Product,
   MIN(Date) AS Date1,
   CASE WHEN COUNT(t1.Product) > 1 THEN MAX(Date) END AS Date2
   FROM Table1 AS t1
   LEFT JOIN Table2 AS t2 ON t1.Product = t2.Product
   GROUP BY t1.Product

Try not use * in sql queries


问:
moving border and background css like teespring
The question is: how to make it work and make the background (that like a border)  moves.

.class
{
    width: 100.431px;
    height: 66.8303px;
    background-image: linear-gradient(90deg,#ddd 50%,#333 0),linear-gradient(90deg,#ddd 50%,#333 0),linear-gradient(180deg,#ddd 50%,#333 0),linear-gradient(180deg,#ddd 50%,#333 0);
    background-size: 8px 1px,8px 1px,1px 8px,1px 8px;
    background-position: 0 0,0 100%,0 0,100% 0;
    background-repeat: repeat-x,repeat-x,repeat-y,repeat-y;
    -webkit-animation: marching-ants-1 .7s;
-webkit-animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
background-position: 16px 0,-16px 100%,0 -16px,100% 16px;
    -webkit-animation-play-state: running;
    animation-play-state: running;

    -webkit-animation: marching-ants-1 .7s;
    animation: marching-ants-1 .7s;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    transform: matrix(1, 0, 0, 1, 182.447, 168.179);
    width: 159.105px;
    height: 83.6429px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br>
<div class="class">
    hello world
</div>
<br></code>```

there is an example in teespring.
I wish to make it work with only css file with no need to Sass or anything else, just css if possible .

答:
I tried to get some lines from compiled less CSS file and it worked.
Just put these lines to style code and I worked.</p>

```<code>@-webkit-keyframes marching-ants-1 {
  0% {
    background-position: 0 0,  0 100%,  0 0,  100% 0;
  }
  100% {
    background-position: 40px 0, -40px 100%, 0 -40px, 100% 40px;
  }
}

@keyframes marching-ants-1 {
  0% {
    background-position: 0 0,  0 100%,  0 0,  100% 0;
  }
  100% {
    background-position: 40px 0, -40px 100%, 0 -40px, 100% 40px;
  }
}
</code>```

Body:
The question is: how to make it work and make the background (that like a border)  moves.

.class
{
    width: 100.431px;
    height: 66.8303px;
    background-image: linear-gradient(90deg,#ddd 50%,#333 0),linear-gradient(90deg,#ddd 50%,#333 0),linear-gradient(180deg,#ddd 50%,#333 0),linear-gradient(180deg,#ddd 50%,#333 0);
    background-size: 8px 1px,8px 1px,1px 8px,1px 8px;
    background-position: 0 0,0 100%,0 0,100% 0;
    background-repeat: repeat-x,repeat-x,repeat-y,repeat-y;
    -webkit-animation: marching-ants-1 .7s;
-webkit-animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
background-position: 16px 0,-16px 100%,0 -16px,100% 16px;
    -webkit-animation-play-state: running;
    animation-play-state: running;

    -webkit-animation: marching-ants-1 .7s;
    animation: marching-ants-1 .7s;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    transform: matrix(1, 0, 0, 1, 182.447, 168.179);
    width: 159.105px;
    height: 83.6429px;
 }

    hello world

there is an example in teespring.
I wish to make it work with only css file with no need to Sass or anything else, just css if possible .

Body:
I tried to get some lines from compiled less CSS file and it worked.
Just put these lines to style code and I worked.

@-webkit-keyframes marching-ants-1 {
  0% {
    background-position: 0 0,  0 100%,  0 0,  100% 0;
  }
  100% {
    background-position: 40px 0, -40px 100%, 0 -40px, 100% 40px;
  }
}

@keyframes marching-ants-1 {
  0% {
    background-position: 0 0,  0 100%,  0 0,  100% 0;
  }
  100% {
    background-position: 40px 0, -40px 100%, 0 -40px, 100% 40px;
  }
}


问:
bootstrap grid system control-group not lining up - Panells
I've been using Bootstrap 3 to design my screens but I'm having an issue with controls NOT starting from the left when using control-group.  Most of the time it works fine, but now and then I get 1 label that simply refuses to start on a new line - and will wrap onto the previous line:

Here is a section of my code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

PPE and Ladders

      Site Specific PPE:

        <input type="checkbox" id="siteSpecificPPE" name="siteSpecificPPE" tabindex=10></input>

      Comments:

        <textarea rows="3" class="form-control" id="PPEComments" name="PPEComments" tabindex=10></textarea>

      Ladder ID:

        <input type="text" class="form-control" id="laddersID" name="laddersID" tabindex=10></input>

      Safety Catches:

        <input type="checkbox" id="safetyCatchesWorking" name="safetyCatchesWorking" tabindex=10></input>

      Warn. Sign:

        <input type="checkbox" id="warningSign" name="warningSign" tabindex=10></input>

      Comments:

        <textarea rows="3" class="form-control" id="equipmentComments" name="equipmentComments" tabindex=1></textarea>

```

In the illustration below you can see the issue.

1

Has anyone got any ideas on how to cure this... driving me potty!

答:
UPDATE:

As you said, you were having margin issues, it was due to the gutter of -15px created on left and right by using class="row".

You need to wrap all your row class inside container/container-fluid class.

Like this:

```<code><div class="container">
   <div class="row">
   </div>
</div>
</code>```

Never forget to add class="row" if you need to align the columns in one line.

Also make sure you sum up the columns to 12 in a row.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

PPE and Ladders

          Site Specific PPE:

            <input type="checkbox" id="siteSpecificPPE" name="siteSpecificPPE" tabindex=10 />

          Comments:

            <textarea rows="3" class="form-control" id="PPEComments" name="PPEComments" tabindex=10></textarea>

          Ladder ID:

            <input type="text" class="form-control" id="laddersID" name="laddersID" tabindex=10 />

          Safety Catches:

            <input type="checkbox" id="safetyCatchesWorking" name="safetyCatchesWorking" tabindex=10></input>

          Warn. Sign:

            <input type="checkbox" id="warningSign" name="warningSign" tabindex=10></input>

          Comments:

            <textarea rows="3" class="form-control" id="equipmentComments" name="equipmentComments" tabindex=1></textarea>

```

Body:
I've been using Bootstrap 3 to design my screens but I'm having an issue with controls NOT starting from the left when using control-group.  Most of the time it works fine, but now and then I get 1 label that simply refuses to start on a new line - and will wrap onto the previous line:

Here is a section of my code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

PPE and Ladders

      Site Specific PPE:

        <input type="checkbox" id="siteSpecificPPE" name="siteSpecificPPE" tabindex=10></input>

      Comments:

        <textarea rows="3" class="form-control" id="PPEComments" name="PPEComments" tabindex=10></textarea>

      Ladder ID:

        <input type="text" class="form-control" id="laddersID" name="laddersID" tabindex=10></input>

      Safety Catches:

        <input type="checkbox" id="safetyCatchesWorking" name="safetyCatchesWorking" tabindex=10></input>

      Warn. Sign:

        <input type="checkbox" id="warningSign" name="warningSign" tabindex=10></input>

      Comments:

        <textarea rows="3" class="form-control" id="equipmentComments" name="equipmentComments" tabindex=1></textarea>

In the illustration below you can see the issue.

1

Has anyone got any ideas on how to cure this... driving me potty!

Body:
UPDATE:

As you said, you were having margin issues, it was due to the gutter of -15px created on left and right by using class="row".

You need to wrap all your row class inside container/container-fluid class.

Like this:

<div class="container">
   <div class="row">
   </div>
</div>

Never forget to add class="row" if you need to align the columns in one line.

Also make sure you sum up the columns to 12 in a row.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="panel panel-primary">
  <div class="panel-heading">
    <h3 class="panel-title">PPE and Ladders</h3>
  </div>
  <div class="panel-body">
    <div class="control-group">
      <div class="container">
        <div class="row">
          <label class="control-label col-xs-3">Site Specific PPE:</label>
          <div class="col-xs-9">
            <input type="checkbox" id="siteSpecificPPE" name="siteSpecificPPE" tabindex=10 />
          </div>
        </div>
      </div>
    </div>
    <div class="control-group">
      <div class="container">
        <div class="row">
          <label class="control-label col-xs-3">Comments:</label>
          <div class="col-xs-9">
            <textarea rows="3" class="form-control" id="PPEComments" name="PPEComments" tabindex=10></textarea>
          </div>
        </div>
      </div>
    </div>
    <div class="control-group">
      <div class="container">
        <div class="row">
          <label class="control-label col-xs-3">Ladder ID:</label>
          <div class="col-xs-2">
            <input type="text" class="form-control" id="laddersID" name="laddersID" tabindex=10 />

          </div>
          <label class="control-label col-xs-3">Safety Catches:</label>
          <div class="col-xs-1">
            <input type="checkbox" id="safetyCatchesWorking" name="safetyCatchesWorking" tabindex=10></input>
          </div>
          <label class="control-label col-xs-2">Warn. Sign:</label>
          <div class="col-xs-1">
            <input type="checkbox" id="warningSign" name="warningSign" tabindex=10></input>
          </div>
        </div>
      </div>
    </div>
    <div class="control-group">
      <div class="container">
        <div class="row">
          <label class="control-label col-xs-3">Comments:</label>
          <div class="col-xs-9">
            <textarea rows="3" class="form-control" id="equipmentComments" name="equipmentComments" tabindex=1></textarea>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- panel-body -->
</div>
<!-- panel panel-primary -->


问:
How to simulate button clicking by using Shortcut?
I have a kind of handmade button:

```<code>Rectangle {

    // ...

    Text {
        // ...
    }

    Shortcut {
        sequence: if (number!=12) "F"+number
        onActivated: (valve.opened) ? valve.open() : valve.close()
    }

    MouseArea {
        anchors.fill: parent
        onClicked: (valve.opened) ? valve.open() : valve.close()
        onPressed: parent.color = (valve.opened) ? "forestgreen" : "grey"
        onReleased: parent.color = (valve.opened) ? "lightgreen" : "#A8A8A8"
    }
}
</code>```

Pressing this button with a mouse changes the button's background color, and releasing returns its natural color (looks like a behavior of an usual button).

The button also has its shortcut. How can I add similar behavior to Shortcut, that is, to change a button's color while I'm pressing some keyboard shortcut, then changing color after releasing the button? Now it just performs the action of this button.

答: Shortcuts are just triggered (multiple times) and do not have a notion of being pressed. You should implement it yourself using Keys.onPressed and Keys.onReleased, see Keys for more information.

Body:
I have a kind of handmade button:

Rectangle {

    // ...

    Text {
        // ...
    }

    Shortcut {
        sequence: if (number!=12) "F"+number
        onActivated: (valve.opened) ? valve.open() : valve.close()
    }

    MouseArea {
        anchors.fill: parent
        onClicked: (valve.opened) ? valve.open() : valve.close()
        onPressed: parent.color = (valve.opened) ? "forestgreen" : "grey"
        onReleased: parent.color = (valve.opened) ? "lightgreen" : "#A8A8A8"
    }
}

Pressing this button with a mouse changes the button's background color, and releasing returns its natural color (looks like a behavior of an usual button).

The button also has its shortcut. How can I add similar behavior to Shortcut, that is, to change a button's color while I'm pressing some keyboard shortcut, then changing color after releasing the button? Now it just performs the action of this button.


问:
Count by day and uniqueness
Have the following table

Table A

```<code>ID   Username   Role  SYS_CREATION_DATE
</code>```

In that table a username can be there multiple times with different rows.   So data could be:

```<code>ID   Username   Role  SYS_CREATION_DATE
--------------------------------------------------
1    JoeSmuck    5    4-DEC-2017 08.00.00000000 AM
2    JoeSmuck    4    4-DEC-2017 08.00.00000000 AM
3    MaryLamb    5    4-DEC-2017 08.00.00000000 AM
4    MaryLamb    4    4-DEC-2017 08.00.00000000 AM
5    MickeyM     5    4-DEC-2017 08.00.00000000 AM
6    MickeyM     4    4-DEC-2017 08.00.00000000 AM
</code>```

Trying to figure out the SQL statement to find that for the 4th of Dec, three users are registered

答:
Your date looks like it has a time component.  You should get rid of it.  The following works in some databases:

```<code>select trunc(sys_creation_date), count(distinct username)
from t
group by trunc(sys_creation_date);
</code>```

Different databases have different functions for removing the time component.

Title: Count by day and uniqueness

Body:
Have the following table

Table A

ID   Username   Role  SYS_CREATION_DATE

In that table a username can be there multiple times with different rows.   So data could be:

ID   Username   Role  SYS_CREATION_DATE
--------------------------------------------------
1    JoeSmuck    5    4-DEC-2017 08.00.00000000 AM
2    JoeSmuck    4    4-DEC-2017 08.00.00000000 AM
3    MaryLamb    5    4-DEC-2017 08.00.00000000 AM
4    MaryLamb    4    4-DEC-2017 08.00.00000000 AM
5    MickeyM     5    4-DEC-2017 08.00.00000000 AM
6    MickeyM     4    4-DEC-2017 08.00.00000000 AM

Trying to figure out the SQL statement to find that for the 4th of Dec, three users are registered

Body:
Your date looks like it has a time component.  You should get rid of it.  The following works in some databases:

select trunc(sys_creation_date), count(distinct username)
from t
group by trunc(sys_creation_date);

Different databases have different functions for removing the time component.


问:
Passing sub document to view
in my schema where i have company with sub document PostedJobs of type array
all companies of are passed to user view

Get Company

```<code>router.get('/',  isLoggedIn ,  function(req, res, next) {
    Company.find({'Creator': req.user.id}).then(function(companies) {
        res.render('Company', { "Companies" : companies });
    });
});
</code>```

after getting a specific company i get that company by name which is unique

```<code>router.get('/:name' , isLoggedIn , function(req , res , next) {
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
        res.render('dashboard',{
            "Company" : Company
        });
    });
});
</code>```

with this view i want to also pass PostedJob into company view

答:
The Sub document is present in page and you can access it as i access it as following </p>

```<code><% Company.PostedJobs.forEach(function(Job ,index){%>
                                  <tr>
                                   <td><%= index+1 %></td>
                                  <td><%=Job.JobName %></td>
                                  <td><%=Job.JobType %></td>
                                  <td><%=Job.JobLocation %></td>
                                  <td><%=Job.JobSalary %></td>
                                  </tr>
                                <%}) %>
</code>```

Title: Passing sub document to view

Body:
in my schema where i have company with sub document PostedJobs of type array
all companies of are passed to user view

Get Company

router.get('/',  isLoggedIn ,  function(req, res, next) {
    Company.find({'Creator': req.user.id}).then(function(companies) {
        res.render('Company', { "Companies" : companies });
    });
});

after getting a specific company i get that company by name which is unique

router.get('/:name' , isLoggedIn , function(req , res , next) {
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
        res.render('dashboard',{
            "Company" : Company
        });
    });
});

with this view i want to also pass PostedJob into company view

Body:
The Sub document is present in page and you can access it as i access it as following

<% Company.PostedJobs.forEach(function(Job ,index){%>
                                  <tr>
                                   <td><%= index+1 %></td>
                                  <td><%=Job.JobName %></td>
                                  <td><%=Job.JobType %></td>
                                  <td><%=Job.JobLocation %></td>
                                  <td><%=Job.JobSalary %></td>
                                  </tr>
                                <%}) %>


问:
How does one make a horizontal listbox in .NET
I am working on porting a VB6 application to .NET and one of the desired UI elements is a horizontal listbox. I can't seem to figure out how to replicate this in .NET.

Can this be done with basic winforms?

How would you replicate this?

Sample:

The VB6 code that will replicate the above image:

```<code>Private Sub Form_Load()
    lst_horizontal(1).FontSize = 6
    Dim iMaxChoices As Integer
    iMaxChoices = 10
    For i = 1 To iMaxChoices
        lst_horizontal(1).AddItem (" " + CStr(i))
    Next i
End Sub

Private Sub lst_horizontal_Click(Index As Integer)
    Dim iMaxChoices As Integer
    iMaxChoices = 10

    For i = 0 To iMaxChoices - 1

        If lst_horizontal(1).Selected(i) Then
            Debug.Print ("Item " + CStr(i + 1) + " selected")
        End If

    Next i
</code>```

Weasel words: I can figure out how to replicate this in Silverlight/XAML, but this app can't be done in that fashion.

答:
I would suggest the ListView with LargIcon for View property, It might be a good and ready solution for your case.

Good luck!

Body:
I am working on porting a VB6 application to .NET and one of the desired UI elements is a horizontal listbox. I can't seem to figure out how to replicate this in .NET.

Can this be done with basic winforms?

How would you replicate this?

Sample:

The VB6 code that will replicate the above image:

Private Sub Form_Load()
    lst_horizontal(1).FontSize = 6
    Dim iMaxChoices As Integer
    iMaxChoices = 10
    For i = 1 To iMaxChoices
        lst_horizontal(1).AddItem (" " + CStr(i))
    Next i
End Sub

Private Sub lst_horizontal_Click(Index As Integer)
    Dim iMaxChoices As Integer
    iMaxChoices = 10

    For i = 0 To iMaxChoices - 1

        If lst_horizontal(1).Selected(i) Then
            Debug.Print ("Item " + CStr(i + 1) + " selected")
        End If

    Next i

Weasel words: I can figure out how to replicate this in Silverlight/XAML, but this app can't be done in that fashion.


问:
What is the difference between if( pointer == NULL) and if(!pointer)?
What is the difference in between using:

```<code>if( pointer == NULL)
</code>```

And

```<code>if(!pointer)
</code>```

I am concerned with the differences between the two in respect to the following points:

 1. Are they different for the compiler? If yes, then how?

 2. Which of the two is the recommended coding style for general use and why?

 3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.

答:
Are they different for the compiler? If yes, then how?

If pointer indeed has a pointer type, then there is no difference at all for the compiler.

Which of the two is the recommended coding style for general use and why?

There probably are recommendations either way.

A possible advantage of using !pointer is that there is no opportunity to mistype pointer = NULL, which has very different meaning, but is well-formed. Another advantage is that is requires less typing.

Can you please explain how NULL is "seen" by the compiler.

As specified in the standard, NULL is an implementation defined macro, which expands to a null pointer constant.

Body:
What is the difference in between using:

if( pointer == NULL)

And

if(!pointer)

I am concerned with the differences between the two in respect to the following points:

 1. Are they different for the compiler? If yes, then how?

 2. Which of the two is the recommended coding style for general use and why?

 3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.


问:
Looping through elements not working
I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

Stripped down code below.

HTML

```<code><div class="list">
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="2"></div>
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="1"></div>
</div>
</code>```

JS (event is tied to the target class):

```<code>if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}
</code>```

Clearly, I don't know how to loop through it properly. What's the solution?

答:
You could probably use a one-liner:</p>

```<code>if ($(this).closest('.list').find('.target[data-post-id=' + $(this).data("post-id") + ']').not(this).length > 0) {
// there was at least one other element in the list with the same data-post-id as the clicked element
}
</code>```

Title: Looping through elements not working

Body:
I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

Stripped down code below.

HTML

JS (event is tied to the target class):

if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}

Clearly, I don't know how to loop through it properly. What's the solution?

Body:
You could probably use a one-liner:

if ($(this).closest('.list').find('.target[data-post-id=' + $(this).data("post-id") + ']').not(this).length > 0) {
// there was at least one other element in the list with the same data-post-id as the clicked element
}


问:
How to make a Bootstrap page?
I must make a webpage using Bootstrap.

These are the requirements:

1 page in bootstrap. We have attached a handmade sketch. The page will have a list. In each list, there will be a title, 8 text fields in the group of 2 divided into 4 parts.

For example, FirstName: Oracle(2 fields), LastName: Maven (2 fields), and so on, an image slider, which can have minimum 1 and maximum 3 images in it. We can view the image on a big scale and zoom in zoom out the image. Below the slider will be Approve and Reject button which will be visible ONLY at the last Image. The right side of the section will contain 11 Input fields along with the labels. all are optional. Below the 11 fields will be a submit button. This will repeat like a list.

This is the sketch:

I don't understand how to do the lists.
I would be very grateful if you could help me.

答:
If you didn't use Bootstrap and don't know how it's function better download some tool for making bootstrap sites or if you are familiar download a template.

Take a look on Pingendo, it's a drag and drop desktop application (you also have web) and just pick which element you want and drop it on the page...

Title: How to make a Bootstrap page?


问:
Java Generics - method which accept different generic interfaces
Say I have this code:

```<code>IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...
</code>```

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

```<code>void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}
</code>```

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

答:
I'm assuming your Operation classes and interfaces look something like this:

```<code>interface IOperation<T> {
    public List<T> processList(List<T> list);
    public List<T> getList();
}

interface ITotallyDifferentOperation<T> {
    public List<T> processList(List<T> list);
    public List<T> getList();
}

class MyOperation<T> implements IOperation<T> {
    public List<T> processList(List<T> list) {return null;}
    public List<T> getList() {return null;}
}

class MyTotallyDifferentOperation<T> implements ITotallyDifferentOperation<T> {
    public List<T> processList(List<T> list) {return null;}
    public List<T> getList() {return null;}
}
</code>```

And that the error you get is something like this:

```<code>void myMethod(final IOperation<?> parameter1,
final ITotallyDifferentOperation<?> parameter2) {
    // COMPILE ERROR: processList() is not applicable for the arguments
    parameter1.processList(parameter2.getList());
}
</code>```

The reason for this compile error is that myMethod() allows the type of parameter1 and parameter2 to be different from each other.

The best option (In my opinion) would be to not wildcard parameter1 and parameter2, and instead ensure that they are the same generic type, like so:

```<code>Operation<T> parameter1 = null;
ITotallyDifferentOperation<T> parameter2 = null;
</code>```

Based on the IOperation interfaces any of these operations would require myMethod() to accept two parameters with the same generic types, like so:

```<code>void <T> myMethod(
final IOperation<T> operation,
final ITotallyDifferentOperation<T> totallyDifferentOperation) {
    operation.processList(totallyDifferentOperation.getList());
}
</code>```

BUT

If you don't want to do any of the above, then you could change both IOperation interfaces processList methods to accept wildcards so that you can leave all the inputs as wildcards, like so:

```<code>interface IOperation<T> {
    public List<T> processList(List<?> list);
    public List<T> getList();
}

interface ITotallyDifferentOperation<T> {
    public List<T> processList(List<?> list);
    public List<T> getList();
}
</code>```

The only issue then is that you wont have any compile-time type guarantee within those methods and you'd have to check them at run-time...

EDIT in response to Malte Hartwig:

Not wildcarding the parameters will not compile, as T cannot be resolved. That's the whole problem: you do not know which type it is

You don't need to know what type it is, just that they are the same type T. I have expanded on my answer here:

```<code>// remove wildcards, use a generic method, rather than deciding Type in a switch statment.
<T> void someMethod(final Class<T> klass, final int DB_OPERATION_TYPE) {
    IOperation<T> parameter1 = new MyOperation<T>();
    ITotallyDifferentOperation<T> parameter2 = new MyTotallyDifferentOperation<T>();

// ... OR ...

<T> void someMethod(final int DB_OPERATION_TYPE, IOperation<T> parameter1,
    ITotallyDifferentOperation<T> parameter2) {

    // ... Other conditions to evaluate before calling the myMethod ...

    switch(DB_OPERATION_TYPE) {
        case 1:
            myMethod(parameter1, parameter2);
            break;
        case 2:
            myOtherMethod(parameter1, parameter2);
            break;
    }
}

<T> void myMethod(final IOperation<T> operation, final ITotallyDifferentOperation<T> totallyDifferentOperation) {
    operation.processList(totallyDifferentOperation.getList());
}

<T> void myOtherMethod(final IOperation<T> operation, final ITotallyDifferentOperation<T> totallyDifferentOperation) {
    // something... ?
}
</code>```

And to call this method:

```<code>final int DB_OPERATION_TYPE = 1;
someMethod(String.class, DB_OPERATION_TYPE);
// OR
someMethod(DB_OPERATION_TYPE, new MyOperation<String>(), MyTotallyDifferentOperation<String>());
</code>```

As for bringing the method call into the switch and ditching the parameters altogether: Op clarified that this is not an option.

Op clarified this in response to you only after my answer had been posted. I have now edited it out of my answer.

Body:
Say I have this code:

IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

Body:
I'm assuming your Operation classes and interfaces look something like this:

interface IOperation<T> {
    public List<T> processList(List<T> list);
    public List<T> getList();
}

interface ITotallyDifferentOperation<T> {
    public List<T> processList(List<T> list);
    public List<T> getList();
}

class MyOperation<T> implements IOperation<T> {
    public List<T> processList(List<T> list) {return null;}
    public List<T> getList() {return null;}
}

class MyTotallyDifferentOperation<T> implements ITotallyDifferentOperation<T> {
    public List<T> processList(List<T> list) {return null;}
    public List<T> getList() {return null;}
}

And that the error you get is something like this:

void myMethod(final IOperation<?> parameter1,
final ITotallyDifferentOperation<?> parameter2) {
    // COMPILE ERROR: processList() is not applicable for the arguments
    parameter1.processList(parameter2.getList());
}

The reason for this compile error is that myMethod() allows the type of parameter1 and parameter2 to be different from each other.

The best option (In my opinion) would be to not wildcard parameter1 and parameter2, and instead ensure that they are the same generic type, like so:

Operation<T> parameter1 = null;
ITotallyDifferentOperation<T> parameter2 = null;

Based on the IOperation interfaces any of these operations would require myMethod() to accept two parameters with the same generic types, like so:

void <T> myMethod(
final IOperation<T> operation,
final ITotallyDifferentOperation<T> totallyDifferentOperation) {
    operation.processList(totallyDifferentOperation.getList());
}

BUT

If you don't want to do any of the above, then you could change both IOperation interfaces processList methods to accept wildcards so that you can leave all the inputs as wildcards, like so:

interface IOperation<T> {
    public List<T> processList(List<?> list);
    public List<T> getList();
}

interface ITotallyDifferentOperation<T> {
    public List<T> processList(List<?> list);
    public List<T> getList();
}

The only issue then is that you wont have any compile-time type guarantee within those methods and you'd have to check them at run-time...

EDIT in response to Malte Hartwig:

Not wildcarding the parameters will not compile, as T cannot be resolved. That's the whole problem: you do not know which type it is

You don't need to know what type it is, just that they are the same type T. I have expanded on my answer here:

// remove wildcards, use a generic method, rather than deciding Type in a switch statment.
<T> void someMethod(final Class<T> klass, final int DB_OPERATION_TYPE) {
    IOperation<T> parameter1 = new MyOperation<T>();
    ITotallyDifferentOperation<T> parameter2 = new MyTotallyDifferentOperation<T>();

// ... OR ...

<T> void someMethod(final int DB_OPERATION_TYPE, IOperation<T> parameter1,
    ITotallyDifferentOperation<T> parameter2) {

    // ... Other conditions to evaluate before calling the myMethod ...

    switch(DB_OPERATION_TYPE) {
        case 1:
            myMethod(parameter1, parameter2);
            break;
        case 2:
            myOtherMethod(parameter1, parameter2);
            break;
    }
}

<T> void myMethod(final IOperation<T> operation, final ITotallyDifferentOperation<T> totallyDifferentOperation) {
    operation.processList(totallyDifferentOperation.getList());
}

<T> void myOtherMethod(final IOperation<T> operation, final ITotallyDifferentOperation<T> totallyDifferentOperation) {
    // something... ?
}

And to call this method:

final int DB_OPERATION_TYPE = 1;
someMethod(String.class, DB_OPERATION_TYPE);
// OR
someMethod(DB_OPERATION_TYPE, new MyOperation<String>(), MyTotallyDifferentOperation<String>());

As for bringing the method call into the switch and ditching the parameters altogether: Op clarified that this is not an option.

Op clarified this in response to you only after my answer had been posted. I have now edited it out of my answer.


问:
C# string manipulation, why this doesn't work?
```<code>int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}
</code>```

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

答:
I think you meant to wrap that with a String.Format call.</p>

```<code>string str = String.Format("test{0}", i);
</code>```

Body:
int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

Body:
I think you meant to wrap that with a String.Format call.

string str = String.Format("test{0}", i);


问:
SQL (BigQuery): How do i use a single value, derived with another query?
This is my query:

```<code>WITH last_transaction AS (
  SELECT
    month
  FROM db.transactions
  ORDER BY date DESC
  LIMIT 1
)
SELECT
  *
FROM db.transactions
-- WHERE month = last_transaction.month
WHERE month = 11
GROUP BY
  id
</code>```

Commented out line doesn't work, but intention is clear, i assume: i need to select transactions for the latest month. Business logic might not make sense, because i've extracted it from a bigger query. The main question is: how do i use a single value, derived with another query.

答:
You have only one row, so you can use a scalar subquery:

```<code>SELECT t.*
FROM db.transactions t
WHERE month = (SELECT last_transaction.month FROM last_transaction);
</code>```

I removed the GROUP BY id because it would be a syntax error in BigQuery and it logically does not make sense.  Why would a column called id be duplicated in the table?

However, this query would often be written as:

```<code>SELECT t.*
FROM (SELECT t.*, MAX(month) OVER () as max_month
      FROM db.transactions t
WHERE month = max_month;
</code>```

Body:
This is my query:

WITH last_transaction AS (
  SELECT
    month
  FROM db.transactions
  ORDER BY date DESC
  LIMIT 1
)
SELECT
  *
FROM db.transactions
-- WHERE month = last_transaction.month
WHERE month = 11
GROUP BY
  id

Commented out line doesn't work, but intention is clear, i assume: i need to select transactions for the latest month. Business logic might not make sense, because i've extracted it from a bigger query. The main question is: how do i use a single value, derived with another query.

Body:
You have only one row, so you can use a scalar subquery:

SELECT t.*
FROM db.transactions t
WHERE month = (SELECT last_transaction.month FROM last_transaction);

I removed the GROUP BY id because it would be a syntax error in BigQuery and it logically does not make sense.  Why would a column called id be duplicated in the table?

However, this query would often be written as:

SELECT t.*
FROM (SELECT t.*, MAX(month) OVER () as max_month
      FROM db.transactions t
WHERE month = max_month;


问:
Android systems files ,<resource> and <assets> in particular
I am trying to write a code that lets me programmatically switch a file from one of my resources folders to my assets folder.  I have tried the usual file.renameTo method that has worked so very well for me in the past....but with android it seems to do nothing...

答: The assets and res folders are part of the structure of the .apk file. This isn't something that can be changed by the application on the phone. You can create a folder structure in the phone's file system, but that will need to be accessed from your app by the file access api, not as assets or resource identifiers.</p>


问:
qmake & windows: how to convert backslashes into forward slashes
I am trying to use bison, so I've specified following line:

```<code>bison.commands = bison -d -o ${QMAKE_FILE_PATH}/${QMAKE_FILE_BASE}.parser.cc ${QMAKE_FILE_IN}
</code>```

The problem is that ${QMAKE_FILE_IN} and ${QMAKE_FILE_PATH} contain backslashes which bison doesn't understand.

So how to convert them into forward slashes?

答:
Late but...

```<code>message($$replace(QMAKE_FILE_PATH, \\\\, /))
</code>```

...replaces backslash (needs to be escaped twice, thus the quadruple backslash) by forward slashes.

Body:
I am trying to use bison, so I've specified following line:

bison.commands = bison -d -o ${QMAKE_FILE_PATH}/${QMAKE_FILE_BASE}.parser.cc ${QMAKE_FILE_IN}

The problem is that ${QMAKE_FILE_IN} and ${QMAKE_FILE_PATH} contain backslashes which bison doesn't understand.

So how to convert them into forward slashes?

Body:
Late but...

message($$replace(QMAKE_FILE_PATH, \\\\, /))

...replaces backslash (needs to be escaped twice, thus the quadruple backslash) by forward slashes.


问:
How to import bulk products in Facebook shop?
Im using codeigniter3. Its E-commerce website and have above 7000 products. Facebook shop option don't allow to upload bulk products. its just allow to upload 1 product at a time. Its very hard to upload 7000 products manually.

Kindly give me some sample or right path to achieve this goal.
Thanks.

答:
There is currently no public API for this. You will have to apply for the Alpha here:

https://developers.facebook.com/docs/pages/shops-api

Currently, businesses can create a Shop section on a Page via self-serve Page publishing tools or through select third party eCommerce platforms like Shopify. We're now expanding our alpha test to additional third party eCommerce platforms. Through this API, platforms can offer their merchants the ability to sell products right on their Facebook Page via the same tools they are using to manage their eCommerce business.

Thanks


问:
My applet is not drawing a lisajouss figure but a sine function
I am trying to draw a lisajouss figure but instead my program is just drawing a single sine function, why?

```<code>var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctxt = canvas.getContext('2d');

var x;
var y;
var STARTi = -1000;
var MAXi = 1000;
var yOffset = canvas.height / 2;
var xOffset = canvas.width / 2;
var xAmp = 2;
var yAmp = 3;
var xFreq = 6;
var yFreq = 4;
var phaseDiff = (Math.PI / 2);

//X-Axis
ctxt.beginPath();
ctxt.setLineDash([5, 15]);
ctxt.moveTo(0, canvas.height / 2);
ctxt.lineTo(canvas.width, canvas.height / 2);
ctxt.strokeStyle = "rgba(169,169,169)"
ctxt.stroke();

//y-Axis
ctxt.beginPath();
ctxt.setLineDash([5, 15]);
ctxt.moveTo(canvas.width / 2, 0);
ctxt.lineTo(canvas.width / 2, canvas.height);
ctxt.strokeStyle = "rgba(169,169,169)"
ctxt.stroke();

ctxt.setLineDash([0, 0]);

function xCoord(a) {
  return 100 * (xAmp * Math.sin(xFreq * (0.3 * a * Math.PI / 180)));
}

function yCoord(a) {
  return 100 * (yAmp * Math.sin(yFreq * (0.3 * a * Math.PI / 180)));
}

x = xCoord(STARTi);
y = yCoord(x);
ctxt.beginPath();
ctxt.moveTo(x + xOffset, y + yOffset)

for (i = STARTi; i < MAXi; i++) {

  ctxt.moveTo(x + xOffset, y + yOffset)
  x = xCoord(i);
  y = yCoord(x);
  ctxt.lineTo(x + xOffset, y + yOffset)

}
  ctxt.strokeStyle = "black";
ctxt.stroke();
</code>```

Do I need to change up the way the formulas for the curves are formatted or is there something else wrong, because from what I see, the programm just seems to ignore the xCoord formula and just puts in a normal number.

答:
You're passing the computed x coordinate as the parameter for the y coordinate function, but you should be passing i:

```<code>x = xCoord(STARTi);
y = yCoord(STARTi);
ctxt.beginPath();
ctxt.moveTo(x + xOffset, y + yOffset)

for (i = STARTi; i < MAXi; i++) {

  ctxt.moveTo(x + xOffset, y + yOffset)
  x = xCoord(i);
  y = yCoord(i);
  ctxt.lineTo(x + xOffset, y + yOffset)

}
</code>```

Body:
I am trying to draw a lisajouss figure but instead my program is just drawing a single sine function, why?

var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctxt = canvas.getContext('2d');

var x;
var y;
var STARTi = -1000;
var MAXi = 1000;
var yOffset = canvas.height / 2;
var xOffset = canvas.width / 2;
var xAmp = 2;
var yAmp = 3;
var xFreq = 6;
var yFreq = 4;
var phaseDiff = (Math.PI / 2);

//X-Axis
ctxt.beginPath();
ctxt.setLineDash([5, 15]);
ctxt.moveTo(0, canvas.height / 2);
ctxt.lineTo(canvas.width, canvas.height / 2);
ctxt.strokeStyle = "rgba(169,169,169)"
ctxt.stroke();

//y-Axis
ctxt.beginPath();
ctxt.setLineDash([5, 15]);
ctxt.moveTo(canvas.width / 2, 0);
ctxt.lineTo(canvas.width / 2, canvas.height);
ctxt.strokeStyle = "rgba(169,169,169)"
ctxt.stroke();

ctxt.setLineDash([0, 0]);

function xCoord(a) {
  return 100 * (xAmp * Math.sin(xFreq * (0.3 * a * Math.PI / 180)));
}

function yCoord(a) {
  return 100 * (yAmp * Math.sin(yFreq * (0.3 * a * Math.PI / 180)));
}

x = xCoord(STARTi);
y = yCoord(x);
ctxt.beginPath();
ctxt.moveTo(x + xOffset, y + yOffset)

for (i = STARTi; i < MAXi; i++) {

  ctxt.moveTo(x + xOffset, y + yOffset)
  x = xCoord(i);
  y = yCoord(x);
  ctxt.lineTo(x + xOffset, y + yOffset)

}
  ctxt.strokeStyle = "black";
ctxt.stroke();

Do I need to change up the way the formulas for the curves are formatted or is there something else wrong, because from what I see, the programm just seems to ignore the xCoord formula and just puts in a normal number.

Body:
You're passing the computed x coordinate as the parameter for the y coordinate function, but you should be passing i:

x = xCoord(STARTi);
y = yCoord(STARTi);
ctxt.beginPath();
ctxt.moveTo(x + xOffset, y + yOffset)

for (i = STARTi; i < MAXi; i++) {

  ctxt.moveTo(x + xOffset, y + yOffset)
  x = xCoord(i);
  y = yCoord(i);
  ctxt.lineTo(x + xOffset, y + yOffset)

}


问:
Multiple {n} quantifiers regex
Is it possible to have multiple quantifiers in a regex?
Say I have the following regex:

[A-Z0-9]{44}|[A-Z0-9]{36}|[A-Z0-9]{30}

I want to match any string which is either 30, 36 or 44 chars long. Is it possible to write this shorter in any way? Something like the following:

[A-Z0-9<]{30|36|44}?

Edit: Seeing the answers I assume there is not really a way in which you can write the above shorter. The best solution would be to solve it programmatically I guess. Thanks for the input.

答:
Brief

Note that your regex performs much better than any other answers you'll get on your question, but since your question is actually about simplifying/shortening your regex, you can use this.

Your original regex (38 characters):

```<code>[A-Z0-9]{44}|[A-Z0-9]{36}|[A-Z0-9]{30}
</code>```

Your original regex with modifications so that we can use it to test against multiline input (44 characters):

```<code>^(?:[A-Z0-9]{44}|[A-Z0-9]{36}|[A-Z0-9]{30})$
</code>```

Code

My original regex (32 characters):

```<code>([A-Z0-9]){44}|(?1){36}|(?1){30}
</code>```

My original regex with modifications so that we can use it to test against multiline input (38 characters):

```<code>^(?:([A-Z0-9]){44}|(?1){36}|(?1){30})$
</code>```

See regex in use here

Explanation

([A-Z0-9]){44}|(?1){36}|(?1){30} Match either of the following

([A-Z0-9]){44} Match any character in the set (A-Z or 0-9) exactly 44 times. This also captures a single character in the set into capture group 1. We will later use this capture group through recursion.

(?1){36} Recurse the first subpattern exactly 36 times

(?1){30} Recurse the first subpattern exactly 30 times

Title: Multiple {n} quantifiers regex

Body:
Brief

Note that your regex performs much better than any other answers you'll get on your question, but since your question is actually about simplifying/shortening your regex, you can use this.

Your original regex (38 characters):

[A-Z0-9]{44}|[A-Z0-9]{36}|[A-Z0-9]{30}

Your original regex with modifications so that we can use it to test against multiline input (44 characters):

^(?:[A-Z0-9]{44}|[A-Z0-9]{36}|[A-Z0-9]{30})$

Code

My original regex (32 characters):

([A-Z0-9]){44}|(?1){36}|(?1){30}

My original regex with modifications so that we can use it to test against multiline input (38 characters):

^(?:([A-Z0-9]){44}|(?1){36}|(?1){30})$

See regex in use here

Explanation

([A-Z0-9]){44}|(?1){36}|(?1){30} Match either of the following

([A-Z0-9]){44} Match any character in the set (A-Z or 0-9) exactly 44 times. This also captures a single character in the set into capture group 1. We will later use this capture group through recursion.

(?1){36} Recurse the first subpattern exactly 36 times

(?1){30} Recurse the first subpattern exactly 30 times


问:
What's the difference between EscapeUriString and EscapeDataString?
If only deal with url encoding, I should use EscapeUriString?</p>

答:
Comments in the source address the difference clearly. Why this info isn't brought forward via XML documentation comments is a mystery to me.

EscapeUriString:

This method will escape any character that is not a reserved or
unreserved character, including percent signs. Note that
EscapeUriString will also do not escape a '#' sign.

EscapeDataString:

This method will escape any character that is not an unreserved
character, including percent signs.

So the difference is in how they handle reserved characters. EscapeDataString escapes them; EscapeUriString does not.

According to the RFC, the reserved characters are: :/?#[]@!$&'()*+,;=

For completeness, the unreserved characters are alphanumeric and -._~

Both methods escape characters that are neither reserved nor unreserved.

I disagree with the general notion that EscapeUriString is evil. I think a method that escapes only illegal characters (such as spaces) and not reserved characters is useful. But it does have a quirk in how it handles the % character. Percent-encoded characters (% followed by 2 hex digits) are legal in a URI. I think EscapeUriString would be far more useful if it detected this pattern and avoided encoding % when it's immediately proceeded by 2 hex digits.


问:
Do CSS variables work differently in Microsoft Edge?
I am developing a web site and have optimized it for Firefox and Chrome. The project contains a style sheet called base.css which is included in all the pages, and which contains some global settings and definitions, including a list of variables which I use to store color values like such:

```<code>:root {
    --yellow-1: #fff8e3;
    --yellow-2: #ffe9a9;
}
</code>```

and so on, and calling them like for example:

```<code>.a-class {
    background-color: var(--yellow-2);
}
</code>```

When I look at the page in Edge, all the colors are missing, and when I use the DOM explorer, it marks all uses of the variables with red underlines. Does Edge not support CSS variables in this way? What can I do to work around this?

答:
MS Edge does support CSS variables from EdgeHTML v15:

https://blogs.windows.com/msedgedev/2017/03/24/css-custom-properties/

This is also backed up here:

https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables#Browser_compatibility

The syntax is as follows:

Declaring a variable:

```<code>element {
  --main-bg-color: brown;
}
</code>```

Using the variable:

```<code>element {
  background-color: var(--main-bg-color);
}
</code>```

Body:
I am developing a web site and have optimized it for Firefox and Chrome. The project contains a style sheet called base.css which is included in all the pages, and which contains some global settings and definitions, including a list of variables which I use to store color values like such:

:root {
    --yellow-1: #fff8e3;
    --yellow-2: #ffe9a9;
}

and so on, and calling them like for example:

.a-class {
    background-color: var(--yellow-2);
}

When I look at the page in Edge, all the colors are missing, and when I use the DOM explorer, it marks all uses of the variables with red underlines. Does Edge not support CSS variables in this way? What can I do to work around this?

Body:
MS Edge does support CSS variables from EdgeHTML v15:

https://blogs.windows.com/msedgedev/2017/03/24/css-custom-properties/

This is also backed up here:

https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables#Browser_compatibility

The syntax is as follows:

Declaring a variable:

element {
  --main-bg-color: brown;
}

Using the variable:

element {
  background-color: var(--main-bg-color);
}


问:
SQL Function not working the way I want
I wrote these 2 functions:

```<code>USE muziekdatabase
GO
CREATE FUNCTION fnSpecNivAantal
    (
        @Niveau as char(1)
    )

RETURNS char(1)
AS

BEGIN

    DECLARE @Aantal AS int

    IF @Niveau = 'A'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'A')

    ELSE IF @Niveau = 'B'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'B')

    ELSE IF @Niveau = 'C'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'C')

RETURN @Aantal

END

USE muziekdatabase
GO

ALTER FUNCTION fnHoogsteNummer
    (
        @EersteNummer as numeric,
        @TweedeNummer as numeric
    )
RETURNS numeric
AS
BEGIN

    DECLARE @HoogsteNummer as VARCHAR(MAX)

    IF MAX(@Eerstenummer) > MAX(@TweedeNummer)
    SET @HoogsteNummer = @EersteNummer
    ELSE IF
    MAX(@Tweedenummer) > MAX(@Eerstenummer)
    SET @HoogsteNummer = @TweedeNummer
    ELSE IF
    @EersteNummer = @TweedeNummer
    SET @HoogsteNummer = 'Nummers zijn gelijk'
    ELSE
    SET @HoogsteNummer = 'Er is iets fout gegaan'

    RETURN @HoogsteNummer
END
</code>```

Now they pretty much work like they should. But there's one thing that's not quite right. When I insert a value into my function, the outcome is a whole list with the same answer. Like 10 rows with just a 3, where it only should be 1 row with the number 3. I know I can use DISTINCT, but I think something is wrong with the function. I tried to use CASE / WHEN but that's not working either..

答:
Changing these function to inline table valued functions will offer some performance benefits. They are a little different way to think about functions but well worth the effort. One habit you need to get into is defining the size and precision of your variables and parameters. Do NOT get lazy and do things like numeric. You should be precise and define the size. SQL Server does not automatically adjust the scale and precision to meet the values it finds. On the contrary it uses a default size which may or may not fit with your data.

Your first function can be great simplified to this.

```<code>CREATE FUNCTION fnSpecNivAantal
(
    @Niveau as char(1)
)RETURNS TABLE AS RETURN

    SELECT Niveau = COUNT(*)
    FROM STUK
    WHERE niveaucode = @Niveau
        AND niveaucode IN ('A', 'B', 'C')
</code>```

The second one is a little different. You defined your function as returning a numeric (no scale or precision) but your code can return a numeric or a string literal. This doesn't work because all parts of a function MUST return the same datatype. Not a huge deal you just have to realize that your return datatype is a varchar here and not a number. This function could be converted to an inline table valued function like this.

```<code>ALTER FUNCTION fnHoogsteNummer
    (
        @EersteNummer as numeric, --need to define scale and precision
        @TweedeNummer as numeric --need to define scale and precision
    )
RETURNS TABLE AS RETURN

    SELECT CASE WHEN @Eerstenummer > @TweedeNummer THEN convert(varchar(25), @EersteNummer)
            WHEN @TweedeNummer > @EersteNummer THEN convert(varchar(25), @TweedeNummer)
            WHEN @TweedeNummer = @EersteNummer THEN 'Nummers zijn gelijk'
            ELSE 'Er is iets fout gegaan'
            END
</code>```

Please note that both of these functions are a single statement. This is what makes them an inline table valued function. If you start defining variables and have multiple statements it becomes a multi-statement table valued function and the performance can be even worse than a scalar function.

Title: SQL Function not working the way I want

Body:
I wrote these 2 functions:

USE muziekdatabase
GO
CREATE FUNCTION fnSpecNivAantal
    (
        @Niveau as char(1)
    )

RETURNS char(1)
AS

BEGIN

    DECLARE @Aantal AS int

    IF @Niveau = 'A'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'A')

    ELSE IF @Niveau = 'B'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'B')

    ELSE IF @Niveau = 'C'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'C')

RETURN @Aantal

END

USE muziekdatabase
GO

ALTER FUNCTION fnHoogsteNummer
    (
        @EersteNummer as numeric,
        @TweedeNummer as numeric
    )
RETURNS numeric
AS
BEGIN

    DECLARE @HoogsteNummer as VARCHAR(MAX)

    IF MAX(@Eerstenummer) > MAX(@TweedeNummer)
    SET @HoogsteNummer = @EersteNummer
    ELSE IF
    MAX(@Tweedenummer) > MAX(@Eerstenummer)
    SET @HoogsteNummer = @TweedeNummer
    ELSE IF
    @EersteNummer = @TweedeNummer
    SET @HoogsteNummer = 'Nummers zijn gelijk'
    ELSE
    SET @HoogsteNummer = 'Er is iets fout gegaan'

    RETURN @HoogsteNummer
END

Now they pretty much work like they should. But there's one thing that's not quite right. When I insert a value into my function, the outcome is a whole list with the same answer. Like 10 rows with just a 3, where it only should be 1 row with the number 3. I know I can use DISTINCT, but I think something is wrong with the function. I tried to use CASE / WHEN but that's not working either..

Body:
Changing these function to inline table valued functions will offer some performance benefits. They are a little different way to think about functions but well worth the effort. One habit you need to get into is defining the size and precision of your variables and parameters. Do NOT get lazy and do things like numeric. You should be precise and define the size. SQL Server does not automatically adjust the scale and precision to meet the values it finds. On the contrary it uses a default size which may or may not fit with your data.

Your first function can be great simplified to this.

CREATE FUNCTION fnSpecNivAantal
(
    @Niveau as char(1)
)RETURNS TABLE AS RETURN

    SELECT Niveau = COUNT(*)
    FROM STUK
    WHERE niveaucode = @Niveau
        AND niveaucode IN ('A', 'B', 'C')

The second one is a little different. You defined your function as returning a numeric (no scale or precision) but your code can return a numeric or a string literal. This doesn't work because all parts of a function MUST return the same datatype. Not a huge deal you just have to realize that your return datatype is a varchar here and not a number. This function could be converted to an inline table valued function like this.

ALTER FUNCTION fnHoogsteNummer
    (
        @EersteNummer as numeric, --need to define scale and precision
        @TweedeNummer as numeric --need to define scale and precision
    )
RETURNS TABLE AS RETURN

    SELECT CASE WHEN @Eerstenummer > @TweedeNummer THEN convert(varchar(25), @EersteNummer)
            WHEN @TweedeNummer > @EersteNummer THEN convert(varchar(25), @TweedeNummer)
            WHEN @TweedeNummer = @EersteNummer THEN 'Nummers zijn gelijk'
            ELSE 'Er is iets fout gegaan'
            END

Please note that both of these functions are a single statement. This is what makes them an inline table valued function. If you start defining variables and have multiple statements it becomes a multi-statement table valued function and the performance can be even worse than a scalar function.


问:
how to identify Gmail Account Type using Google API?
I want to identify if the connected Gmail Account is a GSUITE (Paid Account) or a normal Trial account.
Which Gmail/Google API call should i use to identify this?</p>

答:
You can use the Google+ API. All paid accounts require that users register a domain and you can use the Google+ API to detect if a domain is associated with an account (free personal accounts cannot have domains associated with them). </p>

<p>Another way to do it is to check a user's drive storage quota via the Drive API. The free personal account allows a max of 15GB, whereas Google's paid accounts offer 30GB (for GSuite Basic) or unlimited. </p>

Body:
You can use the Google+ API. All paid accounts require that users register a domain and you can use the Google+ API to detect if a domain is associated with an account (free personal accounts cannot have domains associated with them).

Another way to do it is to check a user's drive storage quota via the Drive API. The free personal account allows a max of 15GB, whereas Google's paid accounts offer 30GB (for GSuite Basic) or unlimited.


问:
No implementation for play.modules.reactivemongo.ReactiveMongoApi was bound
I'm working on a back-end project using Scala, the Play Framework, and the IntelliJ IDE just to practice, I'm new to these technologies.

I added the Reactive Mongo dependency to the build.sbt

```<code>libraryDependencies ++= Seq(
  "org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"
)
</code>```

What I get is this error :

```<code>No implementation for play.modules.reactivemongo.ReactiveMongoApi was bound
</code>```

When I hover the mouse on

```<code>"org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"
</code>```

This little text displays:

Unknown artifact. Not resolved or indexed.

What am I doing wrong ?

UPDATE:

When i refresh the project by hitting option + enter on the dependency, the "Event log" shows this :

[warn] Found version conflict(s) in library dependencies; some are suspected to be binary incompatible: [warn] * com.google.guava:guava:22.0 is selected over 19.0 [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 22.0) [warn] +- com.google.inject:guice:4.1.0 (depends on 19.0) [warn] * com.typesafe.akka:akka-stream_2.12:2.5.6 is selected over 2.4.19 [warn] +- com.typesafe.play:play-streams_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-http-core_2.12:10.0.10 (depends on 2.4.19) [warn] * com.typesafe.akka:akka-actor_2.12:2.5.6 is selected over {2.4.14, 2.4.19} [warn] +- com.typesafe.akka:akka-stream_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-slf4j_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-parsing_2.12:10.0.10 (depends on 2.4.19) [warn] +- org.reactivemongo:reactivemongo_2.12:0.12.6 () (depends on 2.4.14) [warn] Run 'evicted' to see detailed eviction warnings

答:
There is no 0.12.6-play26 version of the plugin published in the Maven Central Repository. You probably want version 0.12.7-play26:

```<code>libraryDependencies ++= Seq(
  "org.reactivemongo" %% "play2-reactivemongo" % "0.12.7-play26"
)
</code>```

Body:
I'm working on a back-end project using Scala, the Play Framework, and the IntelliJ IDE just to practice, I'm new to these technologies.

I added the Reactive Mongo dependency to the build.sbt

libraryDependencies ++= Seq(
  "org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"
)

What I get is this error :

No implementation for play.modules.reactivemongo.ReactiveMongoApi was bound

When I hover the mouse on

"org.reactivemongo" %% "play2-reactivemongo" % "0.12.6-play26"

This little text displays:

Unknown artifact. Not resolved or indexed.

What am I doing wrong ?

UPDATE:

When i refresh the project by hitting option + enter on the dependency, the "Event log" shows this :

[warn] Found version conflict(s) in library dependencies; some are suspected to be binary incompatible: [warn] * com.google.guava:guava:22.0 is selected over 19.0 [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 22.0) [warn] +- com.google.inject:guice:4.1.0 (depends on 19.0) [warn] * com.typesafe.akka:akka-stream_2.12:2.5.6 is selected over 2.4.19 [warn] +- com.typesafe.play:play-streams_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-http-core_2.12:10.0.10 (depends on 2.4.19) [warn] * com.typesafe.akka:akka-actor_2.12:2.5.6 is selected over {2.4.14, 2.4.19} [warn] +- com.typesafe.akka:akka-stream_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.play:play_2.12:2.6.7 (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-slf4j_2.12:2.5.6 () (depends on 2.5.6) [warn] +- com.typesafe.akka:akka-parsing_2.12:10.0.10 (depends on 2.4.19) [warn] +- org.reactivemongo:reactivemongo_2.12:0.12.6 () (depends on 2.4.14) [warn] Run 'evicted' to see detailed eviction warnings

Body:
There is no 0.12.6-play26 version of the plugin published in the Maven Central Repository. You probably want version 0.12.7-play26:

libraryDependencies ++= Seq(
  "org.reactivemongo" %% "play2-reactivemongo" % "0.12.7-play26"
)


问:
How to open a test page with a url with a certain domain in path without deploying it to a server?
This seems like a simple question, but I just can't seem to wrap my head around it...

I have a simple html page. All that html page does is looks to see whether a browser cookie is present, and if it is, it will write a message that says "Found the cookie".

In order for this html page to work, it needs to be opened in a browser using a url that uses a specific domain "mytestsite.org" in the path in order to work. So I want to be able to open that page in a browser using a url like "www.mytestsite.org/mytestpage.html". Easy enough...

When I use this test page locally, I just deploy it to a local JBoss server, then make a mapping in my "hosts" file (I'm on Windows XP), that maps my local IP to "local.mytestsite.org". This tricks the browser into thinking that it is actually getting the page from "mytestsite.org", when it is actually being served by my local JBoss server.

I want to give this html file to another person who is going to use it on their pc. However, they don't have any sort of http server installed, so the little host mapping trick won't work. I don't want to make them go through the trouble of installing a server just to get this test page to work. Additionally, I can't physically put this file on "mytestsite.org".

Any thoughts on how I could open this page through a "mytestsite.org" url through a browser, without actually having it deployed to a server?

答: Is your test machine with JBoss installed accessible from the Internet? If so, you may ask the other person to add a mapping to their hosts file, that maps local.mytextsite.org to the public IP of your test machine.


问:
How to pass parameter to a function
I am new to javascript. In the below posted code, I created a function caleed "func", but as shown it does not accept any parameters. what i want to is, to make "func" accepts a parameter
that should be passed to "fs.readdir". in other words, it should be something like the following:

```<code>var func(path) = fs.readdir(path, (err, file)......);
</code>```

so that, each time i call func with a different parameter, fs.readdir should be called with the new parameter

how can i do that.

code:

```<code>var func = fs.readdir(p, (err, files) => {
if (err) {
console.log('ERROR: ' + err.message);
} else {
    files.filter( (file)=> {
      console.log(file + '____' + fs.statSync(file).size);
    });
  }
});
</code>```

答:
Since you're using ES6 :

```<code>const func = path => fs.readdir(path, (err, files) => {
        // ...
    });

func("somePath") // and call it like this
</code>```

In ES5 that would be :

```<code>var func = function(path) {
    fs.readdir(path, (err, files) => {
        // ...
    });
}

func("somePath") // and call it like this
</code>```

If you want to pass multiple arguments :

```<code>const func = (path, arg2, arg3) => fs.readdir(path, (err, files) => {
        console.log(arg2, arg3) // "Second argument", "Third argument"
    });

func("somePath", "Second argument", "Third argument") // and call it like this
</code>```

Title: How to pass parameter to a function

Body:
I am new to javascript. In the below posted code, I created a function caleed "func", but as shown it does not accept any parameters. what i want to is, to make "func" accepts a parameter
that should be passed to "fs.readdir". in other words, it should be something like the following:

var func(path) = fs.readdir(path, (err, file)......);

so that, each time i call func with a different parameter, fs.readdir should be called with the new parameter

how can i do that.

code:

var func = fs.readdir(p, (err, files) => {
if (err) {
console.log('ERROR: ' + err.message);
} else {
    files.filter( (file)=> {
      console.log(file + '____' + fs.statSync(file).size);
    });
  }
});

Body:
Since you're using ES6 :

const func = path => fs.readdir(path, (err, files) => {
        // ...
    });

func("somePath") // and call it like this

In ES5 that would be :

var func = function(path) {
    fs.readdir(path, (err, files) => {
        // ...
    });
}

func("somePath") // and call it like this

If you want to pass multiple arguments :

const func = (path, arg2, arg3) => fs.readdir(path, (err, files) => {
        console.log(arg2, arg3) // "Second argument", "Third argument"
    });

func("somePath", "Second argument", "Third argument") // and call it like this