问:
C# Asynchronous Chat Server
I'm trying to build an Asynchronous Chat Server and this is what I got so far:

Server

```<code>using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);

public AsynchronousSocketListener()
{
}

public static void StartListening()
{
    byte[] bytes = new Byte[1024];
    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true)
        {
            allDone.Reset();
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
            allDone.WaitOne();
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

public static void AcceptCallback(IAsyncResult ar)
{
    allDone.Set();
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
    String content = String.Empty;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {
        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
        content = state.sb.ToString();
        if (content.IndexOf("<EOF>") > -1)
        {
            Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
            Send(handler, content);
        }
        else
        {
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
        }
    }
}

private static void Send(Socket handler, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to client.", bytesSent);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartListening();
    return 0;
}
}
</code>```

Client

```<code>using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    private const int port = 11000;
    private static ManualResetEvent connectDone =new ManualResetEvent(false);
    private static ManualResetEvent sendDone =new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =new ManualResetEvent(false);
    private static String response = String.Empty;
    static String username = "";
    static int a = 1;

private static void StartClient()
{
    try
    {
        Console.WriteLine("Username: ");
        username = Console.ReadLine();

        while (a == 1)
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            Console.WriteLine("Receiver: ");
            String receiver = Console.ReadLine();
            Console.WriteLine("Message: ");
            String message = Console.ReadLine();

            String Message = username + "[" + receiver + "[" + message + "<EOF>";
            Send(client, Message);
            sendDone.WaitOne();
            Receive(client);
            receiveDone.WaitOne();
            Console.WriteLine("Response received : {0}", response);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ConnectCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        client.EndConnect(ar);
        connectDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Receive(Socket client)
{
    try
    {
        StateObject state = new StateObject();
        state.workSocket = client;
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;
        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Send(Socket client, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        int bytesSent = client.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartClient();
    return 0;
}
}
</code>```

I'm able to send messages to the server and get back an answer, but the connection is cut every time and I have to reconnect it and like this I wouldn't be able to get messages after I send one. I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Furthermore I'm looking for a way to send messages from one client to another one and to send a message to all clients, who are connected to the server.

Another Question I have, how can I set up multiple ports and let the server listen to all ports? I wanted to open one port for the login and one port for the messages.

答:
but the connection is cut every time

because your explicitly close it in SendCallback

```<code>Socket handler = (Socket) ar.AsyncState;
handler.Shutdown(SocketShutdown.Both);
handler.Close();
</code>```

You may call handler.BeginReceive instead

Title: C# Asynchronous Chat Server

Body:
I'm trying to build an Asynchronous Chat Server and this is what I got so far:

Server

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);

public AsynchronousSocketListener()
{
}

public static void StartListening()
{
    byte[] bytes = new Byte[1024];
    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true)
        {
            allDone.Reset();
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
            allDone.WaitOne();
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

public static void AcceptCallback(IAsyncResult ar)
{
    allDone.Set();
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
    String content = String.Empty;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {
        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
        content = state.sb.ToString();
        if (content.IndexOf("<EOF>") > -1)
        {
            Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
            Send(handler, content);
        }
        else
        {
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
        }
    }
}

private static void Send(Socket handler, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to client.", bytesSent);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartListening();
    return 0;
}
}

Client

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    private const int port = 11000;
    private static ManualResetEvent connectDone =new ManualResetEvent(false);
    private static ManualResetEvent sendDone =new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =new ManualResetEvent(false);
    private static String response = String.Empty;
    static String username = "";
    static int a = 1;

private static void StartClient()
{
    try
    {
        Console.WriteLine("Username: ");
        username = Console.ReadLine();

        while (a == 1)
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            Console.WriteLine("Receiver: ");
            String receiver = Console.ReadLine();
            Console.WriteLine("Message: ");
            String message = Console.ReadLine();

            String Message = username + "[" + receiver + "[" + message + "<EOF>";
            Send(client, Message);
            sendDone.WaitOne();
            Receive(client);
            receiveDone.WaitOne();
            Console.WriteLine("Response received : {0}", response);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ConnectCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        client.EndConnect(ar);
        connectDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Receive(Socket client)
{
    try
    {
        StateObject state = new StateObject();
        state.workSocket = client;
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;
        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Send(Socket client, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        int bytesSent = client.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartClient();
    return 0;
}
}

I'm able to send messages to the server and get back an answer, but the connection is cut every time and I have to reconnect it and like this I wouldn't be able to get messages after I send one. I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Furthermore I'm looking for a way to send messages from one client to another one and to send a message to all clients, who are connected to the server.

Another Question I have, how can I set up multiple ports and let the server listen to all ports? I wanted to open one port for the login and one port for the messages.

Body:
but the connection is cut every time

because your explicitly close it in SendCallback

Socket handler = (Socket) ar.AsyncState;
handler.Shutdown(SocketShutdown.Both);
handler.Close();

You may call handler.BeginReceive instead


来源: stackexchange

问:
Multiple $scope.$watch not working in Angular JS
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)</p>

```<code>$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});
</code>```

答: Thank you all. To answer, the issue was in my html rendering of the results and the root cause was my own idiocy. I has an extraneous ng-show which was hiding the results.</p>

ContentLicense: CC BY-SA 3.0

Body:
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)

$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});


问:
ReactJS: lifting the parameter several levels up?
I want to upstream the key of the component on change. I.e., I write

```<code> onChange= {(e) => this.props.onChange(e, key)}
</code>```

However, in my case this.props.onChange also points in its turn to its props.onChange function. I've tried to define all the hierarchically "upper" assignments as onChange={this.props.onChange} as well as onChange={(e,key) => this.props.onChange(e,key)}, but nothing helps the fact that key is undefined when it comes to the actual function body.

Here's the full code of that what has to do with the peoblem:

