问:
Angular2 http.post, sending request inside header
```<code>let headers = new Headers();
headers.append('Content-Type', 'application/json');
let myReq = { FirstName: "AB", LastName: "CD"}

let options = new RequestOptions({ headers: headers });
const url = 'http://myurl.com';
return this.http.post(url, options)
        .map(res => res.json());
</code>```

How can I inject json request (myReq variable) inside header as part of this post request.

答:
try like below code :</p>

```<code>addBook() {

  let books = [
      { id: 1, name: 'Core Java' },
      { id: 2, name: 'Angular 2' },
      { id: 3, name: 'Hibernate' }
    ];

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, book, options)
               .map(this.extractData)
               .catch(this.handleErrorObservable);
}
</code>```

Body:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let myReq = { FirstName: "AB", LastName: "CD"}

let options = new RequestOptions({ headers: headers });
const url = 'http://myurl.com';
return this.http.post(url, options)
        .map(res => res.json());

How can I inject json request (myReq variable) inside header as part of this post request.

Body:
try like below code :

addBook() {

  let books = [
      { id: 1, name: 'Core Java' },
      { id: 2, name: 'Angular 2' },
      { id: 3, name: 'Hibernate' }
    ];

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, book, options)
               .map(this.extractData)
               .catch(this.handleErrorObservable);
}


来源: stackexchange

问:
Mac OS Shell: Find a file by exact modified date time
I am trying to manage files created by my camera.

I got 2 folders one for RawFiles and another for Proxy files.

I want to loop through all the files in RawFiles folder, get the modified date and find the matching file with the same modified date.

I have the following script so far (you may need to change the file path)

I couldn't find a better way to "find" a file that matches an exact time stamp. I've commented out the line that's supposed to find the file matching the timestamp.

I'd like to keep this working on MacOS terminal without any dependency on perl etc.

```<code>#!/bin/bash

echo "Start Renaming Proxy files matching RAW files."

fmt='%Y%m%d%H%M%S'

RAWFILES=("/Volumes/RAWCard/"*.CRM)

PROXYDIR="/Volumes/ProxyCard/DCIM"

for f in "${RAWFILES[@]}"
do

 echo  "${f}";

 export STAMP="$(stat -f "%Sm" -t "$fmt" "$f")"

 echo "${STAMP}"

 echo "1"

# find $PROXYDIR -type f -newermt "${STAMP}" ! -newermt "${STAMP}"

 echo "Parse"

 date -j -f %s -v +1S "${STAMP}" +"$fmt"

done```
```

答:
Not certain I understand what you are up to, but this should help. You can use stat to get the modification (or access, change or birth time) in seconds since 1st January 1970 (epoch) of a whole bunch of files in one go like this:

```<code>stat -f "%m %SN" RAWCard/*
</code>```

Sample Output

```<code>1511359473 RAWCard/step1.png
1511359474 RAWCard/step2.png
1512638778 RAWCard/step3.png
</code>```

If you do that for both directories, you can then use join to join lines on the common field (the time):

```<code>stat -f "%m %SN" RAWCard/*    > raw
stat -f "%m %SN" ProxyCard/*  > proxy
join raw proxy
</code>```

Sample Output

```<code>1511359473 RAWCard/step1.png ProxyCard/step1.png
1511359474 RAWCard/step2.png ProxyCard/step2.png
1512638778 RAWCard/step3.png ProxyCard/step3.png
</code>```

Or, you can do it all in one go:

```<code>join <(stat -f "%m %SN" RAWCard/*) <(stat -f "%m %SN" ProxyCard/*)
</code>```

If you want to then remove the timestamp field, you can do:

```<code>join -o 1.2,2.2 ...
</code>```

You can also read the pairs in a loop:

```<code>join -o 1.2,2.2 ... | while read a b ; do
   echo $a is friends with $b
done
</code>```

May I suggest you always carefully check the resulting number of files is correct - since you will have problems if you have two images shot in the same second, or no matching image shot in the same second.

Working Script --

```<code>echo "Start Renaming Files"

RAWFILES="/Volumes/RAWCard/CRM/REEL_002/*"

PROXYDIR="/Volumes/ProxyCard/DCIM/136_1205/*.MP4"

stat -f "%m %SN" /Volumes/RAWCard/CRM/REEL_002/*.CRM > raw
stat -f "%m %SN" /Volumes/ProxyCard/DCIM/136_1205/*.MP4 > proxy

join raw proxy

join -o 1.2,2.2 raw proxy | while read a b; do
   echo $a is friends with $b
   rawfilebasename=$(basename "$a")
   rawfilename="${rawfilebasename%.*}"
   echo $rawfilename
   proxydirname=$(dirname "$b")
   proxyfilename=$(basename "$b")
   proxyextension="${proxyfilename##*.}"
   echo $proxydirname/$rawfilename.$proxyextension
   mv $b $proxydirname/$rawfilename.$proxyextension

done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to manage files created by my camera.

I got 2 folders one for RawFiles and another for Proxy files.

I want to loop through all the files in RawFiles folder, get the modified date and find the matching file with the same modified date.

I have the following script so far (you may need to change the file path)

I couldn't find a better way to "find" a file that matches an exact time stamp. I've commented out the line that's supposed to find the file matching the timestamp.

I'd like to keep this working on MacOS terminal without any dependency on perl etc.

#!/bin/bash

echo "Start Renaming Proxy files matching RAW files."

fmt='%Y%m%d%H%M%S'

RAWFILES=("/Volumes/RAWCard/"*.CRM)

PROXYDIR="/Volumes/ProxyCard/DCIM"

for f in "${RAWFILES[@]}"
do

 echo  "${f}";

 export STAMP="$(stat -f "%Sm" -t "$fmt" "$f")"

 echo "${STAMP}"

 echo "1"

# find $PROXYDIR -type f -newermt "${STAMP}" ! -newermt "${STAMP}"

 echo "Parse"

 date -j -f %s -v +1S "${STAMP}" +"$fmt"

done```

Body:
Not certain I understand what you are up to, but this should help. You can use stat to get the modification (or access, change or birth time) in seconds since 1st January 1970 (epoch) of a whole bunch of files in one go like this:

stat -f "%m %SN" RAWCard/*

Sample Output

1511359473 RAWCard/step1.png
1511359474 RAWCard/step2.png
1512638778 RAWCard/step3.png

If you do that for both directories, you can then use join to join lines on the common field (the time):

stat -f "%m %SN" RAWCard/*    > raw
stat -f "%m %SN" ProxyCard/*  > proxy
join raw proxy

Sample Output

1511359473 RAWCard/step1.png ProxyCard/step1.png
1511359474 RAWCard/step2.png ProxyCard/step2.png
1512638778 RAWCard/step3.png ProxyCard/step3.png

Or, you can do it all in one go:

join <(stat -f "%m %SN" RAWCard/*) <(stat -f "%m %SN" ProxyCard/*)

If you want to then remove the timestamp field, you can do:

join -o 1.2,2.2 ...

You can also read the pairs in a loop:

join -o 1.2,2.2 ... | while read a b ; do
   echo $a is friends with $b
done

May I suggest you always carefully check the resulting number of files is correct - since you will have problems if you have two images shot in the same second, or no matching image shot in the same second.

Working Script --

echo "Start Renaming Files"

RAWFILES="/Volumes/RAWCard/CRM/REEL_002/*"

PROXYDIR="/Volumes/ProxyCard/DCIM/136_1205/*.MP4"

stat -f "%m %SN" /Volumes/RAWCard/CRM/REEL_002/*.CRM > raw
stat -f "%m %SN" /Volumes/ProxyCard/DCIM/136_1205/*.MP4 > proxy

join raw proxy

join -o 1.2,2.2 raw proxy | while read a b; do
   echo $a is friends with $b
   rawfilebasename=$(basename "$a")
   rawfilename="${rawfilebasename%.*}"
   echo $rawfilename
   proxydirname=$(dirname "$b")
   proxyfilename=$(basename "$b")
   proxyextension="${proxyfilename##*.}"
   echo $proxydirname/$rawfilename.$proxyextension
   mv $b $proxydirname/$rawfilename.$proxyextension

done


问:
Getting (400) Bad Request. when trying to send GCM Message
I am trying to send message to GCM Server through C#.net

I found a good example that I am trying to use

http://www.codewithasp.net/2015/11/send-message-gcm-c-sharp-single-multiple.html

The problem is that I get "The remote server returned an error: (400) Bad Request." error whenever I try to Get the response from this line

```<code>            WebResponse wResponse = wRequest.GetResponse();
</code>```

I tried to find what the prblem is, I changed the API code from Server to Android, to Browser, and the result is either (400) Bad request or (401) Unauthorized.

Not sure what I am doing wrong here, it looked very simple and straight forward in the example.

Help is much appreciated

Here is The code

```<code>        NotificationManager nm = new NotificationManager();
        List<string> ls = new List<string>(new string[] { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });

        nm.SendNotification(ls, " Hi.. This is a test","Hi.. Title",1);
</code>```

and here is the class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Net;
using System.Text;
using System.IO;

namespace WebApplication1
{

    public class NotificationManager
    {
        private class NotificationMessage
        {
            public string Title;
            public string Message;
            public long ItemId;
        }

        public NotificationManager()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
        {
            try
            {
                string regIds = string.Join("\",\"", deviceRegIds);

                string AppId = "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                var SenderId = "1234567890";

                NotificationMessage nm = new NotificationMessage();
                nm.Title = title;
                nm.Message = message;
                nm.ItemId = id;

                var value = new JavaScriptSerializer().Serialize(nm);
                WebRequest wRequest;
                wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                wRequest.Method = "post";
                wRequest.ContentType = " application/json;charset=UTF-8";
                wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));

                wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

                string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";

                Byte[] bytes = Encoding.UTF8.GetBytes(postData);
                wRequest.ContentLength = bytes.Length;

                Stream stream = wRequest.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                WebResponse wResponse = wRequest.GetResponse();

                stream = wResponse.GetResponseStream();

                StreamReader reader = new StreamReader(stream);

                String response = reader.ReadToEnd();

                HttpWebResponse httpResponse = (HttpWebResponse)wResponse;
                string status = httpResponse.StatusCode.ToString();

                reader.Close();
                stream.Close();
                wResponse.Close();

                if (status == "")
                {
                    return response;
                }
                else
                {
                    return "";
                }
            }
            catch( Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}
</code>```

Here is how I get the API ID and Sender ID

答:
I got the same error from sending a GCM Message via HttpWebRequests:

The remote server returned an error: (400) Bad Request.

StatusDescription: InvalidTokenFormat

But the issue wasn't the same. I just had the wrong url:

```<code>"https://fcm.googleapis.com/fcm/send/" //wrong
"https://fcm.googleapis.com/fcm/send"
</code>```

It took me longer than I'd like to admit to figure that out. And I'd like to spare other people the trouble, from such a misleading error message.

Body:
I am trying to send message to GCM Server through C#.net

I found a good example that I am trying to use

http://www.codewithasp.net/2015/11/send-message-gcm-c-sharp-single-multiple.html

The problem is that I get "The remote server returned an error: (400) Bad Request." error whenever I try to Get the response from this line

            WebResponse wResponse = wRequest.GetResponse();

I tried to find what the prblem is, I changed the API code from Server to Android, to Browser, and the result is either (400) Bad request or (401) Unauthorized.

Not sure what I am doing wrong here, it looked very simple and straight forward in the example.

Help is much appreciated

Here is The code

        NotificationManager nm = new NotificationManager();
        List<string> ls = new List<string>(new string[] { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });

        nm.SendNotification(ls, " Hi.. This is a test","Hi.. Title",1);

and here is the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Net;
using System.Text;
using System.IO;

namespace WebApplication1
{

    public class NotificationManager
    {
        private class NotificationMessage
        {
            public string Title;
            public string Message;
            public long ItemId;
        }

        public NotificationManager()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
        {
            try
            {
                string regIds = string.Join("\",\"", deviceRegIds);

                string AppId = "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
                var SenderId = "1234567890";

                NotificationMessage nm = new NotificationMessage();
                nm.Title = title;
                nm.Message = message;
                nm.ItemId = id;

                var value = new JavaScriptSerializer().Serialize(nm);
                WebRequest wRequest;
                wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                wRequest.Method = "post";
                wRequest.ContentType = " application/json;charset=UTF-8";
                wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));

                wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

                string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";

                Byte[] bytes = Encoding.UTF8.GetBytes(postData);
                wRequest.ContentLength = bytes.Length;

                Stream stream = wRequest.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                WebResponse wResponse = wRequest.GetResponse();

                stream = wResponse.GetResponseStream();

                StreamReader reader = new StreamReader(stream);

                String response = reader.ReadToEnd();

                HttpWebResponse httpResponse = (HttpWebResponse)wResponse;
                string status = httpResponse.StatusCode.ToString();

                reader.Close();
                stream.Close();
                wResponse.Close();

                if (status == "")
                {
                    return response;
                }
                else
                {
                    return "";
                }
            }
            catch( Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}

Here is how I get the API ID and Sender ID

Body:
I got the same error from sending a GCM Message via HttpWebRequests:

The remote server returned an error: (400) Bad Request.

StatusDescription: InvalidTokenFormat

But the issue wasn't the same. I just had the wrong url:

"https://fcm.googleapis.com/fcm/send/" //wrong
"https://fcm.googleapis.com/fcm/send"

It took me longer than I'd like to admit to figure that out. And I'd like to spare other people the trouble, from such a misleading error message.


问:
Can't open database-Android
I'm developing a simple Android application with SQL.
I followed the following guides -
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

I get an error when trying to open the database.
Here is my DataBaseHelp.Java Class-

```<code>public class DataBaseHelper extends SQLiteOpenHelper{

private static String DB_PATH = "/data/data/and.testDB/databases/";

private static String DB_NAME = "MyData";

private SQLiteDatabase myDataBase;

private final Context myContext;
public DataBaseHelper(Context context) {

 super(context, DB_NAME, null, 1);
    this.myContext = context;
}
public void createDataBase() throws IOException{

 boolean dbExist = checkDataBase();

 if(dbExist){
  //do nothing - database already exist
 }else{
     this.getReadableDatabase();

     try {

   copyDataBase();

  } catch (IOException e) {

      throw new Error("Error copying database");

     }
 }

}

private boolean checkDataBase(){

 SQLiteDatabase checkDB = null;

 try{
  String myPath = DB_PATH + DB_NAME;
  checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

 }catch(SQLiteException e){

  //database does't exist yet.

 }

 if(checkDB != null){

  checkDB.close();

 }

 return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{

 //Open your local db as the input stream
 InputStream myInput = myContext.getAssets().open(DB_NAME);

 // Path to the just created empty db
 String outFileName = DB_PATH + DB_NAME;

 //Open the empty db as the output stream
 OutputStream myOutput = new FileOutputStream(outFileName);

 //transfer bytes from the inputfile to the outputfile
 byte[] buffer = new byte[1024];
 int length;
 while ((length = myInput.read(buffer))>0){
  myOutput.write(buffer, 0, length);
 }

 //Close the streams
 myOutput.flush();
 myOutput.close();
 myInput.close();

}

public void openDataBase() {

 //Open the database
    String myPath = DB_PATH + DB_NAME;
 myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
 public synchronized void close() {
         if(myDataBase != null)
          myDataBase.close();
         super.close();
 }
 @Override
 public void onCreate(SQLiteDatabase db) {
 }
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}
</code>```

And this is my testDB.Java class-

```<code>public class testDB extends Activity {
SQLiteDatabase myDataBase;
public String[] gur = new String[4];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DataBaseHelper myDbHelper = new DataBaseHelper(this);
    myDbHelper = new DataBaseHelper(this);

    try {

        myDbHelper.createDataBase();

} catch (IOException ioe) {

    throw new Error("Unable to create database");

}

try {

    myDbHelper.openDataBase();
// Here is the problem-Can't open the database/
}catch(SQLException sqle){

    throw sqle;

}
    myDataBase = myDbHelper.getWritableDatabase();

    Cursor c = myDataBase.rawQuery("SELECT * FROM beer", null);

if (c != null ) {
    if  (c.moveToFirst()) {
          for(int x=0;x< 1;x++)
          {

              gur[x] = (c.getString(c.getColumnIndex("name")));
              c.moveToNext();
          }
}
    Toast.makeText(this,gur[0],Toast.LENGTH_LONG).show();
}

        }
    }
</code>```

I created the database using SQLite Database Browser, created a table named "beer", added 2 rows and put it in the /assests folder in my project.

Please note that i'm new to SQL, and its my first time using it. I searched all day for an answer and couldn't find one.

Thanks!

答:
I suggest to use an other tutorial.  To create a database outside of the devices is "a little bit" wired. I learned it from a book, but i think this tutorial uses the right procedure.

Edit:
Ok, the tutorial is for a special case

Most all of the Android examples and tutorials out there assume you want to create and populate your database at runtime and not to use and access an independent, preloaded database with your Android application.

The method I'm going to show you takes your own SQLite database file from the "assets" folder and copies into the system database path of your application so the SQLiteDatabase API can open and access it normally.

ContentLicense: CC BY-SA 2.5

Title: Can't open database-Android

Body:
I'm developing a simple Android application with SQL.
I followed the following guides -
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

I get an error when trying to open the database.
Here is my DataBaseHelp.Java Class-

public class DataBaseHelper extends SQLiteOpenHelper{

private static String DB_PATH = "/data/data/and.testDB/databases/";

private static String DB_NAME = "MyData";

private SQLiteDatabase myDataBase;

private final Context myContext;
public DataBaseHelper(Context context) {

 super(context, DB_NAME, null, 1);
    this.myContext = context;
}
public void createDataBase() throws IOException{

 boolean dbExist = checkDataBase();

 if(dbExist){
  //do nothing - database already exist
 }else{
     this.getReadableDatabase();

     try {

   copyDataBase();

  } catch (IOException e) {

      throw new Error("Error copying database");

     }
 }

}

private boolean checkDataBase(){

 SQLiteDatabase checkDB = null;

 try{
  String myPath = DB_PATH + DB_NAME;
  checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

 }catch(SQLiteException e){

  //database does't exist yet.

 }

 if(checkDB != null){

  checkDB.close();

 }

 return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{

 //Open your local db as the input stream
 InputStream myInput = myContext.getAssets().open(DB_NAME);

 // Path to the just created empty db
 String outFileName = DB_PATH + DB_NAME;

 //Open the empty db as the output stream
 OutputStream myOutput = new FileOutputStream(outFileName);

 //transfer bytes from the inputfile to the outputfile
 byte[] buffer = new byte[1024];
 int length;
 while ((length = myInput.read(buffer))>0){
  myOutput.write(buffer, 0, length);
 }

 //Close the streams
 myOutput.flush();
 myOutput.close();
 myInput.close();

}

public void openDataBase() {

 //Open the database
    String myPath = DB_PATH + DB_NAME;
 myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
 public synchronized void close() {
         if(myDataBase != null)
          myDataBase.close();
         super.close();
 }
 @Override
 public void onCreate(SQLiteDatabase db) {
 }
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}

And this is my testDB.Java class-

public class testDB extends Activity {
SQLiteDatabase myDataBase;
public String[] gur = new String[4];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DataBaseHelper myDbHelper = new DataBaseHelper(this);
    myDbHelper = new DataBaseHelper(this);

    try {

        myDbHelper.createDataBase();

} catch (IOException ioe) {

    throw new Error("Unable to create database");

}

try {

    myDbHelper.openDataBase();
// Here is the problem-Can't open the database/
}catch(SQLException sqle){

    throw sqle;

}
    myDataBase = myDbHelper.getWritableDatabase();

    Cursor c = myDataBase.rawQuery("SELECT * FROM beer", null);

if (c != null ) {
    if  (c.moveToFirst()) {
          for(int x=0;x< 1;x++)
          {

              gur[x] = (c.getString(c.getColumnIndex("name")));
              c.moveToNext();
          }
}
    Toast.makeText(this,gur[0],Toast.LENGTH_LONG).show();
}

        }
    }

I created the database using SQLite Database Browser, created a table named "beer", added 2 rows and put it in the /assests folder in my project.

Please note that i'm new to SQL, and its my first time using it. I searched all day for an answer and couldn't find one.

Thanks!


问:
Way to not use goto loops in vba msgbox
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

```<code>Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub
</code>```

Thanks for any help you are able to provide

答:
```<code>Option Explicit

Sub MsgBox_Test()

    Dim TestVariable As String
    Dim done As Boolean

    Do
        TestVariable = InputBox(" Y or N")

        done = True            ' preload exit value

        If LCase(TestVariable) = "y" Then
            MsgBox ("Yeyy")

        ElseIf LCase(TestVariable) = "n" Then
            MsgBox ("Awww")

        ElseIf Len(TestVariable) > 0 Then

            done = False       ' abort exit

        End If

    Loop Until done

End Sub
</code>```

Title: Way to not use goto loops in vba msgbox

Body:
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub

Thanks for any help you are able to provide


问:
Requests/actions on mobile applications cannot be recorded in Jmeter via HTTP(S) Test Script Recorder
I want to do performance test on a mobile app so that I am using Jmeter's HTTP(S) Test Script Recorder. I followed the belows steps before testing:

Open Jmeter

Select Templates > Recording and Create a recorder

I have everything I need like Test Plan > Thread Group > Recording
Controller or Workbench > HTTP(S) Test Script Recorder > View
Results Tree and so on

In HTTP(S) Test Script Recorder I set a port

Then I press "Start" button and a pop-up is appeared that states
ApacheJMeterTemporaryRootCA.crt is created under .\bin directory

I go to .\bin directory and installed the certificate

Then, I used my mobile device (in this case, Google Nexus 10) to
install ApacheJMeterTemporaryRootCA.crt

I send the file to myself and follow this path: Settings > Wifi >
Advanced > Install Certificates

I installed the certificate and see a message like "Network may be
monitored" which means installation is ok.

Then modify the network I use; set Proxy option as Manual, set host
 IP as the same one with my laptop which I run Jmeter and set the
 port number same in HTTP(S) Test Script Recorder and I saved the changes

Finally, I open some apps or using Chrome but nothing can be seen in Jmeter

PS: My laptop and the device are in the same network

I tried to use some filter for URL patters but nothing change.

I reviewed the open tickets related to this issue but I could not find an answer

I can successfully record changes that I do in Firefox or Chrome in
my laptop but for mobile case I cannot

Also, I checked the jmeter.log file, however; I could not see any error

I guess, there is a simple configuration problem but I could not figure out

Lastly,
Jmeter version: 3.3
OS: Windows 10 Enterprise
Android: 5.1.1

Thanks,

答:
You might need a third-party application like ProxyDroid in order to be able to route all the traffic to JMeter's proxy. Other settings look good, so your setup should work fine. </p>

<p>You can also try an alternative way of recording a JMeter test on mobile device - it is cloud-based proxy which automates certificate installation process. As a little bonus it can export recorded scripts in SmartJMX format with automatic detection and correlation of any dynamic parameters so you will be able to save some time on adding and configuring the relevant PostProcessors. </p>

Body:
You might need a third-party application like ProxyDroid in order to be able to route all the traffic to JMeter's proxy. Other settings look good, so your setup should work fine.

You can also try an alternative way of recording a JMeter test on mobile device - it is cloud-based proxy which automates certificate installation process. As a little bonus it can export recorded scripts in SmartJMX format with automatic detection and correlation of any dynamic parameters so you will be able to save some time on adding and configuring the relevant PostProcessors.


问:
Computing edit distance using two simple columns from iris dataset
In the following code below, I want to compute similarity between two columns of text strings.To achieve this, I take first 10 rows of "Petal.Length" column from iris and assign it to a1 , and first 4 rows from "Sepal.Length" column from iris and assign it to a2. My objective is that each "a2" value should be compared to every a1 value using the formula in the last line such that I get a final vector percent_calc with 40 values. </p>

```<code>library(stringdist)
library(RecordLinkage)

a1 = iris$Petal.Length[1:10] * 1000
a2 = iris$Sepal.Length[1:4]  * 1000
a1 = as.character(a1)
a2 = as.character(a2)

percent_calc = RecordLinkage::levenshteinSim(a2,a1)
</code>```

Body:
In the following code below, I want to compute similarity between two columns of text strings.To achieve this, I take first 10 rows of "Petal.Length" column from iris and assign it to a1 , and first 4 rows from "Sepal.Length" column from iris and assign it to a2. My objective is that each "a2" value should be compared to every a1 value using the formula in the last line such that I get a final vector percent_calc with 40 values.

library(stringdist)
library(RecordLinkage)

a1 = iris$Petal.Length[1:10] * 1000
a2 = iris$Sepal.Length[1:4]  * 1000
a1 = as.character(a1)
a2 = as.character(a2)

percent_calc = RecordLinkage::levenshteinSim(a2,a1)

Body:
Get all combinations, then get distance:

a12 <- expand.grid(a1, a2, stringsAsFactors = FALSE)

percent_calc <- levenshteinSim(a12$Var1, a12$Var2)

percent_calc
# [1] 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50
# [19] 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.75 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50 0.50
# [37] 0.50 0.50 0.50 0.50


问:
Understanding event listeners in java
I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

```<code>    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};
</code>```

or:

```<code>javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
</code>```

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)

答:
I'll try to exemplify the second example.

In this case invokeLater method expects any object which implements the Runnable interface.

for example, this is an alternative way of writing the same thing without an anonymous class:

```<code>class Example implements Runnable{
  public void run(){
    // do something
  }
}
</code>```

and your example could be:

```<code>javax.swing.SwingUtilities.invokeLater(new Example());
</code>```

But since this Example class it's likely you'll use it only once, it's more convenient to use an anonymous class.

Title: Understanding event listeners in java

Body:
I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};

or:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)

Body:
I'll try to exemplify the second example.

In this case invokeLater method expects any object which implements the Runnable interface.

for example, this is an alternative way of writing the same thing without an anonymous class:

class Example implements Runnable{
  public void run(){
    // do something
  }
}

and your example could be:

javax.swing.SwingUtilities.invokeLater(new Example());

But since this Example class it's likely you'll use it only once, it's more convenient to use an anonymous class.


问:
Getting 'dispatch is not defined' in redux component
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.

This is my code:

```<code>  //store
  import * as redux from 'redux';
  import thunk from 'redux-thunk';
  import {userReducer, exampleReducer, namesReducer} from 'reducers';

  export var configure = (initialState = {}) => {
    const reducer = redux.combineReducers({
            user: userReducer,
            example: exampleReducer,
            names: namesReducer
        })

  var store = redux.createStore(reducer, initialState, redux.compose(
      redux.applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    ));

    return store;
  };

  //reducers
  export var namesReducer = (state = [], action) => {
    switch (action.type) {
      case 'GET_NAMES':
        return [
          action.names
        ]
      default:
      return state;
    }
  }

  //actions
  export var getNames = (names) => {
    return {
        type: 'GET_NAMES',
        names
    }
  };

  export var startGetNames = () => {
    console.log("action started")
    return (dispatch) => {
        var nameRef = firebase.database().ref().child('names');
        return nameRef.once('value').then((snapshot) => {
                var data = snapshot.val();
                _.map(data, function(name) {return finalArr.push(
              {
                display: `${name.first_name} ${name.last_name}`,
                value: name.id
              }
            )});
           dispatch(getNames(finalArr));
        })
      }
  }

  //component
  import _ from 'underscore';
  import React from 'react';
  import { render } from "react-dom";
  import {connect} from 'react-redux';
  import Modal from 'react-responsive-modal';
  var actions = require('actions');
  var firebase = require('firebase/app');
  require('firebase/auth');
  require('firebase/database');
  //components
  import roomBookingForm from 'roomBookingForm';

  import PanelHeader from 'PanelHeader';
  import PanelItem from 'PanelItem';
  import Table from 'Table';
  import TableRow from 'TableRow';
  import TableHeaderCell from 'TableHeaderCell';
  import TextInput from 'TextInput';
  import Dropdown from 'Dropdown';

  class roomBooking extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      pageTitle: "Appointment Creation",
      openForm: false
    }
  }

  componentWillMount() {
   this.props.clinicians
  }

   onOpenModal = () => {
    this.setState({openForm: true});
  }

   modalClose = () => {
    this.setState({ openForm: false });
  };

    render() {
      return (
        <div className="main-container">
          <div className="options-menu">
            <PanelHeader >
              Options
            </PanelHeader>
              <PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>
          </div>
        <div>
          <Table className="display-table">
            <TableRow className="display-table-head">
              <TableHeaderCell className="name" displayText="Name" />
            </TableRow>
          </Table>
        </div>
        <roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />
      </div>
      )
    }
  }

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect()(roomBooking);
</code>```

答:
There are few issues with your code:

finalArr is not defined before using it.

dispatch does not work like this. It needs to be called like store.dispatch({ACTION}). So, you'll need to import store.

Body:
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.

This is my code:

  //store
  import * as redux from 'redux';
  import thunk from 'redux-thunk';
  import {userReducer, exampleReducer, namesReducer} from 'reducers';

  export var configure = (initialState = {}) => {
    const reducer = redux.combineReducers({
            user: userReducer,
            example: exampleReducer,
            names: namesReducer
        })

  var store = redux.createStore(reducer, initialState, redux.compose(
      redux.applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    ));

    return store;
  };

  //reducers
  export var namesReducer = (state = [], action) => {
    switch (action.type) {
      case 'GET_NAMES':
        return [
          action.names
        ]
      default:
      return state;
    }
  }

  //actions
  export var getNames = (names) => {
    return {
        type: 'GET_NAMES',
        names
    }
  };

  export var startGetNames = () => {
    console.log("action started")
    return (dispatch) => {
        var nameRef = firebase.database().ref().child('names');
        return nameRef.once('value').then((snapshot) => {
                var data = snapshot.val();
                _.map(data, function(name) {return finalArr.push(
              {
                display: `${name.first_name} ${name.last_name}`,
                value: name.id
              }
            )});
           dispatch(getNames(finalArr));
        })
      }
  }

  //component
  import _ from 'underscore';
  import React from 'react';
  import { render } from "react-dom";
  import {connect} from 'react-redux';
  import Modal from 'react-responsive-modal';
  var actions = require('actions');
  var firebase = require('firebase/app');
  require('firebase/auth');
  require('firebase/database');
  //components
  import roomBookingForm from 'roomBookingForm';

  import PanelHeader from 'PanelHeader';
  import PanelItem from 'PanelItem';
  import Table from 'Table';
  import TableRow from 'TableRow';
  import TableHeaderCell from 'TableHeaderCell';
  import TextInput from 'TextInput';
  import Dropdown from 'Dropdown';

  class roomBooking extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      pageTitle: "Appointment Creation",
      openForm: false
    }
  }

  componentWillMount() {
   this.props.clinicians
  }

   onOpenModal = () => {
    this.setState({openForm: true});
  }

   modalClose = () => {
    this.setState({ openForm: false });
  };

    render() {
      return (

            <PanelHeader >
              Options
            </PanelHeader>
              <PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>

            <TableRow className="display-table-head">
              <TableHeaderCell className="name" displayText="Name" />
            </TableRow>

        <roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />

      )
    }
  }

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect()(roomBooking);


问:
Selenium click on class
I have this html code and i try to click on the class = "btn  submit-btn".

```<code><div  <div id="js-tab-a" data-tab="tab1" class="tab-content a">
        <div>
            <fieldset class="example a">
              <div class="test a">
                <input type="submit" class="btn js-submit-btn" title="Search title" value="Search">
                <input type="submit" class="btn some class" title="some title" value="some value">
              </div>
            </fieldset>
        </div>
     </div>

    <div id="js-tab-b" data-tab="tab2" class="tab-content b">
        <div>
            <fieldset class="example class">
              <div id="some id" class="some class">
              </div>
            </fieldset>
            <fieldset>
              <div class="example b">
                <input type="submit" class="btn  submit-btn" value="Search" title="Search title">
                <input type="submit" class="btn some options-btn" value="some value" title="some title">
              </div>
            </fieldset>

          </form>
        </div>
     </div>
</div>
</code>```

I want to click on (under class = example b)

```<code><input type="submit" class="btn  submit-btn" value="Search" title="Search title">
</code>```

I tried this:

```<code>@FindBy(xpath = "//input[@type='submit'][@value='Search']")
    WebElement submit;
    submit.click
</code>```

and this:

```<code> @FindBy(xpath = "//input[@type='submit'][@class='btn submit-btn']")
    WebElement submit;
    submit.click
</code>```

But the "button" cannot be clicked and don't get any error.

答:
To clear up a certain fact we can't click on the class = "btn submit-btn". It's the WebElement which can contain class = "btn submit-btn" as one of the attribute and invoke the click() method. So we can click on the WebElement with the attribute class = "btn submit-btn"

Now, if you want to click on the WebElement under class = example b with the attribute class = "btn submit-btn" you can use the following code block :

```<code>@FindBy(xpath = "//div[@class='example b']/input[@class='btn submit-btn' and @value='Search' and @title='Search title']")
    WebElement submit;
    submit.click
</code>```

Title: Selenium click on class

Body:
I have this html code and i try to click on the class = "btn  submit-btn".

<div

            <fieldset class="example a">

                <input type="submit" class="btn js-submit-btn" title="Search title" value="Search">
                <input type="submit" class="btn some class" title="some title" value="some value">

            </fieldset>

            <fieldset class="example class">

            </fieldset>
            <fieldset>

                <input type="submit" class="btn  submit-btn" value="Search" title="Search title">
                <input type="submit" class="btn some options-btn" value="some value" title="some title">

            </fieldset>

          </form>

I want to click on (under class = example b)

<input type="submit" class="btn  submit-btn" value="Search" title="Search title">

I tried this:

@FindBy(xpath = "//input[@type='submit'][@value='Search']")
    WebElement submit;
    submit.click

and this:

 @FindBy(xpath = "//input[@type='submit'][@class='btn submit-btn']")
    WebElement submit;
    submit.click

But the "button" cannot be clicked and don't get any error.

Body:
To clear up a certain fact we can't click on the class = "btn submit-btn". It's the WebElement which can contain class = "btn submit-btn" as one of the attribute and invoke the click() method. So we can click on the WebElement with the attribute class = "btn submit-btn"

Now, if you want to click on the WebElement under class = example b with the attribute class = "btn submit-btn" you can use the following code block :

@FindBy(xpath = "//div[@class='example b']/input[@class='btn submit-btn' and @value='Search' and @title='Search title']")
    WebElement submit;
    submit.click


问:
My code is running but not inserting any value
I have this segment of code running while looping through files in an folder.
Code does run but, is not having any output on this segment.

```<code>Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")

With ThisWorkbook.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
.Range("E" & LastRow + 1).Value = rng1
End With
</code>```

I'm using this segment of code to extract data from B15 to E81 & N15 to O 81 from all the excel workbook in the folder.

Upon copying range into variable, it will activate the workbook where this code lie

Select last entry from column E, Offset by 1 row

Input range variable to the next blank cell.

Appreciate all the help I could find. Thanks in advance.

答:
Try this:</p>

```<code>Dim lastRow As Range, rng1 As Range

Set rng1 = Worksheets(1).Range("B15:E81,N15:O81")
Set lastRow = ThisWorkbook.Worksheets("Sheet1").Cells(ThisWorkbook.Worksheets("Sheet1").Rows.Count, "E").End(xlUp)

lastRow.Offset(1, 0).Resize(rng1.Rows.Count, rng1.Columns.Count).Value = rng1.Value
</code>```

Body:
I have this segment of code running while looping through files in an folder.
Code does run but, is not having any output on this segment.

Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")

With ThisWorkbook.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
.Range("E" & LastRow + 1).Value = rng1
End With

I'm using this segment of code to extract data from B15 to E81 & N15 to O 81 from all the excel workbook in the folder.

Upon copying range into variable, it will activate the workbook where this code lie

Select last entry from column E, Offset by 1 row

Input range variable to the next blank cell.

Appreciate all the help I could find. Thanks in advance.

Body:
Try this:

Dim lastRow As Range, rng1 As Range

Set rng1 = Worksheets(1).Range("B15:E81,N15:O81")
Set lastRow = ThisWorkbook.Worksheets("Sheet1").Cells(ThisWorkbook.Worksheets("Sheet1").Rows.Count, "E").End(xlUp)

lastRow.Offset(1, 0).Resize(rng1.Rows.Count, rng1.Columns.Count).Value = rng1.Value


问:
Empty a Select Box with YUI 2
If you have a select box that looks like this:

<select id="test"></select>

You could empty it with jQuery like this:

```<code>$('#test').empty();
</code>```

How could I do something like this using YUI 2?

Thanks!

答:
No idea how you would do this with YUI 2 but here's how you could do it with plain javascript:</p>

```<code>document.getElementById('test').length = 0;
</code>```

Title: Empty a Select Box with YUI 2

Body:
If you have a select box that looks like this:

<select id="test"></select>

You could empty it with jQuery like this:

$('#test').empty();

How could I do something like this using YUI 2?

Thanks!

Body:
No idea how you would do this with YUI 2 but here's how you could do it with plain javascript:

document.getElementById('test').length = 0;


问:
Why I have some junk bytes while receiving file with UDP Socket in C?
I writed a client/server program in C, where the client send the file to the server.
It works, but some junk bytes are added to the received file at the position of 1400 of the byte.
I tried with a text file and I setted to 0 the memory before any sent.
Why that junk bytes?

Here the code:

macro.h

```<code>#ifndef MACRO_H
#define MACRO_H

#include <stdio.h>
#include <errno.h>
#include <stdint.h>

#define SERV_PORT 49312
#define MAXLINE   1400

#define END_FLAG "================END"

#define abort_on_error(cond, msg) do {                                          \
    if (cond) {                                                                 \
        fprintf(stderr, "%s (errno=%d [%s])\n", msg, errno, strerror(errno));   \
        exit(EXIT_FAILURE);                                                     \
    }                                                                           \
} while (0)

struct pkt {
    // struct sockaddr_in addr;
    // int sockfd;
    uint16_t seq_num;
    uint32_t status;
    uint8_t data[MAXLINE];
};

typedef struct pkt PACK;

#endif // MACRO_H
</code>```

client.c

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>

#include "macro.h"

int main(int argc, char **argv)
{
    int sockfd, n, count = 0;
    struct sockaddr_in servaddr;
    // char buf[MAXLINE];
    char *target, *path;
    FILE *file;
    PACK packet;
    long filesize;

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    path = argv[2];
    target = argv[3];

    packet.seq_num = 0;
    packet.status = 0;
    memset(packet.data, 0, sizeof(packet.data));
    memcpy(packet.data, target, strlen(target));

    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                    "sendto() filename error");

    memset(packet.data, 0, sizeof(packet.data));
    abort_on_error(recvfrom(sockfd, &packet, sizeof(packet), 0, NULL, NULL) == -1, "recvfrom() ok error");
    if (!strncmp((const char *) packet.data, "ok", 2)) {
        printf("Filename sent.\n");
    }

    file = fopen(path, "r");
    abort_on_error(file == NULL, "fopen() error");

    fseek(file, 0L, SEEK_END);
    filesize = ftell(file);
    printf("filesize: %ld\n", filesize);
    fseek(file, 0L, SEEK_SET);
    memset(packet.data, 0, sizeof(packet.data));
    sprintf((char *) packet.data, "%ld", filesize);

    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                        "sendto() data error");

    memset(packet.data, 0, sizeof(packet.data));
    while ((n = fread(packet.data, sizeof(char), MAXLINE, file))) {
        // packet.data[n] = '\0';
        // printf("n: %d\n", n);
        abort_on_error(n == -1, "fread() error");
        abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                        "sendto() data error");
        count = count + n;
        memset(packet.data, 0, sizeof(packet.data));
    }
    printf("Tot Bytes sent: %d\n", count);

    memset(packet.data, 0, sizeof(packet.data));
    memcpy(packet.data, END_FLAG, strlen(END_FLAG));
    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                    "sendto() end_flag error");

    fclose(file);
    return 0;
}
</code>```

server.c

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#include "macro.h"

void run(int sockfd, struct sockaddr *cliaddr, socklen_t clilen)
{
    int n = 0, count = 0, status = 0;
    socklen_t len;
    // char buf[MAXLINE];
    FILE *file;
    PACK packet;

    len = clilen;
    n = recvfrom(sockfd, &packet, sizeof(packet), 0, cliaddr, &len);
    abort_on_error(n == -1, "recvfrom() filename error");
    // buf[n] = 0;
    printf("Received from client: [%s]\n", packet.data);

    file = fopen((const char *) packet.data, "w+");
    abort_on_error(file == NULL, "fopen() error");

    packet.seq_num = 0;
    packet.status = 0;
    memset(packet.data, 0, sizeof(packet.data));
    memcpy(packet.data, "ok", strlen("ok"));
    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, cliaddr, len) == -1,
                    "sendto() ok error");

    memset(packet.data, 0, sizeof(packet.data));
    abort_on_error(recvfrom(sockfd, &packet, sizeof(packet), 0, cliaddr, &len) == -1,
                    "recvfrom() error");
    long filesize = strtol((const char *) packet.data, NULL, 0);
    printf("filesize: %ld\n", filesize);

    while ((n = recvfrom(sockfd, &packet, sizeof(packet), 0, cliaddr, &len))) {
        abort_on_error(n == -1, "recvfrom() data error");
        // packet.data[n] = '\0';
        // printf("%s\n", packet.data);
        if (!(strcmp((const char *) packet.data, END_FLAG))) {
            break;
        }

        int num_packet = filesize / n;
        // printf("num_packet: %d\n", num_packet);

        count += n;
        if(!num_packet){
            fwrite(packet.data, sizeof(char), n-(n-filesize), file);
            printf("byte to write: %ld\n", n-(n-filesize));
        }
        else {
            if(count <= filesize) {
                fwrite(packet.data, sizeof(char), n-8, file);
                printf("byte to write: %d\n", n);
            }
            else if ((count > filesize) && (filesize-num_packet*n-8) && !status) {
                    fwrite(packet.data, sizeof(char), filesize-num_packet*(n-8), file);
                    printf("byte to write: %ld\n", filesize-num_packet*(n-8));
                    status = 1;
            }
        }
    }
    printf("Tot Bytes received: %d\n", count);
    fclose(file);
}

int main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in servaddr, cliaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    run(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));

    return 0;
}
</code>```

For files less than 1400 bytes it works perfectly!
If the file is larger than 1400 bytes (more packet for sent it) then some junk bytes are added.
I can't find why!

答:
junk bytes at the end of string a dead giveaway for a missing string nul termination problem.

here:

```<code>memcpy(packet.data, target, strlen(target));
</code>```

or here:

```<code>memcpy(packet.data, "ok", strlen("ok"));
</code>```

you're copying the string without the terminator.

now on reception you have no way of knowing where the string ends and neither does fprintf.

So just use strcpy instead of memcpy when copying strings. It'll work and add the nul termination char

```<code>strcpy(packet.data, target);
</code>```

and

```<code>strcpy(packet.data, "ok");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I writed a client/server program in C, where the client send the file to the server.
It works, but some junk bytes are added to the received file at the position of 1400 of the byte.
I tried with a text file and I setted to 0 the memory before any sent.
Why that junk bytes?

Here the code:

macro.h

#ifndef MACRO_H
#define MACRO_H

#include <stdio.h>
#include <errno.h>
#include <stdint.h>

#define SERV_PORT 49312
#define MAXLINE   1400

#define END_FLAG "================END"

#define abort_on_error(cond, msg) do {                                          \
    if (cond) {                                                                 \
        fprintf(stderr, "%s (errno=%d [%s])\n", msg, errno, strerror(errno));   \
        exit(EXIT_FAILURE);                                                     \
    }                                                                           \
} while (0)

struct pkt {
    // struct sockaddr_in addr;
    // int sockfd;
    uint16_t seq_num;
    uint32_t status;
    uint8_t data[MAXLINE];
};

typedef struct pkt PACK;

#endif // MACRO_H

client.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>

#include "macro.h"

int main(int argc, char **argv)
{
    int sockfd, n, count = 0;
    struct sockaddr_in servaddr;
    // char buf[MAXLINE];
    char *target, *path;
    FILE *file;
    PACK packet;
    long filesize;

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    path = argv[2];
    target = argv[3];

    packet.seq_num = 0;
    packet.status = 0;
    memset(packet.data, 0, sizeof(packet.data));
    memcpy(packet.data, target, strlen(target));

    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                    "sendto() filename error");

    memset(packet.data, 0, sizeof(packet.data));
    abort_on_error(recvfrom(sockfd, &packet, sizeof(packet), 0, NULL, NULL) == -1, "recvfrom() ok error");
    if (!strncmp((const char *) packet.data, "ok", 2)) {
        printf("Filename sent.\n");
    }

    file = fopen(path, "r");
    abort_on_error(file == NULL, "fopen() error");

    fseek(file, 0L, SEEK_END);
    filesize = ftell(file);
    printf("filesize: %ld\n", filesize);
    fseek(file, 0L, SEEK_SET);
    memset(packet.data, 0, sizeof(packet.data));
    sprintf((char *) packet.data, "%ld", filesize);

    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                        "sendto() data error");

    memset(packet.data, 0, sizeof(packet.data));
    while ((n = fread(packet.data, sizeof(char), MAXLINE, file))) {
        // packet.data[n] = '\0';
        // printf("n: %d\n", n);
        abort_on_error(n == -1, "fread() error");
        abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                        "sendto() data error");
        count = count + n;
        memset(packet.data, 0, sizeof(packet.data));
    }
    printf("Tot Bytes sent: %d\n", count);

    memset(packet.data, 0, sizeof(packet.data));
    memcpy(packet.data, END_FLAG, strlen(END_FLAG));
    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1,
                    "sendto() end_flag error");

    fclose(file);
    return 0;
}

server.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#include "macro.h"

void run(int sockfd, struct sockaddr *cliaddr, socklen_t clilen)
{
    int n = 0, count = 0, status = 0;
    socklen_t len;
    // char buf[MAXLINE];
    FILE *file;
    PACK packet;

    len = clilen;
    n = recvfrom(sockfd, &packet, sizeof(packet), 0, cliaddr, &len);
    abort_on_error(n == -1, "recvfrom() filename error");
    // buf[n] = 0;
    printf("Received from client: [%s]\n", packet.data);

    file = fopen((const char *) packet.data, "w+");
    abort_on_error(file == NULL, "fopen() error");

    packet.seq_num = 0;
    packet.status = 0;
    memset(packet.data, 0, sizeof(packet.data));
    memcpy(packet.data, "ok", strlen("ok"));
    abort_on_error(sendto(sockfd, (struct pkt *) &packet, sizeof(packet), 0, cliaddr, len) == -1,
                    "sendto() ok error");

    memset(packet.data, 0, sizeof(packet.data));
    abort_on_error(recvfrom(sockfd, &packet, sizeof(packet), 0, cliaddr, &len) == -1,
                    "recvfrom() error");
    long filesize = strtol((const char *) packet.data, NULL, 0);
    printf("filesize: %ld\n", filesize);

    while ((n = recvfrom(sockfd, &packet, sizeof(packet), 0, cliaddr, &len))) {
        abort_on_error(n == -1, "recvfrom() data error");
        // packet.data[n] = '\0';
        // printf("%s\n", packet.data);
        if (!(strcmp((const char *) packet.data, END_FLAG))) {
            break;
        }

        int num_packet = filesize / n;
        // printf("num_packet: %d\n", num_packet);

        count += n;
        if(!num_packet){
            fwrite(packet.data, sizeof(char), n-(n-filesize), file);
            printf("byte to write: %ld\n", n-(n-filesize));
        }
        else {
            if(count <= filesize) {
                fwrite(packet.data, sizeof(char), n-8, file);
                printf("byte to write: %d\n", n);
            }
            else if ((count > filesize) && (filesize-num_packet*n-8) && !status) {
                    fwrite(packet.data, sizeof(char), filesize-num_packet*(n-8), file);
                    printf("byte to write: %ld\n", filesize-num_packet*(n-8));
                    status = 1;
            }
        }
    }
    printf("Tot Bytes received: %d\n", count);
    fclose(file);
}

int main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in servaddr, cliaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    run(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));

    return 0;
}

For files less than 1400 bytes it works perfectly!
If the file is larger than 1400 bytes (more packet for sent it) then some junk bytes are added.
I can't find why!

Body:
junk bytes at the end of string a dead giveaway for a missing string nul termination problem.

here:

memcpy(packet.data, target, strlen(target));

or here:

memcpy(packet.data, "ok", strlen("ok"));

you're copying the string without the terminator.

now on reception you have no way of knowing where the string ends and neither does fprintf.

So just use strcpy instead of memcpy when copying strings. It'll work and add the nul termination char

strcpy(packet.data, target);

and

strcpy(packet.data, "ok");


问:
Find if key contains value in a map and return a boolean
I have a map within an object in Groovy. The map has keys made from long strings, I want to see if a key in my map contains a certain value within the string and return a boolean.

For example if my map key is 'X1234_RANDOM_STRING', if my parameter is X1234 I want to look in my map and see if the a key with that value exists and return true of false.

Currently I am using .find however this doesn't return a boolean, I thought I could use .containsKey() but this won't work when my parameter may only contain a portion of the string.

```<code>map.find {
   it.key.toString().contains(code)
}
</code>```

答:
If you need boolean output, use collect instead of find.

Here you go:

```<code>def code = 'X1234'
def map = [X1234_RANDOM_STRING: 1]
print map.collect {    it.key.toString().contains(code) }
</code>```

Body:
I have a map within an object in Groovy. The map has keys made from long strings, I want to see if a key in my map contains a certain value within the string and return a boolean.

For example if my map key is 'X1234_RANDOM_STRING', if my parameter is X1234 I want to look in my map and see if the a key with that value exists and return true of false.

Currently I am using .find however this doesn't return a boolean, I thought I could use .containsKey() but this won't work when my parameter may only contain a portion of the string.

map.find {
   it.key.toString().contains(code)
}

Body:
If you need boolean output, use collect instead of find.

Here you go:

def code = 'X1234'
def map = [X1234_RANDOM_STRING: 1]
print map.collect {    it.key.toString().contains(code) }


问:
neo4j windows desktop: Unrecoverable authentication error
I run ne04j-desktop-1.0.6-setup.exe to install the desktop neo4j application, and it proceeds through the install up to the point where it opens, and then gives the message (in a red warning rectangle with only a dismiss button) "Unrecoverable authentication error".

How can I find out what the error is and try to fix it?

答: I had this problem too, try to put the comptability mode on Windows 7. If it don't work immediatly, try to reload the app by clicking on "Reload" in the "Developper" tab.</p>


答:
There's nothing perplexing about the semicolon or parentheses here. Basically, this is one way to assign an anonymous class in Java. If you are not used to this construct, you can certainly create your own class that implements Runnable, and assign it like this:-

```<code>public class YourRunnableClass implements Runnable {
   public void run() {
      ...
   }
}
</code>```

Then you can make it look nicer, like this:-

```<code>javax.swing.SwingUtilities.invokeLater(new YourRunnableClass());
</code>```

P/S: Try not to use "WTF" in your post. :)

Title: Understanding event listeners in java

Body:
There's nothing perplexing about the semicolon or parentheses here. Basically, this is one way to assign an anonymous class in Java. If you are not used to this construct, you can certainly create your own class that implements Runnable, and assign it like this:-

public class YourRunnableClass implements Runnable {
   public void run() {
      ...
   }
}

Then you can make it look nicer, like this:-

javax.swing.SwingUtilities.invokeLater(new YourRunnableClass());

P/S: Try not to use "WTF" in your post. :)


问:
"unable to move temporary installation" when installing dependency packages in R
When I install a package, the prerequisite packages were installed first before the actual package. I get the "unable to move temporary installation" warning for all the prerequisite packages, but no such warning for the actual package. But the package will give error when I load it.

For example, when I install.packages("mlr"), it installed all the dependencies and I got various warnings such as this:

```<code>package ‘BBmisc’ successfully unpacked and MD5 sums checked
Warning in install.packages :
  unable to move temporary installation ‘D:\Documents\R\win-library\3.2\filef3811142c73\BBmisc’ to ‘D:\Documents\R\win-library\3.2\BBmisc’
</code>```

I ignored it because it's just a warning. Unfortunately library(mlr) gave me Error: package ‘BBmisc’ required by ‘mlr’ could not be found, so I couldn't ignore it after all.

install.packages("BBmisc") directly didn't produce the warning.

What gives? How can I work through this, short of installing all the dependencies on my own?

In case session info needed:

```<code>> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_Singapore.1252  LC_CTYPE=English_Singapore.1252
[3] LC_MONETARY=English_Singapore.1252 LC_NUMERIC=C
[5] LC_TIME=English_Singapore.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_3.2.2
</code>```

答:
I tried all the solutions suggested here and elsewhere. I'm running Windows 7 in a large company where antivirus etc. is forced.
The solution for me was:

Uninstall R and RStudio

Delete all files (including hidden) that has to do with R

Install R and RStudio as administrator

Run RStudio as administrator

Only downside is a warning when starting RStudio (running as admin).
All updates and installs works perfect.

Body:
When I install a package, the prerequisite packages were installed first before the actual package. I get the "unable to move temporary installation" warning for all the prerequisite packages, but no such warning for the actual package. But the package will give error when I load it.

For example, when I install.packages("mlr"), it installed all the dependencies and I got various warnings such as this:

package ‘BBmisc’ successfully unpacked and MD5 sums checked
Warning in install.packages :
  unable to move temporary installation ‘D:\Documents\R\win-library\3.2\filef3811142c73\BBmisc’ to ‘D:\Documents\R\win-library\3.2\BBmisc’

I ignored it because it's just a warning. Unfortunately library(mlr) gave me Error: package ‘BBmisc’ required by ‘mlr’ could not be found, so I couldn't ignore it after all.

install.packages("BBmisc") directly didn't produce the warning.

What gives? How can I work through this, short of installing all the dependencies on my own?

In case session info needed:

> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_Singapore.1252  LC_CTYPE=English_Singapore.1252
[3] LC_MONETARY=English_Singapore.1252 LC_NUMERIC=C
[5] LC_TIME=English_Singapore.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_3.2.2


问:
Find the Max and Min element out of all the nested arrays in javascript
I have a array like so:

```<code>var arr = [[12,45,75], [54,45,2],[23,54,75,2]];
</code>```

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

```<code>    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }
</code>```

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.

答:
You can simply merged all the nested array into a single array and then find minimum and maximum value by using Math.min.apply(null, array) and Math.max.apply(null, array)

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];
var merged = [].concat.apply([], arr);
var max = Math.max.apply(null, merged);
var min = Math.min.apply(null, merged);
console.log(max,min)```

Body:
I have a array like so:

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.


问:
Challenging data file format which needs to be read into vars of array containing class objects
I have a program with 5 instances of the class Garbage, garbage has 3 variables I need to update from a data file. The first is a char array, the other two integers. All except the updating the int variables work, and I have no clue of how to achieve that, so any help is greatly appreciated. My code:

```<code>#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
#include <iomanip>

using namespace std;

class Garbage {
  public:
    void writeData();
    void updateFromFile( ifstream & file );
  private:
    char name[40];
    int num1;
    int num2;
};

void Garbage::writeData() {
  cout << name << ", " << num1 << ", " << num2 << endl;
}

void Garbage::updateFromFile ( ifstream & file ) {

  if ( !file.eof() ) {

    file.getline(name, STRLEN);

    /*
    Int variables from Garbage class need to be updated here
    */

  }

}