```<code>handleValueChange = (e, key) => {
    console.log('Event was on ' + key);
    let currElemData = this.state.currentElementsData.slice();
    currElemData[key] = {value: e.target.value};
    this.setState({currentElementsData: currElemData});
};
addFilter = () => {
    let activeFiltersNow = this.state.activeFilterElements.slice();
    activeFiltersNow.push(<Filter key={this.state.filterCounter} onSelect={(e, key) => this.handleReferenceSelection(e, key)}
                                  onChange={(e,key) =>this.handleValueChange(e, key)}/>);
    let currElemData = this.state.currentElementsData.slice();
    currElemData.push(InitialHelper.getInitialFilterData());
    this.setState({activeFilterElements: activeFiltersNow, currentElementsData: currElemData, filterCounter: this.state.filterCounter++});
};
</code>```

...

```<code>class Filter extends Component {
    render() {
        return <div className="filterContainer">
            {this.props.isFirst? '':<FilterPrefix />}
            <FilterReference onSelect={(e,key) => this.props.onSelect(e,key)} key={this.props.key}/>
            <FilterAssignment />
            <FilterValue onChange={(e,key) => this.props.onChange(e,key)} key={this.props.key}/>
            <DeleteFilterButton />
        </div>
    }
}
</code>```

...

```<code>class FilterValue extends Component{
    render() {
        return <input onChange={(e) => this.props.onChange(e,this.props.key)} key={this.props.key}/>
    }
    loadSuggestions(reference) {
    }
}
</code>```

答:
I'm not quite sure what you are trying to do here, but I've noticed that you are falling for a pretty common ReactJs pitfall which is that:

Keys serve as a hint to React but they don't get passed to your
  components. If you need the same value in your component, pass it
  explicitly as a prop with a different name

meaning that this.props.key will always be undefined. So, I'm afraid that all the instances in where you are using this.props.key are not going to behave as you expect...

Body:
I want to upstream the key of the component on change. I.e., I write

 onChange= {(e) => this.props.onChange(e, key)}

However, in my case this.props.onChange also points in its turn to its props.onChange function. I've tried to define all the hierarchically "upper" assignments as onChange={this.props.onChange} as well as onChange={(e,key) => this.props.onChange(e,key)}, but nothing helps the fact that key is undefined when it comes to the actual function body.

Here's the full code of that what has to do with the peoblem:

handleValueChange = (e, key) => {
    console.log('Event was on ' + key);
    let currElemData = this.state.currentElementsData.slice();
    currElemData[key] = {value: e.target.value};
    this.setState({currentElementsData: currElemData});
};
addFilter = () => {
    let activeFiltersNow = this.state.activeFilterElements.slice();
    activeFiltersNow.push(<Filter key={this.state.filterCounter} onSelect={(e, key) => this.handleReferenceSelection(e, key)}
                                  onChange={(e,key) =>this.handleValueChange(e, key)}/>);
    let currElemData = this.state.currentElementsData.slice();
    currElemData.push(InitialHelper.getInitialFilterData());
    this.setState({activeFilterElements: activeFiltersNow, currentElementsData: currElemData, filterCounter: this.state.filterCounter++});
};

...

class Filter extends Component {
    render() {
        return

            {this.props.isFirst? '':<FilterPrefix />}
            <FilterReference onSelect={(e,key) => this.props.onSelect(e,key)} key={this.props.key}/>
            <FilterAssignment />
            <FilterValue onChange={(e,key) => this.props.onChange(e,key)} key={this.props.key}/>
            <DeleteFilterButton />

    }
}

...

class FilterValue extends Component{
    render() {
        return <input onChange={(e) => this.props.onChange(e,this.props.key)} key={this.props.key}/>
    }
    loadSuggestions(reference) {
    }
}


问:
trouble making an "if" statment with time.now on ruby on rails
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

```<code><% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

答:
try:

```<code><% if Time.now >= Time.parse("7:00") and Time.now <= Time.parse("14:00") %>
  Good Morning <%= current_user.nome %>! <br>
<% else %>
  Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

Note: Time.now  will return time object while "7:00" is a string, so you need to convert string time to time object and can compare.

Body:
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

<% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>!

<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

Body:
try:

<% if Time.now >= Time.parse("7:00") and Time.now <= Time.parse("14:00") %>
  Good Morning <%= current_user.nome %>! <br>
<% else %>
  Good Afternoon <%= current_user.nome %>!
<% end %>

Note: Time.now  will return time object while "7:00" is a string, so you need to convert string time to time object and can compare.


问:
Does PetaPoco's Query(string query, parameters) method protect from SQL injection?
In PetaPoco's home page there is a mention that PetaPoco's SQL Builder (Sql object) protects from SQL injection. But does Query(string query, parameters) method protect from SQL injection?

SQL Builder is safe:

```<code>var id = 123;
var a = db.Query<article>(PetaPoco.Sql.Builder
  .Append("SELECT * FROM articles")
  .Append("WHERE article_id=@0", id)
);
</code>```

But is it safe with string query where parameters are passed like this?

```<code>var id = 123;
var a = db.Query<article>("SELECT * FROM articles WHERE article_id=@0", id);
</code>```

答:
Yes it does protect against SQL injection.

You can verify this, if you aren't sure, by running a SQL Trace on the SQL being executed. Or provide some inputs with a single and a double quote in it (against a nvarchar column) and see whether a runtime exception occurs (which would occur if SQL injection was a problem).

See also https://github.com/CollaboratingPlatypus/PetaPoco/issues/326#issuecomment-238538854 :

this is the correct behaviour. The SQL and parameters are passed to
  the DB Command to prevent injection based attacks. The connected DB
  will put the SQL and parameters together in a safe manner

Body:
In PetaPoco's home page there is a mention that PetaPoco's SQL Builder (Sql object) protects from SQL injection. But does Query(string query, parameters) method protect from SQL injection?

SQL Builder is safe:

var id = 123;
var a = db.Query
(PetaPoco.Sql.Builder
  .Append("SELECT * FROM articles")
  .Append("WHERE article_id=@0", id)
);

But is it safe with string query where parameters are passed like this?

var id = 123;
var a = db.Query
("SELECT * FROM articles WHERE article_id=@0", id);


问:
R - Calculate difference (similarity measure) between similar datasets
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData1:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData2:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

答:
Not quite sure what you mean by "difference", but if you just want to know how much each cell differs from each cell on average (given the matrices are of the same shape and have indentical cols/rows), you could do absolute difference, or use Euclidean distance, or Kolmogorov-Smirnov distance - depending again on what you mean by "difference".</p>

```<code>abs(head(mtcars) - (head(mtcars)*0.5)) # differences by cell
mean( as.matrix(abs(head(mtcars) - (head(mtcars)*0.5)))) # mean abs difference
dist( t(data.frame(as.vector(as.matrix(head(mtcars))), (as.vector(as.matrix(head(mtcars)*0.5)))))) # Euclidean; remove t() to see element by element
ks.test( as.vector(as.matrix(head(mtcars))), (as.vector(as.matrix(head(mtcars)*0.5))))$statistic  # K-S
</code>```

Body:
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData1:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData2:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

Body:
Not quite sure what you mean by "difference", but if you just want to know how much each cell differs from each cell on average (given the matrices are of the same shape and have indentical cols/rows), you could do absolute difference, or use Euclidean distance, or Kolmogorov-Smirnov distance - depending again on what you mean by "difference".

abs(head(mtcars) - (head(mtcars)*0.5)) # differences by cell
mean( as.matrix(abs(head(mtcars) - (head(mtcars)*0.5)))) # mean abs difference
dist( t(data.frame(as.vector(as.matrix(head(mtcars))), (as.vector(as.matrix(head(mtcars)*0.5)))))) # Euclidean; remove t() to see element by element
ks.test( as.vector(as.matrix(head(mtcars))), (as.vector(as.matrix(head(mtcars)*0.5))))$statistic  # K-S


问:
Trigger change event of a worksheet with activated edited cell in a shape/button click event
I have a worksheet with a clickable shape and a class listening to the change events of that sheet:

Sheet1:

```<code>Public Sub Shape_click()
  Debug.Print "click"
End Sub
</code>```

Class1:

```<code>Private WithEvents sh As Worksheet

Private Sub Class_Initialize()
  Set sh = Sheet1
End Sub

Private Sub sh_Change(ByVal Target As Range)
  Debug.Print "change: " & Target.Address
End Sub
</code>```

When I edit a cell in Sheet1 and click directly on the shape the output is

```<code>click
change: $B$1
</code>```

I would like to trigger the change event in the shape macro so that the change event would occur before printing "click". DoEvents, Sleep from kernel32 and activation of some other cell from the Shape_click were not working for me.

答:
I have found two "hacks", the first one quite limited, but the second one does the job:

Selection.Cut:

```<code>Public Sub Shape_click()
  Selection.Cut Selection
  Debug.Print "click"
End Sub
</code>```

It makes the Change event to fire 3 times (2x before "click", 1x after that), every time with the right (changed) value.

Of course you need to check the Selection (if it is set, if it's of Range type etc.)

The solution is quite limited as you can't use it with merged cells in the selection (will ask if you want to unmerge them).

Selection.Value = Selection.Value

```<code>Public Sub Shape_click()
  Selection.Value = Selection.Value
  Debug.Print "click"
End Sub
</code>```

Works even with merged cells. There is also need to check Selection if it really contains a range.

Body:
I have a worksheet with a clickable shape and a class listening to the change events of that sheet:

Sheet1:

Public Sub Shape_click()
  Debug.Print "click"
End Sub

Class1:

Private WithEvents sh As Worksheet

Private Sub Class_Initialize()
  Set sh = Sheet1
End Sub

Private Sub sh_Change(ByVal Target As Range)
  Debug.Print "change: " & Target.Address
End Sub

When I edit a cell in Sheet1 and click directly on the shape the output is

click
change: $B$1

I would like to trigger the change event in the shape macro so that the change event would occur before printing "click". DoEvents, Sleep from kernel32 and activation of some other cell from the Shape_click were not working for me.

Body:
I have found two "hacks", the first one quite limited, but the second one does the job:

Selection.Cut:

Public Sub Shape_click()
  Selection.Cut Selection
  Debug.Print "click"
End Sub

It makes the Change event to fire 3 times (2x before "click", 1x after that), every time with the right (changed) value.

Of course you need to check the Selection (if it is set, if it's of Range type etc.)

The solution is quite limited as you can't use it with merged cells in the selection (will ask if you want to unmerge them).

Selection.Value = Selection.Value

Public Sub Shape_click()
  Selection.Value = Selection.Value
  Debug.Print "click"
End Sub

Works even with merged cells. There is also need to check Selection if it really contains a range.


问:
Add class to parent element
I know this has been asked many times before, but I could not find anything that worked.
I will need to add a class to a div that gets autogenerated over my ul.

This is my html code:

```<code><div class="wrapper">
    <ul id="bx-pager">
       <li><a><img></a></li>
       <li><a><img></a></li>
    </ul>
</div>
</code>```

I need to add a second class to div class "wrapper", but after what I have tried I can't get it to work. I would be nice if someone can help me out with this simple task, but showing me how to do it. I don't have much experience with jQuery, but need it now.

答:
In pure javaScript

```<code>this.parentElement.classList.add('newClass');
</code>```

Updated

const myElement = document.querySelector('#bx-pager');
myElement.parentElement.classList.add('new-class');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.new-class {
  background-color: tomato;
}</code>```

```

Title: Add class to parent element

Body:
I know this has been asked many times before, but I could not find anything that worked.
I will need to add a class to a div that gets autogenerated over my ul.

This is my html code:

I need to add a second class to div class "wrapper", but after what I have tried I can't get it to work. I would be nice if someone can help me out with this simple task, but showing me how to do it. I don't have much experience with jQuery, but need it now.

Body:
In pure javaScript

this.parentElement.classList.add('newClass');

Updated

const myElement = document.querySelector('#bx-pager');
myElement.parentElement.classList.add('new-class');

.new-class {
  background-color: tomato;
}

<div class="wrapper">
  <ul id="bx-pager">
    <li>
      <a><img></a>
    </li>
    <li>
      <a><img></a>
    </li>
  </ul>
</div>

ContentLicense: CC BY-SA 4.0


问:
How to set ArrayList with isChecked in CheckBox android
How to set data with checkbox when user clicks submit? I want to get all data within isChecked()

And I try this code which doesn't work.

myadapter

```<code>viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Log.d("ChatGroupInviteAdap", "onClick position: " + position);
            Log.d("ChatGroupInviteAdap", "onClick getFirstname: " + chatFriendsListModels.get(position).getFirstname());
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.add(id);
        }

        if (!isChecked) {
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.remove(id);
        }

    }
});
</code>```

myFragment

user clicks submit when user checks finish

```<code>tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "OnClick: " + ChatGroupInviteFragment.dataMember.size());

        for (int i=0;i<ChatGroupInviteFragment.dataMember.size();i++){
            Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i));
        }
    }
});
</code>```

I get error when user unChecked

FATAL EXCEPTION: main
                                                                           Process: xxx.xx.x, PID: 20496
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 36, size is 3

```<code>36 is id unChecked

and 3 = size isChecked
</code>```

How to set it?

答:
getView(): </p>

```<code>viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                int position=  viewHolder.checkbox.getTag(); //Try to get position this way

                id = chatFriendsListModels.get(position).getId();
                ChatGroupInviteFragment.dataMember.add(id);
            }
            if (!isChecked) {
                id = chatFriendsListModels.get(position).getId();
                ChatGroupInviteFragment.dataMember.remove(id);
            }

        }
    });

    viewHolder.checkbox.setTag(position);
</code>```

Body:
How to set data with checkbox when user clicks submit? I want to get all data within isChecked()

And I try this code which doesn't work.

myadapter

viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Log.d("ChatGroupInviteAdap", "onClick position: " + position);
            Log.d("ChatGroupInviteAdap", "onClick getFirstname: " + chatFriendsListModels.get(position).getFirstname());
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.add(id);
        }

        if (!isChecked) {
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.remove(id);
        }

    }
});