void readFile() {

  ifstream infile("data.txt");

  for(int i = 0; i < sizeof(garbages)/sizeof(garbages[0]); i++) {
    garbages[i].updateFromFile(infile);
  }

}

Garbage garbages[5];

int main() {
  readFile();

  for(int i = 0; i < sizeof(garbages)/sizeof(garbages[0]; i++) {
    garbages[i].writeData();
  }

  return 0;
}
</code>```

The data structure of "data.txt" is as follows:

```<code>lorem A
10 20
ipsum B
20 30
dolor C
30 40
sit D
40 50
amet E
50 60
</code>```

lorem is the char array (may include whitespaces!), 10 is num1 and 20 is num2 and so on. Due to this being a school assignment, I cannot change the structure of the c++ code nor the data file structure. And If it's possible to achieve this without additional preprocessing directives, that would be preferable.

Any and all input is greatly appreciated!

Edit: fixed class member function naming inconsistencies and poor use of sizeof(). I also added an optional letter in name fields of the data structure showing that name may include whitespaces, and thus I can't rely on the ">>" operator alone and must use getline.

答:
Stream operators consume whitespace. All you need is

```<code>void Letter::updateFromFile ( ifstream & file ) {
  file.getline(name, STRLEN);
  file >> num1 >> num2 >> ws; // eat the end of line
}
</code>```

Additional:
If you have control over the parameter, I would change it to istream &, because there is nothing file stream specific going on. Strive to use the least specific type that works correctly.

C style arrays are more quirky, harder to use safely, and less featureful than std::array and std::vector. The only reason to use them today is to share definitions with C code.

Body:
I have a program with 5 instances of the class Garbage, garbage has 3 variables I need to update from a data file. The first is a char array, the other two integers. All except the updating the int variables work, and I have no clue of how to achieve that, so any help is greatly appreciated. My code:

#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
#include <iomanip>

using namespace std;

class Garbage {
  public:
    void writeData();
    void updateFromFile( ifstream & file );
  private:
    char name[40];
    int num1;
    int num2;
};

void Garbage::writeData() {
  cout << name << ", " << num1 << ", " << num2 << endl;
}

void Garbage::updateFromFile ( ifstream & file ) {

  if ( !file.eof() ) {

    file.getline(name, STRLEN);

    /*
    Int variables from Garbage class need to be updated here
    */

  }

}

void readFile() {

  ifstream infile("data.txt");

  for(int i = 0; i < sizeof(garbages)/sizeof(garbages[0]); i++) {
    garbages[i].updateFromFile(infile);
  }

}

Garbage garbages[5];

int main() {
  readFile();

  for(int i = 0; i < sizeof(garbages)/sizeof(garbages[0]; i++) {
    garbages[i].writeData();
  }

  return 0;
}

The data structure of "data.txt" is as follows:

lorem A
10 20
ipsum B
20 30
dolor C
30 40
sit D
40 50
amet E
50 60

lorem is the char array (may include whitespaces!), 10 is num1 and 20 is num2 and so on. Due to this being a school assignment, I cannot change the structure of the c++ code nor the data file structure. And If it's possible to achieve this without additional preprocessing directives, that would be preferable.

Any and all input is greatly appreciated!

Edit: fixed class member function naming inconsistencies and poor use of sizeof(). I also added an optional letter in name fields of the data structure showing that name may include whitespaces, and thus I can't rely on the ">>" operator alone and must use getline.

Body:
Stream operators consume whitespace. All you need is

void Letter::updateFromFile ( ifstream & file ) {
  file.getline(name, STRLEN);
  file >> num1 >> num2 >> ws; // eat the end of line
}

Additional:
If you have control over the parameter, I would change it to istream &, because there is nothing file stream specific going on. Strive to use the least specific type that works correctly.

C style arrays are more quirky, harder to use safely, and less featureful than std::array and std::vector. The only reason to use them today is to share definitions with C code.


问:
Alternative to cntlm to authenticate behind corporate proxy
I'm working in a company that's using a proxy to connect to the internet. Some of my applications, especially package-managers of any kind are unable to connect to the proxy and produce 407 (Proxy Authentication required).

As a first attempt I tried setting the proxy settings manually for each application.
Example:

```<code>python -m pip install six --proxy http://user:pass@proxy:port
</code>```

That did not help.

In a second attempt I set up cntlm as a local proxy to handle the authentication. That didn't help either.

Finally I found out, that we're using Kerberos for authorization. I know there's a patch for cntlm concerning kerberos authentication. But unfortunately this patch is not available for windows. (or I didn't find it)

Another workaround a collegue just informed me about is the Windows 10 linux-subsystem which allows the installation of the unix version of cntlm with the patch. That kinda enables the proxy authorization.
But this does not help me, as my machine is running Windows 7.

My question is:
Are there any alternatives to cntlm capable of handling Authorization process with Kerberos?
(Or did I miss something that could solve my problem with cntlm?)

答: Usually you would configure your proxy to disable authentication for these services (white list for clients IPs requesting a known domain). Or you would set a local replica in your own network, then all clients request your own corporate servers. Then, you update your replica by hand, or you let it go through the proxy without authentication. But in all cases, letting things update themselves automatically is not always a good idea (you could face serious issues if the process goes wrong)</p>

Body:
I'm working in a company that's using a proxy to connect to the internet. Some of my applications, especially package-managers of any kind are unable to connect to the proxy and produce 407 (Proxy Authentication required).

As a first attempt I tried setting the proxy settings manually for each application.
Example:

python -m pip install six --proxy http://user:pass@proxy:port

That did not help.

In a second attempt I set up cntlm as a local proxy to handle the authentication. That didn't help either.

Finally I found out, that we're using Kerberos for authorization. I know there's a patch for cntlm concerning kerberos authentication. But unfortunately this patch is not available for windows. (or I didn't find it)

Another workaround a collegue just informed me about is the Windows 10 linux-subsystem which allows the installation of the unix version of cntlm with the patch. That kinda enables the proxy authorization.
But this does not help me, as my machine is running Windows 7.

My question is:
Are there any alternatives to cntlm capable of handling Authorization process with Kerberos?
(Or did I miss something that could solve my problem with cntlm?)


问:
Handle Login/Password Popup Selenium JAVA
we are trying to authenticate our website https://staging.rockettes.com.
It asks for a user name and password, which we have to supply via our selenium java code.
Can you help?
Thanks,
Rachit</p>

答:
You can used any ways below:

1. By pass with URL:

```<code>String url= "https://" + "username" + ":" + "password" + "@" + "staging.rockettes.com";
driver.get(url);
</code>```

2. Alert

```<code>Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword("username", "password"));
</code>```

3. AutoIT

Autoit script to handle the authentication window:

```<code>WinWaitActive("Windows Security")
Send("username")
Send("{TAB}")
Send("password")
Send("{ENTER}")
</code>```

Save this file as “auth.au3"
Right click on the file and chose “Compile Script (x86)” option and it will make “auth.exe”
Now write the sample java code to use it:

```<code>driver.get("https://staging.rockettes.com/");
Runtime.getRuntime().exec("E:\\AutoIT\\auth.exe");
</code>```

4. Sikuli

```<code>Screen screen = new Screen();
driver = new FirefoxDriver();
driver.get("https://staging.rockettes.com/");
screen.type("C:\\username.png"),"username");
screen.type("C:\\password.png","password");
screen.click("C:\\okButton.png");
</code>```

Body:
You can used any ways below:

1. By pass with URL:

String url= "https://" + "username" + ":" + "password" + "@" + "staging.rockettes.com";
driver.get(url);

2. Alert

Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword("username", "password"));

3. AutoIT

Autoit script to handle the authentication window:

WinWaitActive("Windows Security")
Send("username")
Send("{TAB}")
Send("password")
Send("{ENTER}")

Save this file as “auth.au3"
Right click on the file and chose “Compile Script (x86)” option and it will make “auth.exe”
Now write the sample java code to use it:

driver.get("https://staging.rockettes.com/");
Runtime.getRuntime().exec("E:\\AutoIT\\auth.exe");

4. Sikuli

Screen screen = new Screen();
driver = new FirefoxDriver();
driver.get("https://staging.rockettes.com/");
screen.type("C:\\username.png"),"username");
screen.type("C:\\password.png","password");
screen.click("C:\\okButton.png");


问:
Symfony2 doctrine2 insert record [Semantical Error] The annotation
When trying to insert a record to doctrine, records is inserting but i am getting an error :

[Semantical Error] The annotation "@Expose" in property
  C2Educate\ToolsBundle\Entity\StudentScores::$id was never imported.
  Did you maybe forget to add a "use" statement for this
  annotation? (500 Internal Server Error)

Entity :

```<code><?php