myFragment

user clicks submit when user checks finish

tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "OnClick: " + ChatGroupInviteFragment.dataMember.size());

        for (int i=0;i<ChatGroupInviteFragment.dataMember.size();i++){
            Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i));
        }
    }
});

I get error when user unChecked

FATAL EXCEPTION: main
                                                                           Process: xxx.xx.x, PID: 20496
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 36, size is 3

36 is id unChecked

and 3 = size isChecked

How to set it?

Body:
getView():

viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                int position=  viewHolder.checkbox.getTag(); //Try to get position this way

                id = chatFriendsListModels.get(position).getId();
                ChatGroupInviteFragment.dataMember.add(id);
            }
            if (!isChecked) {
                id = chatFriendsListModels.get(position).getId();
                ChatGroupInviteFragment.dataMember.remove(id);
            }

        }
    });

    viewHolder.checkbox.setTag(position);


问:
JCE padding not being properly encrypted/decrypted
I am working on a program that I will use to encrypt and decrypt files using the JCE. My encryption and decryption is working correctly in default mode (ECB/PKCS5PADDING) however when I try to use CBC and I decrypt my file I am getting some of the text being junk (or when I try an image it gets corrupted.

Can anyone see what I am doing wrong? (I have not included my imports, can add if necessary)

```<code>public class encwork {
private static String keyString = "ykHySDZCWr16TVku"; //Encryption key
private static void bulkWork(int cipherMode, File inputFile, File outputFile) throws Exception{
    //Let the user enter the key they wish to use
    Key secretKey = new SecretKeySpec(keyString.getBytes(), "AES"); //Generates a key based on the default keysize for the specified algorithm

    //Generate an Initialization Vector (IV)
    final int ALG_KEYLENGTH = 128; //Change this as desired for the security level you want
    byte[] iv = new byte[ALG_KEYLENGTH / 8]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
    SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
    prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()];
    inputStream.read(inputBytes);
    byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    outputStream.write(outputBytes);
    inputStream.close();
    outputStream.close();
}

public static void main(String[] args) {
    File inputFile = new File("C:/Users/admin/Desktop/Crypto/In/test.txt");
    File encryptedFile = new File("C:/Users/admin/Desktop/Crypto/Enc/test.encrypted");
    File decryptedFile = new File("C:/Users/admin/Desktop/Crypto/Dec/testdec.txt");

    //Encryption
    try {
        encwork.encrypt(inputFile, encryptedFile); //Encrypt method
    } catch (Exception e) {
        e.printStackTrace(); //Will show what caused the error in the console if an error occurs
    }

    //Decryption
    try {
        encwork.decrypt(encryptedFile, decryptedFile); //Decrypt method
    } catch (Exception e) {
        e.printStackTrace(); //Will show what caused the error in the console if an error occurs
    }
}

public static void encrypt(File inputFile, File outputFile) throws Exception {
    bulkWork(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
}

public static void decrypt(File inputFile, File outputFile) throws Exception {
    bulkWork(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
}}
</code>```

答:
You are not using the same IV for both encryption and decryption.

From the comment that the decryption starts: "the first line is "çQßs}@ LÂ¤qMä]this is a test" that would mean the IV for encryption and decryption is not the same.

This comment says it all:

//Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later

Either:

save the IV by returning it from the encryption and passing it in on decryption

or

prefix the encrypted data with the IV and on decryption split it off to use for decryption. (The IV does not need to be secret)

More on the IV and CBC mode, see Cipher Block Chaining (CBC):

While the IV influences the entire encrypted data CBC mode is self correcting and this means only the first block is incorrect when the wrong IV is used on decryption.

Body:
I am working on a program that I will use to encrypt and decrypt files using the JCE. My encryption and decryption is working correctly in default mode (ECB/PKCS5PADDING) however when I try to use CBC and I decrypt my file I am getting some of the text being junk (or when I try an image it gets corrupted.

Can anyone see what I am doing wrong? (I have not included my imports, can add if necessary)

public class encwork {
private static String keyString = "ykHySDZCWr16TVku"; //Encryption key
private static void bulkWork(int cipherMode, File inputFile, File outputFile) throws Exception{
    //Let the user enter the key they wish to use
    Key secretKey = new SecretKeySpec(keyString.getBytes(), "AES"); //Generates a key based on the default keysize for the specified algorithm

    //Generate an Initialization Vector (IV)
    final int ALG_KEYLENGTH = 128; //Change this as desired for the security level you want
    byte[] iv = new byte[ALG_KEYLENGTH / 8]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
    SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
    prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()];
    inputStream.read(inputBytes);
    byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    outputStream.write(outputBytes);
    inputStream.close();
    outputStream.close();
}

public static void main(String[] args) {
    File inputFile = new File("C:/Users/admin/Desktop/Crypto/In/test.txt");
    File encryptedFile = new File("C:/Users/admin/Desktop/Crypto/Enc/test.encrypted");
    File decryptedFile = new File("C:/Users/admin/Desktop/Crypto/Dec/testdec.txt");

    //Encryption
    try {
        encwork.encrypt(inputFile, encryptedFile); //Encrypt method
    } catch (Exception e) {
        e.printStackTrace(); //Will show what caused the error in the console if an error occurs
    }

    //Decryption
    try {
        encwork.decrypt(encryptedFile, decryptedFile); //Decrypt method
    } catch (Exception e) {
        e.printStackTrace(); //Will show what caused the error in the console if an error occurs
    }
}

public static void encrypt(File inputFile, File outputFile) throws Exception {
    bulkWork(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
}

public static void decrypt(File inputFile, File outputFile) throws Exception {
    bulkWork(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
}}


问:
Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
I have some bash scripts I have been running on Ubuntu 14.04 and 16.04 for well over a year now. Some recent Ubuntu update has broken bash and I cannot figure out how to sort this out.

Example:

```<code>#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"

cat $INPUT | while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done
</code>```

my script then loops through the file doing the printf statement as follows but this is the output produced

```<code>"~jetmo" 0;
"~spamme" 0;
"~baidu" 0;
</code>```

example contents of myinput.txt

```<code>jetmon
spammen
baidu
</code>```

Input lines containing a lowercase n character gets stripped out ??
Am I missing some major change in bash that occured, this started happening a week ago and is driving me insane now.

I have tried changing #!/bin/bash to #!/bin/sh with same results.

Also tried this method of looping through the input file and still get the same results.

```<code>#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"
while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done < $INPUT
</code>```

Tried suggestion from comments using echo

```<code>echo -e -n "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
</code>```

and now I get this output

```<code>-e -n "~jetmo" 0;
-e -n "~spamme" 0;
-e -n "~baidu" 0;
</code>```

Running hexdump -C myinput.txt gives this output

```<code>00000000  6a 65 74 6d 6f 6e 0a 73  70 61 6d 6d 65 6e 0a 62  |jetmon.spammen.b|
00000010  61 69 64 75 0a 0a                                 |aidu..|
00000016
</code>```

Also changed all variable names to lowercase as suggested by Michael but still getting the same results.

```<code>#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"

cat $input | while read line
do
printf "\t\"~${line}\"\t\t$action1\n" >> $output
done
</code>```

THE SOLUTION
The Mystery is Solved

thanks to everyone, but https://stackoverflow.com/users/96588/l0b0 nailed it on the head. I had an IFS=$'\n' hiding earlier on in my script.

I now have this final, better and safer formatting of printf thanks to the recommendations of Nahuel and Charles and it is working 100% ... cannot thank you all enough.

```<code>#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"
while IFS= read -r LINE
do
printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$output"
done < $input1
</code>```

答:
It's safer to use %s to insert a string with printf for example if it can contain %

```<code>printf "\t\"~%s\"\t\t%s\n" "${LINE}" "$ACTION1" >> $OUTPUT
</code>```

EDIT following comments, with single quotes in first argument because there is no variable expansion

```<code>printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$OUTPUT"
</code>```

Body:
I have some bash scripts I have been running on Ubuntu 14.04 and 16.04 for well over a year now. Some recent Ubuntu update has broken bash and I cannot figure out how to sort this out.

Example:

#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"

cat $INPUT | while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done

my script then loops through the file doing the printf statement as follows but this is the output produced

"~jetmo" 0;
"~spamme" 0;
"~baidu" 0;

example contents of myinput.txt

jetmon
spammen
baidu

Input lines containing a lowercase n character gets stripped out ??
Am I missing some major change in bash that occured, this started happening a week ago and is driving me insane now.

I have tried changing #!/bin/bash to #!/bin/sh with same results.

Also tried this method of looping through the input file and still get the same results.

#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"
while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done < $INPUT

Tried suggestion from comments using echo

echo -e -n "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT

and now I get this output

-e -n "~jetmo" 0;
-e -n "~spamme" 0;
-e -n "~baidu" 0;

Running hexdump -C myinput.txt gives this output

00000000  6a 65 74 6d 6f 6e 0a 73  70 61 6d 6d 65 6e 0a 62  |jetmon.spammen.b|
00000010  61 69 64 75 0a 0a                                 |aidu..|
00000016

Also changed all variable names to lowercase as suggested by Michael but still getting the same results.

#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"

cat $input | while read line
do
printf "\t\"~${line}\"\t\t$action1\n" >> $output
done

THE SOLUTION
The Mystery is Solved

thanks to everyone, but https://stackoverflow.com/users/96588/l0b0 nailed it on the head. I had an IFS=$'\n' hiding earlier on in my script.

I now have this final, better and safer formatting of printf thanks to the recommendations of Nahuel and Charles and it is working 100% ... cannot thank you all enough.

#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"
while IFS= read -r LINE
do
printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$output"
done < $input1

Body:
It's safer to use %s to insert a string with printf for example if it can contain %

printf "\t\"~%s\"\t\t%s\n" "${LINE}" "$ACTION1" >> $OUTPUT

EDIT following comments, with single quotes in first argument because there is no variable expansion

printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$OUTPUT"


问:
xslt transformation to copy from xml to xml specific nodes omly
I need to create a sub-xml of some xml file.
I have a list of required nodes. How xslt tranformation should look like?
For example, input file:

```<code><?xml version="1.0"?>
<root>
  <a id="A">
    <aa>text</aa>
    <bb>text</bb>
    <cc id="1">
      <aaa>text</aaa>
      <bbb>text</bbb>
    </cc>
  </a>
  <a id="B">
    <aa>text2</aa>
    <bb>text2</bb>
    <cc id="2">
      <aaa>text2</aaa>
      <bbb>text2</bbb>
    </cc>
  </a>
</root>
</code>```

desired output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
   <a id="A">
      <bb>text</bb>
      <cc>
         <bbb>text</bbb>
      </cc>
   </a>
   <a id="B">
      <bb>text2</bb>
      <cc>
         <bbb>text2</bbb>
      </cc>
   </a>
</root>
</code>```

Currently I use follwonf xslt:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:output indent="yes"/>

  <xsl:template match="node()|@*"/>

  <xsl:template match="
 root
|root/a
|root/a/@id
|root/a/bb
|root/a/bb/node()
|root/a/cc
|root/a/cc/bbb
|root/a/cc/bbb/node()
 ">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

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

But I would like to have shorter list something like that:

```<code> root/a/@id
|root/a/bb/node()
|root/a/cc/bbb/node()
</code>```

So how to create xslt transformation for that short list?

答:
In XSLT 1.0 I would propose the following transformation:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:if test="not(. = following-sibling::*)">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
</code>```

It selects every last node wich has identical value.

Body:
I need to create a sub-xml of some xml file.
I have a list of required nodes. How xslt tranformation should look like?
For example, input file:

<?xml version="1.0"?>
<root>

    <aa>text</aa>
    <bb>text</bb>
    <cc id="1">
      <aaa>text</aaa>
      <bbb>text</bbb>
    </cc>

    <aa>text2</aa>
    <bb>text2</bb>
    <cc id="2">
      <aaa>text2</aaa>
      <bbb>text2</bbb>
    </cc>

</root>

desired output:

<?xml version="1.0" encoding="UTF-8"?>
<root>

      <bb>text</bb>
      <cc>
         <bbb>text</bbb>
      </cc>

      <bb>text2</bb>
      <cc>
         <bbb>text2</bbb>
      </cc>

</root>

Currently I use follwonf xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:output indent="yes"/>

  <xsl:template match="node()|@*"/>

  <xsl:template match="
 root
|root/a
|root/a/@id
|root/a/bb
|root/a/bb/node()
|root/a/cc
|root/a/cc/bbb
|root/a/cc/bbb/node()
 ">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

But I would like to have shorter list something like that:

 root/a/@id
|root/a/bb/node()
|root/a/cc/bbb/node()

So how to create xslt transformation for that short list?

Body:
In XSLT 1.0 I would propose the following transformation:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:if test="not(. = following-sibling::*)">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

It selects every last node wich has identical value.


问:
keyboard overlapping UITextField in Swift 4
i am trying to handle the scrolling of UITextField to avoid the keyboard to overlap it. Click here to view  current OUTPUT i am getting ]StoryBoard Screenshot. I tried to scroll the view when i click on the last textfield ..ie password field. When i click on the password field, only the email field ie the 2nd one is scrolling up. No scroll occur ion the first and last field. How can i solve this issue?

`

```<code>//
//  ViewController.swift

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var name: UITextField!

    @IBOutlet weak var email: UITextField!

    @IBOutlet weak var password: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Begin
        switch textField.tag {
        case 0...1:
            print("DO NOTHING")
        default:
            print("Do Scroll")

            scrollView.setContentOffset(CGPoint(x:0,y:100) , animated: true)
        }

    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // End
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         // Return

        if textField.tag == 0
        {
            email.becomeFirstResponder()
        }
        else if textField.tag == 1
        {
            password.becomeFirstResponder()

        }
        else if textField.tag == 2
        {
            textField.resignFirstResponder()

        }
        return true
    }

}
</code>```

`