namespace C2Educate\ToolsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\SerializerBundle\Annotation\Type;

/**
* C2Educate\ToolsBundle\Entity\StudentScores
*
* @ORM\Table(name="tbl_student_scores")
* @ORM\Entity
*/
class StudentScores {

/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="tbl_student_scores_id_seq", allocationSize="1", initialValue="1")
 * @Expose
 * @Type("integer")
 */
protected $id;

/**
 * @var integer $studentId
 *
 * @ORM\Column(name="student_id", type="integer", nullable=true)
 * @Assert\NotBlank()
 * @Type("integer")
 */
private $studentId;

/**
 * Get id
 *
 * @return integer
 */
public function getId() {
    return $this->id;
}

   /**
 * Set studentId
 *
 * @param string $studentId
 */
public function setStudentId($studentId) {
    $this->studentId = $studentId;
}

/**
 * Get studentId
 *
 * @return string
 */
public function getStudentId() {
    return $this->studentId;
}
}
</code>```

Controller Script :

```<code>$em = $this->getDoctrine()->getEntityManager();
$sc = new StudentScores();
$sc->setScore((!empty($test->composite) ? $test->composite : 0));
$sc->setTestDate($test->test_date);
$sc->setcreatedBy($loggedinUser);
$sc->setCreatedAt($date);
$sc->setupdatedBy($loggedinUser);
$sc->setUpdatedAt($date);
$sc->setStudentId($returnID);
$em->persist($sc);
$em->flush();
</code>```

答:
You forgot to add use statements as it says in error description. Try this </p>

```<code>use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
</code>```

Body:
When trying to insert a record to doctrine, records is inserting but i am getting an error :

[Semantical Error] The annotation "@Expose" in property
  C2Educate\ToolsBundle\Entity\StudentScores::$id was never imported.
  Did you maybe forget to add a "use" statement for this
  annotation? (500 Internal Server Error)

Entity :

<?php

namespace C2Educate\ToolsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\SerializerBundle\Annotation\Type;

/**
* C2Educate\ToolsBundle\Entity\StudentScores
*
* @ORM\Table(name="tbl_student_scores")
* @ORM\Entity
*/
class StudentScores {

/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="tbl_student_scores_id_seq", allocationSize="1", initialValue="1")
 * @Expose
 * @Type("integer")
 */
protected $id;

/**
 * @var integer $studentId
 *
 * @ORM\Column(name="student_id", type="integer", nullable=true)
 * @Assert\NotBlank()
 * @Type("integer")
 */
private $studentId;

/**
 * Get id
 *
 * @return integer
 */
public function getId() {
    return $this->id;
}

   /**
 * Set studentId
 *
 * @param string $studentId
 */
public function setStudentId($studentId) {
    $this->studentId = $studentId;
}

/**
 * Get studentId
 *
 * @return string
 */
public function getStudentId() {
    return $this->studentId;
}
}

Controller Script :

$em = $this->getDoctrine()->getEntityManager();
$sc = new StudentScores();
$sc->setScore((!empty($test->composite) ? $test->composite : 0));
$sc->setTestDate($test->test_date);
$sc->setcreatedBy($loggedinUser);
$sc->setCreatedAt($date);
$sc->setupdatedBy($loggedinUser);
$sc->setUpdatedAt($date);
$sc->setStudentId($returnID);
$em->persist($sc);
$em->flush();

Body:
You forgot to add use statements as it says in error description. Try this

use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;


问:
robots.txt: user-agent: Googlebot disallow: / Google still indexing
Look at the robots.txt of this site:

fr2.dk/robots.txt

The content is:

```<code>User-Agent: Googlebot
Disallow: /
</code>```

That ought to tell google not to index the site, no?

If true, why does the site appear in google searches?

答:
Besides having to wait, because Google's index updates take some time, also note that if you have other sites linking to your site, robots.txt alone won't be sufficient to remove your site.

Quoting Google's support page "Remove a page or site from Google's search results":

If the page still exists but you don't want it to appear in search results, use robots.txt to prevent Google from crawling it. Note that in general, even if a URL is disallowed by robots.txt we may still index the page if we find its URL on another site. However, Google won't index the page if it's blocked in robots.txt and there's an active removal request for the page.

One possible alternative solution is also mentioned in above document:

Alternatively, you can use a noindex meta tag. When we see this tag on a page, Google will completely drop the page from our search results, even if other pages link to it. This is a good solution if you don't have direct access to the site server. (You will need to be able to edit the HTML source of the page).

Body:
Look at the robots.txt of this site:

fr2.dk/robots.txt

The content is:

User-Agent: Googlebot
Disallow: /

That ought to tell google not to index the site, no?

If true, why does the site appear in google searches?


问:
couldn't find file 'jquery' with type 'application/javascript'
This might seem a repeated question but none of the solutions seem to work for me. I have gem jquery-rails in my Gemfile. Also, the lines

```<code>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
</code>```

And this is my Gemfile:

```<code>source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.1'

# Use SCSS for stylesheets
#gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
#gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
#gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
  # Use mysql as the database for Active Record
  gem 'mysql2'
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

My application.html.erb :

```<code><!DOCTYPE html>
<html>
<head>
  <title></title>
  <%= stylesheet_link_tag 'application', media: 'all' %>
  <%= javascript_include_tag 'application' %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>
</code>```

I cannot start my Rails application. I do not understand what is the issue. My ruby version is 2.1.6
Please help.

答: Go to gemfile and make sure that gem jquery-rails is uncommented. Run bundle install. That should do it.

Body:
This might seem a repeated question but none of the solutions seem to work for me. I have gem jquery-rails in my Gemfile. Also, the lines

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

And this is my Gemfile:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.1'

# Use SCSS for stylesheets
#gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
#gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
#gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
  # Use mysql as the database for Active Record
  gem 'mysql2'
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

My application.html.erb :

<!DOCTYPE html>

  <title></title>
  <%= stylesheet_link_tag 'application', media: 'all' %>
  <%= javascript_include_tag 'application' %>
  <%= csrf_meta_tags %>

<%= yield %>

I cannot start my Rails application. I do not understand what is the issue. My ruby version is 2.1.6
Please help.