答: You need to move all textfield to scrollview as below.

Body:
i am trying to handle the scrolling of UITextField to avoid the keyboard to overlap it. Click here to view  current OUTPUT i am getting ]StoryBoard Screenshot. I tried to scroll the view when i click on the last textfield ..ie password field. When i click on the password field, only the email field ie the 2nd one is scrolling up. No scroll occur ion the first and last field. How can i solve this issue?

`

//
//  ViewController.swift

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var name: UITextField!

    @IBOutlet weak var email: UITextField!

    @IBOutlet weak var password: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Begin
        switch textField.tag {
        case 0...1:
            print("DO NOTHING")
        default:
            print("Do Scroll")

            scrollView.setContentOffset(CGPoint(x:0,y:100) , animated: true)
        }

    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // End
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         // Return

        if textField.tag == 0
        {
            email.becomeFirstResponder()
        }
        else if textField.tag == 1
        {
            password.becomeFirstResponder()

        }
        else if textField.tag == 2
        {
            textField.resignFirstResponder()

        }
        return true
    }

}

`


问:
getting a specific image from a website link with beautifulSoup
I'm trying to get some specific image on a website using beautiful soup :

```<code>from bs4 import BeautifulSoup
import urllib.request
import random

url=urllib.request.urlopen("https://www.arandomlink.com")

content = url.read()            #We read it
soup = BeautifulSoup(content)   #We create a BeautifulSoup object
#WE OBTAIN THE URL OF THE IMAGES RELATED TO THE ITEM
images = soup.findAll("img", {'class': "arandonclass"})
print(images['src'])
</code>```

The problem is that it doesn't work, it can't find any image even if I verified that there is images with that class.
What did I do wrong?
I'm using python 3 and BS4

答:
Beautiful Soup Documentation

Searching by CSS class

It’s very useful to search for a tag that has a certain CSS class, but the name of the CSS attribute, “class”, is a reserved word in Python. Using class as a keyword argument will give you a syntax error. As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_:

```<code>soup.find_all("a", class_="sister")
</code>```

Body:
I'm trying to get some specific image on a website using beautiful soup :

from bs4 import BeautifulSoup
import urllib.request
import random

url=urllib.request.urlopen("https://www.arandomlink.com")

content = url.read()            #We read it
soup = BeautifulSoup(content)   #We create a BeautifulSoup object
#WE OBTAIN THE URL OF THE IMAGES RELATED TO THE ITEM
images = soup.findAll("img", {'class': "arandonclass"})
print(images['src'])

The problem is that it doesn't work, it can't find any image even if I verified that there is images with that class.
What did I do wrong?
I'm using python 3 and BS4

Body:
Beautiful Soup Documentation

Searching by CSS class

It’s very useful to search for a tag that has a certain CSS class, but the name of the CSS attribute, “class”, is a reserved word in Python. Using class as a keyword argument will give you a syntax error. As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_:

soup.find_all("a", class_="sister")


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答: The break statement is specifically for exiting loops.

ContentLicense: CC BY-SA 2.5

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?


问:
Swapping nodes in linked list
I tried to make function(swapNodes) for swapping nodes in linked list.
Here i stored previous and next addresses of nodes which are to be swapped.
But my code stucked in infinite loop.

Can this code be made as working one or it is a wrong approach?

```<code>#include<stdio.h>
#include<stdlib.h>
 struct Node
{
    int data;
    struct Node *next;
};
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct Node *node)
{
    while(node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}

void swapNodes(struct Node** headr,int key1,int key2)
{
    struct Node* temp1 = *headr;
    struct Node* temp2 = *headr;

    if(key1 == key2)
    return;

    struct Node* prev1 =NULL;
    struct Node* next1 =temp1;
    while(temp1->data !=key1 && next1 !=NULL)
    {
    prev1 =temp1;
    temp1 =temp1->next;
    next1 =temp1->next;
    }
    struct Node* prev2 =NULL;
    struct Node* next2 =temp2;
    while(temp2->data !=key2 && next2 !=NULL)
    {
    prev2 =temp2;
    temp2 =temp2->next;
    next2 =temp2->next;
    }
    if(next1 == NULL||next2 == NULL)
    return;

    prev1->next =temp2;
    temp2->next =next1;
    prev2->next =temp1;
    temp1->next =next2;
}
int main()
{
    struct Node *start = NULL;

    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);

    printf("\n Linked list before calling swapNodes() ");
    printList(start);

    swapNodes(&start, 4, 3);

    printf("\n Linked list after calling swapNodes() ");
    printList(start);

    return 0;
}
</code>```

答:
The function has undefined behavior because it does not take into account that for example headr can be equal to NULL or prev1 and prev2 can be equal to NULL.

It would be good to write one more function that finds the node that corresponds to the given data.

Nevertheless the function swapNodes can be written the following way. It finds nodes to be swapped and then swaps pointers to the nodes and their data members next.

Here you are

```<code>void swap( struct Node **first, struct Node **second )
{
    struct Node *tmp = *first;
    *first = *second;
    *second = tmp;
}

void swapNodes( struct Node **headr, int key1, int key2 )
{
    if ( key1 == key2 ) return;

    struct Node **first = headr;

    while ( *first && ( *first )->data != key1 ) first = &( *first )->next;

    if ( *first == NULL ) return;

    struct Node **second = headr;

    while ( *second && ( *second )->data != key2 ) second = &( *second )->next;

    if ( *second == NULL ) return;

    swap( first, second );
    swap( &( *first )->next, &( *second )->next );
}
</code>```

Here is a demonstrative program.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct Node *node)
{
    while(node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}

void swap( struct Node **first, struct Node **second )
{
    struct Node *tmp = *first;
    *first = *second;
    *second = tmp;
}

void swapNodes( struct Node **headr, int key1, int key2 )
{
    if ( key1 == key2 ) return;

    struct Node **first = headr;

    while ( *first && ( *first )->data != key1 ) first = &( *first )->next;

    if ( *first == NULL ) return;

    struct Node **second = headr;

    while ( *second && ( *second )->data != key2 ) second = &( *second )->next;

    if ( *second == NULL ) return;

    swap( first, second );
    swap( &( *first )->next, &( *second )->next );
}

int main( void )
{
    struct Node *start = NULL;

    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);

    printf("\n Linked list before calling swapNodes() ");
    printList(start);

    swapNodes(&start, 4, 3);

    printf("\n Linked list after  calling swapNodes() ");
    printList(start);

    return 0;
}
</code>```

Its output is

```<code> Linked list before calling swapNodes() 1 2 3 4 5 6 7
 Linked list after  calling swapNodes() 1 2 4 3 5 6 7
</code>```

In fact the function swapNodes as it is written (without a separate function that finds nodes for a given data) does two things: it 1) finds two nodes and it 2) swaps them. Searching of the nodes can be unsuccessful. So the function should report to the user whether nodes were swapped. In this case it is desirable to declare the function as having return type int.

For example

```<code>int swapNodes( struct Node **headr, int key1, int key2 )
{
    int success = key1 != key2;

    if ( success )
    {
        struct Node **first  = headr;
        struct Node **second = headr;

        while ( *first && ( *first )->data != key1 ) first = &( *first )->next;

        success = *first != NULL;

        if ( success )
        {
            while ( *second && ( *second )->data != key2 ) second = &( *second )->next;

            success = *second != NULL;
        }

        if ( success )
        {
            swap( first, second );
            swap( &( *first )->next, &( *second )->next );
        }
    }

    return success;
}
</code>```

If to write a separate function that searches a node as it was mentioned above then the function that swaps nodes will look more clear and simpler.

For example

```<code>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct Node *node)
{
    while(node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}

void swap( struct Node **first, struct Node **second )
{
    struct Node *tmp = *first;
    *first = *second;
    *second = tmp;
}

struct Node ** find( struct Node **headr, int data )
{
    while ( *headr && ( *headr )->data != data ) headr = &( *headr )->next;

    return headr;
}

void swapNodes( struct Node **first, struct Node **second )
{
    swap( first, second );
    swap( &( *first )->next, &( *second )->next );
}

int main( void )
{
    struct Node *start = NULL;

    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);

    printf("\n Linked list before calling swapNodes() ");
    printList(start);

    struct Node **first;
    struct Node **second;

    if ( ( first = find( &start, 4 ) ) && ( second = find( &start, 3 ) ) )  swapNodes( first, second );

    printf("\n Linked list after  calling swapNodes() ");
    printList(start);

    return 0;
}
</code>```

Title: Swapping nodes in linked list

Body:
I tried to make function(swapNodes) for swapping nodes in linked list.
Here i stored previous and next addresses of nodes which are to be swapped.
But my code stucked in infinite loop.

Can this code be made as working one or it is a wrong approach?

#include<stdio.h>
#include<stdlib.h>
 struct Node
{
    int data;
    struct Node *next;
};
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct Node *node)
{
    while(node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}

void swapNodes(struct Node** headr,int key1,int key2)
{
    struct Node* temp1 = *headr;
    struct Node* temp2 = *headr;

    if(key1 == key2)
    return;

    struct Node* prev1 =NULL;
    struct Node* next1 =temp1;
    while(temp1->data !=key1 && next1 !=NULL)
    {
    prev1 =temp1;
    temp1 =temp1->next;
    next1 =temp1->next;
    }
    struct Node* prev2 =NULL;
    struct Node* next2 =temp2;
    while(temp2->data !=key2 && next2 !=NULL)
    {
    prev2 =temp2;
    temp2 =temp2->next;
    next2 =temp2->next;
    }
    if(next1 == NULL||next2 == NULL)
    return;

    prev1->next =temp2;
    temp2->next =next1;
    prev2->next =temp1;
    temp1->next =next2;
}
int main()
{
    struct Node *start = NULL;

    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);

    printf("\n Linked list before calling swapNodes() ");
    printList(start);

    swapNodes(&start, 4, 3);

    printf("\n Linked list after calling swapNodes() ");
    printList(start);

    return 0;
}

Body:
The function has undefined behavior because it does not take into account that for example headr can be equal to NULL or prev1 and prev2 can be equal to NULL.

It would be good to write one more function that finds the node that corresponds to the given data.

Nevertheless the function swapNodes can be written the following way. It finds nodes to be swapped and then swaps pointers to the nodes and their data members next.

Here you are

void swap( struct Node **first, struct Node **second )
{
    struct Node *tmp = *first;
    *first = *second;
    *second = tmp;
}

void swapNodes( struct Node **headr, int key1, int key2 )
{
    if ( key1 == key2 ) return;

    struct Node **first = headr;

    while ( *first && ( *first )->data != key1 ) first = &( *first )->next;

    if ( *first == NULL ) return;

    struct Node **second = headr;

    while ( *second && ( *second )->data != key2 ) second = &( *second )->next;

    if ( *second == NULL ) return;

    swap( first, second );
    swap( &( *first )->next, &( *second )->next );
}

Here is a demonstrative program.

#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct Node *node)
{
    while(node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}

void swap( struct Node **first, struct Node **second )
{
    struct Node *tmp = *first;
    *first = *second;
    *second = tmp;
}

void swapNodes( struct Node **headr, int key1, int key2 )
{
    if ( key1 == key2 ) return;

    struct Node **first = headr;

    while ( *first && ( *first )->data != key1 ) first = &( *first )->next;

    if ( *first == NULL ) return;

    struct Node **second = headr;

    while ( *second && ( *second )->data != key2 ) second = &( *second )->next;

    if ( *second == NULL ) return;

    swap( first, second );
    swap( &( *first )->next, &( *second )->next );
}

int main( void )
{
    struct Node *start = NULL;

    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);

    printf("\n Linked list before calling swapNodes() ");
    printList(start);

    swapNodes(&start, 4, 3);

    printf("\n Linked list after  calling swapNodes() ");
    printList(start);

    return 0;
}

Its output is

 Linked list before calling swapNodes() 1 2 3 4 5 6 7
 Linked list after  calling swapNodes() 1 2 4 3 5 6 7

In fact the function swapNodes as it is written (without a separate function that finds nodes for a given data) does two things: it 1) finds two nodes and it 2) swaps them. Searching of the nodes can be unsuccessful. So the function should report to the user whether nodes were swapped. In this case it is desirable to declare the function as having return type int.

For example

int swapNodes( struct Node **headr, int key1, int key2 )
{
    int success = key1 != key2;

    if ( success )
    {
        struct Node **first  = headr;
        struct Node **second = headr;

        while ( *first && ( *first )->data != key1 ) first = &( *first )->next;

        success = *first != NULL;

        if ( success )
        {
            while ( *second && ( *second )->data != key2 ) second = &( *second )->next;

            success = *second != NULL;
        }

        if ( success )
        {
            swap( first, second );
            swap( &( *first )->next, &( *second )->next );
        }
    }

    return success;
}

If to write a separate function that searches a node as it was mentioned above then the function that swaps nodes will look more clear and simpler.

For example

#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}

void printList(struct Node *node)
{
    while(node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}

void swap( struct Node **first, struct Node **second )
{
    struct Node *tmp = *first;
    *first = *second;
    *second = tmp;
}

struct Node ** find( struct Node **headr, int data )
{
    while ( *headr && ( *headr )->data != data ) headr = &( *headr )->next;

    return headr;
}

void swapNodes( struct Node **first, struct Node **second )
{
    swap( first, second );
    swap( &( *first )->next, &( *second )->next );
}

int main( void )
{
    struct Node *start = NULL;

    push(&start, 7);
    push(&start, 6);
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);

    printf("\n Linked list before calling swapNodes() ");
    printList(start);

    struct Node **first;
    struct Node **second;

    if ( ( first = find( &start, 4 ) ) && ( second = find( &start, 3 ) ) )  swapNodes( first, second );

    printf("\n Linked list after  calling swapNodes() ");
    printList(start);

    return 0;
}