问:
C# - Delegates and BackgroundWorkers
I'm new to C# and object-oriented programming in general. I have an application which parses the text files.

By default, the program executes on the main thread and thus the application freezes until execution.

I have 5 void methods which take in a list of string as parameter.

Based on the various CheckBox options, these 5 void methods get executed in combinations.

The BackgroundWorker performs the operation on a different thread. Thus, the application does not freeze.

However, I would require 15+ BackgroundWorkers for every combination.

The following is my code:

```<code>public partial class Form1 : Form
{
    List<string> textFiles = new List<string>();

    public Form1()
    {
        InitializeComponent();
    }

    public void mParsing(List<string> textFiles) { /* parsing logic */ }
    public void iParsing(List<string> textFiles) { /* parsing logic */ }
    public void aParsing(List<string> textFiles) { /* parsing logic */ }
    public void qParsing(List<string> textFiles) { /* parsing logic */ }

    public void Summary()
    {
        // Logic to generate summary
    }

    private void btnGo_Click(object sender, EventArgs e)
    {
        if (checkM.Checked == true && checkI.Checked == false && checkA.Checked == false && checkQ.Checked == false)
        {
            backgroundWorker1.RunWorkerAsync();
        }
        else if (checkM.Checked == true && checkI.Checked == true && checkA.Checked == false && checkQ.Checked == false)
        {
            backgroundWorker2.RunWorkerAsync();
        }

        //So On....
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        mParsing(textFiles);
        Summary();
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("View Summary?", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            string summary = filepath;
            Process.Start("notepad.exe", summary);
        }
    }
    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        mParsing(textFiles);
        iParsing(textFiles);
        Summary();
    }
    private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("View Summary?", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            string summary = filepath;
            Process.Start("notepad.exe", summary);
        }
    }
}
</code>```

The Func<> does not accept void datatype and I am having a bad time understanding the delegates and multi threading.

My problem is, I don't know how to avoid multiple background workers. Can this be implemented with help of delegates?

Update: .NET Framework Version: 4.0

答:
In C# there is async/await which is exactly what you need.
Take this example:

```<code>private async void btnGo_Click(object sender, EventArgs e)
{
    if (checkM.Checked == true && checkI.Checked == false && checkA.Checked == false && checkQ.Checked == false)
    {
        await mParsing(textFiles);
        DialogResult dialogResult = MessageBox.Show("View Summary?", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            string summary = filepath;
            Process.Start("notepad.exe", summary);
        }
    }
}
</code>```

For this to work both functions, btnGo_Click and mParsing must have the keyword async in it's definition. In addition the return type of the parsing function must be changed to Task.

```<code>public async Task mParsing(List<string> textFiles)
{
    //Method containing parsing logic
}
</code>```

Moreover you need some changes to your (now async) mParsing function.
E.g. blocking calls like new WebClient().DownloadString(url) must be replaced with non blocking calls new WebClient().DownloadStringTaskAsync(url)

As there's not always a non blocking call available you can also use Task.Run():

```<code>public async Task mParsing(List<string> textFiles)
{
    await Task.Run(() => {
        //Do blocking calls
    });
}
</code>```

Title: C# - Delegates and BackgroundWorkers

Body:
I'm new to C# and object-oriented programming in general. I have an application which parses the text files.

By default, the program executes on the main thread and thus the application freezes until execution.

I have 5 void methods which take in a list of string as parameter.

Based on the various CheckBox options, these 5 void methods get executed in combinations.

The BackgroundWorker performs the operation on a different thread. Thus, the application does not freeze.

However, I would require 15+ BackgroundWorkers for every combination.

The following is my code:

public partial class Form1 : Form
{
    List<string> textFiles = new List<string>();

    public Form1()
    {
        InitializeComponent();
    }

    public void mParsing(List<string> textFiles) { /* parsing logic */ }
    public void iParsing(List<string> textFiles) { /* parsing logic */ }
    public void aParsing(List<string> textFiles) { /* parsing logic */ }
    public void qParsing(List<string> textFiles) { /* parsing logic */ }

    public void Summary()
    {
        // Logic to generate summary
    }

    private void btnGo_Click(object sender, EventArgs e)
    {
        if (checkM.Checked == true && checkI.Checked == false && checkA.Checked == false && checkQ.Checked == false)
        {
            backgroundWorker1.RunWorkerAsync();
        }
        else if (checkM.Checked == true && checkI.Checked == true && checkA.Checked == false && checkQ.Checked == false)
        {
            backgroundWorker2.RunWorkerAsync();
        }

        //So On....
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        mParsing(textFiles);
        Summary();
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("View Summary?", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            string summary = filepath;
            Process.Start("notepad.exe", summary);
        }
    }
    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        mParsing(textFiles);
        iParsing(textFiles);
        Summary();
    }
    private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("View Summary?", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            string summary = filepath;
            Process.Start("notepad.exe", summary);
        }
    }
}

The Func<> does not accept void datatype and I am having a bad time understanding the delegates and multi threading.

My problem is, I don't know how to avoid multiple background workers. Can this be implemented with help of delegates?

Update: .NET Framework Version: 4.0

Body:
In C# there is async/await which is exactly what you need.
Take this example:

private async void btnGo_Click(object sender, EventArgs e)
{
    if (checkM.Checked == true && checkI.Checked == false && checkA.Checked == false && checkQ.Checked == false)
    {
        await mParsing(textFiles);
        DialogResult dialogResult = MessageBox.Show("View Summary?", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            string summary = filepath;
            Process.Start("notepad.exe", summary);
        }
    }
}

For this to work both functions, btnGo_Click and mParsing must have the keyword async in it's definition. In addition the return type of the parsing function must be changed to Task.

public async Task mParsing(List<string> textFiles)
{
    //Method containing parsing logic
}

Moreover you need some changes to your (now async) mParsing function.
E.g. blocking calls like new WebClient().DownloadString(url) must be replaced with non blocking calls new WebClient().DownloadStringTaskAsync(url)

As there's not always a non blocking call available you can also use Task.Run():

public async Task mParsing(List<string> textFiles)
{
    await Task.Run(() => {
        //Do blocking calls
    });
}


来源: stackexchange

问:
You tube Search API - Video Id Prefix with '-' sign?
Few video Ids are prefixed with '-' sign. When we search these Id's with prefix on Youtube, it says no records found. However, Youtube is able to play these videos.

Eg:

https://www.youtube.com/watch?v=-xYmfZ2Ic_M  (Video will play)

https://www.youtube.com/results?search_query=-xYmfZ2Ic_M (No results
found).

I would like to know: what all characters could come as prefix so that I can allow or remove them before my Youtube API call? Or is there any standard way to handle this thing?

答:
You refer to 'API call' using the URL is not making a API call, its calling the search URL. The URL unfortunatly does not work using a URL encoded parameter.

I suggest to implement this using YouTube API V3. In PHP this correctly retrives the video based on a ID even if it starts with hyphens. I have provided a PHP snippet below...

```<code>//In PHP
function videosListById($service, $part, $params) {
$params = array_filter($params);
$response = $service->videos->listVideos(
    $part,
    $params
);

print_r($response);
}

videosListById($service,
'snippet,contentDetails,statistics',
array('id' => '-xYmfZ2Ic_M'));
</code>```

To see this in action you can visit the following URL;
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videos.list?id=-xYmfZ2Ic_M&part=snippet%2CcontentDetails%2Cstatistics

ContentLicense: CC BY-SA 3.0

Body:
You refer to 'API call' using the URL is not making a API call, its calling the search URL. The URL unfortunatly does not work using a URL encoded parameter.

I suggest to implement this using YouTube API V3. In PHP this correctly retrives the video based on a ID even if it starts with hyphens. I have provided a PHP snippet below...

//In PHP
function videosListById($service, $part, $params) {
$params = array_filter($params);
$response = $service->videos->listVideos(
    $part,
    $params
);

print_r($response);
}

videosListById($service,
'snippet,contentDetails,statistics',
array('id' => '-xYmfZ2Ic_M'));

To see this in action you can visit the following URL;
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videos.list?id=-xYmfZ2Ic_M&part=snippet%2CcontentDetails%2Cstatistics


问:
pandas get index of previous date
I have pandas dataframe with date a column, I want to add a new column with previous date index in the dataframe. How to achieve this?
Sample df:

```<code>index Date
0 2015-10-03
1 2015-11-03
2 2015-11-30
3 2015-11-30
4 2015-12-03
</code>```

Desired output:

```<code>index Date previous_day
0 2015-10-03 0
1 2015-11-03 0
2 2015-11-30 1
3 2015-11-30 1
4 2015-12-03 3
</code>```

Since at index 1 there is no previous day i want 1 in previous day.

Since date at index 2 is same as index 3 I expect 1 in previous_day for index 3.

Thanks,

答:
I think you need replace index of duplicated values of Date column to NaN and then forwarding filling these values. Also is necessary rename first value of index to 1 and last subtract 1:

Notice: Solution works only if unique monotonic index (0,1,2,...)

```<code>#see notice above
df.reset_index(drop = True, inplace = True)

df['prev'] = df.rename(index={0:1})
              .index.to_series()
              .where(~df['Date'].duplicated()).ffill()
              .astype(int)
              .sub(1).values
print (df)
            Date  prev
index
0     2015-10-03     0
1     2015-11-03     0
2     2015-11-30     1
3     2015-11-30     1
4     2015-12-03     3
</code>```

Title: pandas get index of previous date

Body:
I have pandas dataframe with date a column, I want to add a new column with previous date index in the dataframe. How to achieve this?
Sample df:

index Date
0 2015-10-03
1 2015-11-03
2 2015-11-30
3 2015-11-30
4 2015-12-03

Desired output:

index Date previous_day
0 2015-10-03 0
1 2015-11-03 0
2 2015-11-30 1
3 2015-11-30 1
4 2015-12-03 3

Since at index 1 there is no previous day i want 1 in previous day.

Since date at index 2 is same as index 3 I expect 1 in previous_day for index 3.

Thanks,

Body:
I think you need replace index of duplicated values of Date column to NaN and then forwarding filling these values. Also is necessary rename first value of index to 1 and last subtract 1:

Notice: Solution works only if unique monotonic index (0,1,2,...)

#see notice above
df.reset_index(drop = True, inplace = True)

df['prev'] = df.rename(index={0:1})
              .index.to_series()
              .where(~df['Date'].duplicated()).ffill()
              .astype(int)
              .sub(1).values
print (df)
            Date  prev
index
0     2015-10-03     0
1     2015-11-03     0
2     2015-11-30     1
3     2015-11-30     1
4     2015-12-03     3


问:
"unimplemented type 'list' in 'EncodeElement'" when writing dataframe in csv
I have below dataframe

```<code>df_Place:
    Name|Places
    ----+-----------------------
    abc |delhi
    bcd |mumbai,delhi
    cde |chennai,hyderabad,delhi
    def |mumbai
    efg |bangalore,mumbai
    ghi |delhi,bangalore
</code>```

I wanted to have places in form of a matrix so I did below operation

```<code>df_Place$matrix<-as.matrix(strsplit(df_Place$Place,","))
</code>```

I get below dataframe

```<code>Name|Places                 |matrix
----+-----------------------+------------------------------
abc |delhi                  |delhi
bcd |mumbai,delhi           |c("mumbai","delhi")
cde |chennai,hyderabad,delhi|c("chennai","hyderabad","delhi")
def |mumbai                 |mumbai
efg |bangalore,mumbai       |c("bangalore","mumbai")
ghi |delhi,bangalore        |c("delhi","bangalore")
</code>```

now while trying to write this into csv
write.csv(df_Place,"tx.csv")
I get below error:

Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol,  :
unimplemented type 'list' in 'EncodeElement'**

but if I remove the matrix column then it gets written successfully.

I know that it will be very basic, but can someone explain the reason behind this?

答:
It has to do with writing a matrix (with multiple dimensions) to a df in which multiple cols have no dimensions (vector). I found this solution to work (see Outputting a Dataframe in R to a .csv)</p>

```<code># First coerce the data.frame to all-character
df_Place2 = data.frame(lapply(df_Place, as.character), stringsAsFactors=FALSE)

# write file
write.csv(df_place2,"tx.csv")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have below dataframe

df_Place:
    Name|Places
    ----+-----------------------
    abc |delhi
    bcd |mumbai,delhi
    cde |chennai,hyderabad,delhi
    def |mumbai
    efg |bangalore,mumbai
    ghi |delhi,bangalore

I wanted to have places in form of a matrix so I did below operation

df_Place$matrix<-as.matrix(strsplit(df_Place$Place,","))

I get below dataframe

Name|Places                 |matrix
----+-----------------------+------------------------------
abc |delhi                  |delhi
bcd |mumbai,delhi           |c("mumbai","delhi")
cde |chennai,hyderabad,delhi|c("chennai","hyderabad","delhi")
def |mumbai                 |mumbai
efg |bangalore,mumbai       |c("bangalore","mumbai")
ghi |delhi,bangalore        |c("delhi","bangalore")

now while trying to write this into csv
write.csv(df_Place,"tx.csv")
I get below error:

Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol,  :
unimplemented type 'list' in 'EncodeElement'**

but if I remove the matrix column then it gets written successfully.

I know that it will be very basic, but can someone explain the reason behind this?

Body:
It has to do with writing a matrix (with multiple dimensions) to a df in which multiple cols have no dimensions (vector). I found this solution to work (see Outputting a Dataframe in R to a .csv)

# First coerce the data.frame to all-character
df_Place2 = data.frame(lapply(df_Place, as.character), stringsAsFactors=FALSE)

# write file
write.csv(df_place2,"tx.csv")


问:
macbook adb cannot open interface
I am encountering a problem with Android ADB debugging through USB.

Using Macbook Air 2013 and trying to connect Nexus 6 dev phone.

On the MAC Android Studio, android latest sdk is installed.

When I do

```<code>adb kill-server
adb devices
</code>```

I get:

```<code>adb I   661  9881 usb_osx.cpp:259] Found vid=18d1 pid=**** serial=*****
adb I   661  9881 usb_osx.cpp:259]
adb E   661  9881 usb_osx.cpp:331] Could not open interface: e00002c5
adb E   661  9881 usb_osx.cpp:265] Could not find device interface
</code>```

So it found the device, vendor id, product id and serial match what I find in the system information for the Nexus 6.

Following suggestions found online I tried - but no success - the following to resolve:

dis- and reenabling debugging mode on the phone, also switching between USB configs for charging, MTP, PTP, RNDIS, Audio Source, MIDI, always making sure the authoriztation for the Mac's RSA fingerprint is given

closing Android Studio / DDMS, killing adb through 'kill-server' command as well as killing process through Apple activity monitor

run adb as root

reboot the Mac several times

reboot the Nexus 6

reinstall Android SDK completely

tried with another debugging enabled Android Device (Samsung Galaxy Tab, also here adb found correct device info but cannot access interface with same error)

tried with 3 different USB cables, all cables which were originally shipped with Android devices

Through google I learned that error code e00002c5 means the device is already in use by another driver.

I had recently installed Sophos Home Antivir. Thinking that this might prevent ADB from opening the device interface, I uninstalled Sophos completely with the provided uninstaller and rebooted the Mac.

Any hint is appreciated:

which steps to resolve?

as e00002c5 seems to be a clear indicator that another driver has the device in use, how to find out which process that is and how to stop it from doing that

答:
If you are using VirtualBox and have a virtual machine opened, you are probably trying to use adb from your host while it is plugged on your virtual machine. The problem is that you cannot have your device plugged on both at the same time.

Solution : Uncheck your device on the bottom right panel if it is detected by your Virtual Machine.

Title: macbook adb cannot open interface

Body:
I am encountering a problem with Android ADB debugging through USB.

Using Macbook Air 2013 and trying to connect Nexus 6 dev phone.

On the MAC Android Studio, android latest sdk is installed.

When I do

adb kill-server
adb devices

I get:

adb I   661  9881 usb_osx.cpp:259] Found vid=18d1 pid=**** serial=*****
adb I   661  9881 usb_osx.cpp:259]
adb E   661  9881 usb_osx.cpp:331] Could not open interface: e00002c5
adb E   661  9881 usb_osx.cpp:265] Could not find device interface

So it found the device, vendor id, product id and serial match what I find in the system information for the Nexus 6.

Following suggestions found online I tried - but no success - the following to resolve:

dis- and reenabling debugging mode on the phone, also switching between USB configs for charging, MTP, PTP, RNDIS, Audio Source, MIDI, always making sure the authoriztation for the Mac's RSA fingerprint is given

closing Android Studio / DDMS, killing adb through 'kill-server' command as well as killing process through Apple activity monitor

run adb as root

reboot the Mac several times

reboot the Nexus 6

reinstall Android SDK completely

tried with another debugging enabled Android Device (Samsung Galaxy Tab, also here adb found correct device info but cannot access interface with same error)

tried with 3 different USB cables, all cables which were originally shipped with Android devices

Through google I learned that error code e00002c5 means the device is already in use by another driver.

I had recently installed Sophos Home Antivir. Thinking that this might prevent ADB from opening the device interface, I uninstalled Sophos completely with the provided uninstaller and rebooted the Mac.

Any hint is appreciated:

which steps to resolve?

as e00002c5 seems to be a clear indicator that another driver has the device in use, how to find out which process that is and how to stop it from doing that


问:
Google FCM Request
I'm working on the Google FCM message service. I deploy my API with my server it's working fine. But when I do the same within Client Production Service it gives me 401 error.

I'm running Window Service and hitting Restful API. I validate each and everything within Google account also but not able to rectify the same.

答:
I've recently the same problem. I implemented everything right with all parameters. Finally I found the solution. I used the API Key from Google developer console and not from firebase. So go to the following url: https://console.firebase.google.com/project/YOUR_PROJECT_ID/settings/cloudmessaging/

There you can see two API keys. Choose the longer top server key.

After I replaced the key in the header Authorization: key=YOUR_KEY, it finally works.

Title: Google FCM Request


问:
Debian control file dependencies for a program which depends on libcurl.so, libsqlite3.so, libcrypto.so and libpthread.so
I am having a program which depends on libcurl.so, libsqlite3.so, libcrypto.so and libpthread.so

```<code>Package: myscript
Version: 0.1
Section: utils
Priority: optional
Architecture: all
Essential: no
Depends: curl | libcurl3, sqlite3 | libsqlite3-0, libcrypto++9 | libk5crypto3
Maintainer: Your Name
Description: Sample Program
</code>```

My queries are,
1. I want to add libpthread dependency in the control file.My machine(linuxmint-17) is having a file named libthread.so.10. But while I am doing dpkg --get-selections , I am not getting any package containing pthread. It is a fresh installation of linuxmint(17) and I haven't manually installed any packages.
2.How will I ensure that this will work, let us say if libcurl4 or  libcrypto++99 comes in future.Am I following the correct method or am I missing something.

答:
At first, please read Debian documentation about control file.

What you need to specify in debian/control file are the -dev packages in section Source. In the section Package when you describe resulting binary package in most situation line Depends: ${shlibs:Depends}, ${misc:Depends} is sufficient. Make sure dh_shlibdeps is run debian/rules. As far as I know dh_make covers that for you - check the dh_make documentation.

Know the difference between libraries with .so and .so.some.numbers.here extenstions. Nice explanation is provided here.

So, in debian/control you should have one section for source package:

Source: packagename
   Build-Depends: packages-dev, other-packages-needed-for-build
   [other fields]

and one or more section for binary package(s) built from this source:

Package: packagename
   Depends: ${shlibs:Depends}, ${misc:Depends}
   [other fields]

How to determine what packages to put in Build-Depends? If you need option -lfoo to successfully link your software, that means you need to have a file libfoo.so available. The -pthread option implicitly adds -lpthread option. So, for PCRE you need to have libpcre.so file, for pthreads - libpthread.so. When you established names, run dpkg -S with all those file names as a parameters. You may want to grep the results to get only .so files, not .so.something.

```<code>arturcz@szczaw:~$ dpkg -S libpcre.so libpthread.so | grep '\.so$'
libpcre3-dev:amd64: /usr/lib/x86_64-linux-gnu/libpcre.so
libc6-dev:amd64: /usr/lib/x86_64-linux-gnu/libpthread.so
</code>```

So, the packages name you want to put as a Build-Dependencies are: libc6-dev and libpcre3-dev. However, another rule is use in Debian. Some packages are considered as build essential and you do not need to put them into Build-Dependencies. libc6-dev is one of those packages. If you properly debianized your software, ${shlibs:Depends}, ${misc:Depends} would be replaced by proper content.

How will I ensure that this will work, let us say if libcurl4 or libcrypto++99 comes in future.Am I following the correct method or am I missing something.

You won't. If major number changed in the SONAME of the library, it means, the API or behaviour of both of the library changed. You need to compile your software again with the new library, making necessary changes in the code then test it and fix problems.

Further recommended reading:

Debian New Maintainer Guide and Debian Policy - if you are going to do some more with deb packages, those two are worth to spend time reading on. They will answer a lot of questions for you.

This question and answers about shared libraries

Body:
I am having a program which depends on libcurl.so, libsqlite3.so, libcrypto.so and libpthread.so

Package: myscript
Version: 0.1
Section: utils
Priority: optional
Architecture: all
Essential: no
Depends: curl | libcurl3, sqlite3 | libsqlite3-0, libcrypto++9 | libk5crypto3
Maintainer: Your Name
Description: Sample Program

My queries are,
1. I want to add libpthread dependency in the control file.My machine(linuxmint-17) is having a file named libthread.so.10. But while I am doing dpkg --get-selections , I am not getting any package containing pthread. It is a fresh installation of linuxmint(17) and I haven't manually installed any packages.
2.How will I ensure that this will work, let us say if libcurl4 or  libcrypto++99 comes in future.Am I following the correct method or am I missing something.

Body:
At first, please read Debian documentation about control file.

What you need to specify in debian/control file are the -dev packages in section Source. In the section Package when you describe resulting binary package in most situation line Depends: ${shlibs:Depends}, ${misc:Depends} is sufficient. Make sure dh_shlibdeps is run debian/rules. As far as I know dh_make covers that for you - check the dh_make documentation.

Know the difference between libraries with .so and .so.some.numbers.here extenstions. Nice explanation is provided here.

So, in debian/control you should have one section for source package:

Source: packagename
   Build-Depends: packages-dev, other-packages-needed-for-build
   [other fields]

and one or more section for binary package(s) built from this source:

Package: packagename
   Depends: ${shlibs:Depends}, ${misc:Depends}
   [other fields]

How to determine what packages to put in Build-Depends? If you need option -lfoo to successfully link your software, that means you need to have a file libfoo.so available. The -pthread option implicitly adds -lpthread option. So, for PCRE you need to have libpcre.so file, for pthreads - libpthread.so. When you established names, run dpkg -S with all those file names as a parameters. You may want to grep the results to get only .so files, not .so.something.

arturcz@szczaw:~$ dpkg -S libpcre.so libpthread.so | grep '\.so$'
libpcre3-dev:amd64: /usr/lib/x86_64-linux-gnu/libpcre.so
libc6-dev:amd64: /usr/lib/x86_64-linux-gnu/libpthread.so

So, the packages name you want to put as a Build-Dependencies are: libc6-dev and libpcre3-dev. However, another rule is use in Debian. Some packages are considered as build essential and you do not need to put them into Build-Dependencies. libc6-dev is one of those packages. If you properly debianized your software, ${shlibs:Depends}, ${misc:Depends} would be replaced by proper content.

How will I ensure that this will work, let us say if libcurl4 or libcrypto++99 comes in future.Am I following the correct method or am I missing something.

You won't. If major number changed in the SONAME of the library, it means, the API or behaviour of both of the library changed. You need to compile your software again with the new library, making necessary changes in the code then test it and fix problems.

Further recommended reading:

Debian New Maintainer Guide and Debian Policy - if you are going to do some more with deb packages, those two are worth to spend time reading on. They will answer a lot of questions for you.

This question and answers about shared libraries


问:
Validating multiple messages on the same JMS endpoint in Citrus Framework
I'm sending a single message that produces multiple messages, two of which arrive on the same JMS endpoint.

```<code>runner.send(sendMessageBuilder -> sendMessageBuilder.endpoint(inputMessage.getEndpoint())
    .messageType(MessageType.XML)
    .payload(inputMessage.getPayload())
    .header(JMSOUTPUTCORRELATIONID, correlationId));

for(OutputMessage outputMessage : inputMessage.getOutputMessages()) {
     runner.receive(receiveMessageBuilder -> receiveMessageBuilder.endpoint(outputMessage.getEndpoint())
        .schemaValidation(false)
        .payload(outputMessage.getPayload())
        .header(JMSOUTPUTCORRELATIONID, correlationId));
}
</code>```

When validating two messages on the same endpoint I'm having trouble finding a way to match them to their respective expected outputs.
I was wondering if Citrus has a built in way to do this or if I could build in a condition that checks the other expected outputs if the first one fails.

答:
You should use JMS message selectors so you can "pick" one of the messages from that queue based on a technical identifier. This selector can be a JMS message header for instance (in your case the header JMSOUTPUTCORRELATIONID). This way you make sure to receive the message that you want to validate first.

Example usage:

```<code>receive(action -> action.endpoint(someEndpoint)
            .selector("correlationId='Cx1x123456789' AND operation='getOrders'"));
</code>```

Citrus message selector support is described here

Body:
I'm sending a single message that produces multiple messages, two of which arrive on the same JMS endpoint.

runner.send(sendMessageBuilder -> sendMessageBuilder.endpoint(inputMessage.getEndpoint())
    .messageType(MessageType.XML)
    .payload(inputMessage.getPayload())
    .header(JMSOUTPUTCORRELATIONID, correlationId));

for(OutputMessage outputMessage : inputMessage.getOutputMessages()) {
     runner.receive(receiveMessageBuilder -> receiveMessageBuilder.endpoint(outputMessage.getEndpoint())
        .schemaValidation(false)
        .payload(outputMessage.getPayload())
        .header(JMSOUTPUTCORRELATIONID, correlationId));
}

When validating two messages on the same endpoint I'm having trouble finding a way to match them to their respective expected outputs.
I was wondering if Citrus has a built in way to do this or if I could build in a condition that checks the other expected outputs if the first one fails.

Body:
You should use JMS message selectors so you can "pick" one of the messages from that queue based on a technical identifier. This selector can be a JMS message header for instance (in your case the header JMSOUTPUTCORRELATIONID). This way you make sure to receive the message that you want to validate first.

Example usage:

receive(action -> action.endpoint(someEndpoint)
            .selector("correlationId='Cx1x123456789' AND operation='getOrders'"));

Citrus message selector support is described here


问:
How to continue in a loop when the file does not exist?
This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found. </p>

```<code>for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       download(d)

 end
end
</code>```

<p>Any ideas? Thanks </p>

答:
In addition to the check before downloading you can do try-catch. This download is likely to throw an error if file is missing or something (load does, but I don't have download). You get this error for load:

Error using load
Unable to read file 'lala.m'. No such file or directory.

Now the same with try-catch:

```<code>try
   load('lala.m')
catch
   disp('No such file')
end
</code>```

It will display No such file, which might not be the real error thrown by load, but you can do multiple catches.

This doesn't have a large advantage when the only thing that can go wrong is "file does not exist", but if you have multiple possible fail points you can have single try-catch (if you don't care what went wrong, just that something did) instead of a long cascade of ifs checking everything.

Body:
This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found.

for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       download(d)

 end
end

Any ideas? Thanks

Body:
In addition to the check before downloading you can do try-catch. This download is likely to throw an error if file is missing or something (load does, but I don't have download). You get this error for load:

Error using load
Unable to read file 'lala.m'. No such file or directory.

Now the same with try-catch:

try
   load('lala.m')
catch
   disp('No such file')
end

It will display No such file, which might not be the real error thrown by load, but you can do multiple catches.

This doesn't have a large advantage when the only thing that can go wrong is "file does not exist", but if you have multiple possible fail points you can have single try-catch (if you don't care what went wrong, just that something did) instead of a long cascade of ifs checking everything.


问:
why DataOutputStream is preferred in Server Client program
Why DataInputStream/DataOutputStream is used or preferred over any other stream of java like BufferedInputStream/BufferedOutputStream , BufferedReader/BufferedWriter in Socket programming like Server Client program ?

Please explain the difference between them ??

Give the detailed feature of DataOutputStream (like what it does).

And explain explicitly why & when do we need DataInputStream/DataOutputStream  ??

Thanks in Advance.

答:
DataInputStream/DataOutputStream implement DataInput/DataOutput interfaces and hence have methods like writeShort(), readInt() and so on. It is very convenient if you have to read/write data in some primitives (short/int/utf8 string/...) and not just bytes.

On the sending side, you do something like

```<code>OutputStream os = ... // let's say you already have it
DataOutputStream dos = new DataOutputSream();
dos.writeInt(42);
</code>```

In the receiving side, it's

```<code>InputStream is = ... // let's say you already have it
DataInputStream dis = new DataInputStream(is);
int intValue = dis.readInt();
</code>```

Now intValue is 42. You don't have to think about int to bytes coversion, byte order and so on, you just write and then read it with convenient methods.

Body:
DataInputStream/DataOutputStream implement DataInput/DataOutput interfaces and hence have methods like writeShort(), readInt() and so on. It is very convenient if you have to read/write data in some primitives (short/int/utf8 string/...) and not just bytes.

On the sending side, you do something like

OutputStream os = ... // let's say you already have it
DataOutputStream dos = new DataOutputSream();
dos.writeInt(42);

In the receiving side, it's

InputStream is = ... // let's say you already have it
DataInputStream dis = new DataInputStream(is);
int intValue = dis.readInt();

Now intValue is 42. You don't have to think about int to bytes coversion, byte order and so on, you just write and then read it with convenient methods.


问:
Reload div with script tag inside
I have a page where I want to reload the content of a div with a script tag inside. The code I use to reload this div works almost fine except that the script tag inside the div is stripped out after I reload the div.

In the following code, I have tried to explain my situation

```<code><div id="myDiv">
  <?php echo date('Y-m-d H:i:s', time()); ?>
  <script>
    document.write("Script");
  </script>
</div>

<a onclick="reloadDiv();">Reload div</a>

<script>
  function reloadDiv(){
    $("#myDiv").load(location.href+" #myDiv");
  }
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</code>```

So when I press Reload div the date updates but the script disappears

The code I use on my site is different but has the same principle. On my site, I use PHP to add an ID from a database so my script has to be in that div.

答: You are replacing the whole content of your div when the load call returns. You should move your script tag somewhere else, e.g. in the head tag of your document. </p>

Title: Reload div with script tag inside

Body:
I have a page where I want to reload the content of a div with a script tag inside. The code I use to reload this div works almost fine except that the script tag inside the div is stripped out after I reload the div.

In the following code, I have tried to explain my situation

  <?php echo date('Y-m-d H:i:s', time()); ?>

Reload div

So when I press Reload div the date updates but the script disappears

The code I use on my site is different but has the same principle. On my site, I use PHP to add an ID from a database so my script has to be in that div.


问:
How to show the same font which in photoshop on my webpage?
I have a text in photoshop with font: "Arial 17 pt regular strong" how can I write it in css to show the same?

My 2 problems are:

1- the pt unit in photoshop, what is it in css?

2- if the font is bold strong in photoshop, how it will look like in css?

答:
Assuming it's for a paragraph (but if not, just change the selector):

```<code>p {
  font-family: Arial;
  font-style: normal; /* as opposed to 'italic' or 'oblique' */
  font-weight: bold; /* or 700, or 900 */
  font-size: 17px; /* consider using relative sizing, for example with 'em' units */
  line-height: 20px; /* or as appropriate */
}
</code>```

As @Joel notes, in the comments, there is a (potentially vast) difference between pt and px. It's worth noting also that pt is more applicable to the print, rather than screen 'digital' medium.

ContentLicense: CC BY-SA 2.5

Body:
Assuming it's for a paragraph (but if not, just change the selector):

p {
  font-family: Arial;
  font-style: normal; /* as opposed to 'italic' or 'oblique' */
  font-weight: bold; /* or 700, or 900 */
  font-size: 17px; /* consider using relative sizing, for example with 'em' units */
  line-height: 20px; /* or as appropriate */
}

As @Joel notes, in the comments, there is a (potentially vast) difference between pt and px. It's worth noting also that pt is more applicable to the print, rather than screen 'digital' medium.


问:
Remain on page after post
This is a really stupid question, but I'm not sure how to do the following:
I have a web app (ASP .Net Core 1.1 MVC) which, when the user clicks a delete button, calls a delete action on a Web API.
        // GET: Property/Delete/5
        public async Task Delete(int id)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

```<code>        HttpResponseMessage responseMessage = await client.DeleteAsync(url);
        if (responseMessage.IsSuccessStatusCode)
        {
            RedirectToAction("Index");
            return Ok();
        }
        return View("Error");
    }
</code>```

Basically, the user is on the Index page, then he clicks "Delete" next to a record, and I want it to delete the record, but remain on the Index page (but it should refresh the Index page to show the record is gone). Obviously what I'm doing above is wrong, but I'm not sure hwo to do it...

答:
```<code> public async Task Delete(int id) {
     if (!ModelState.IsValid) return BadRequest(ModelState);

                HttpResponseMessage responseMessage = await client.DeleteAsync(url);
                if (responseMessage.IsSuccessStatusCode)
                {
                    return Redirect(Request.Referrer.ToString());
                }
                return View("Error");
            }
</code>```

Title: Remain on page after post

Body:
This is a really stupid question, but I'm not sure how to do the following:
I have a web app (ASP .Net Core 1.1 MVC) which, when the user clicks a delete button, calls a delete action on a Web API.
        // GET: Property/Delete/5
        public async Task Delete(int id)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

        HttpResponseMessage responseMessage = await client.DeleteAsync(url);
        if (responseMessage.IsSuccessStatusCode)
        {
            RedirectToAction("Index");
            return Ok();
        }
        return View("Error");
    }

Basically, the user is on the Index page, then he clicks "Delete" next to a record, and I want it to delete the record, but remain on the Index page (but it should refresh the Index page to show the record is gone). Obviously what I'm doing above is wrong, but I'm not sure hwo to do it...


问:
FB.Login opening in new window
I have this code

```<code>FB.login(function(response) {
   if (response.authResponse) {
     self.location.href='javascript:postToWall()';
   } else {
     window.top.location='https://www.facebook.com/dialog/oauth?client_id=XXXXX&redirect_uri=XXXXX&state=5140df0126eae59fbc72ac733383bda3&canvas=1&fbconnect=0&scope=email+publish_stream';
   }
 }, {scope: 'email,publish_stream'});
</code>```

it's working but opened in pop up, i need to open it in full window. How can i do ?

答:
Try this</p>

```<code>FB.getLoginStatus(function(response)
{
     if (response.status === 'connected')
                 {
                     self.location.href='javascript:postToWall()';
                 }
                 else
                 {
                    window.location.href = 'https://www.facebook.com/dialog/oauth?client_id=xxxx&redirect_uri=xxxx';
                 }
         }, {scope: 'email,publish_stream',
             return_scopes: true
        });
</code>```

Title: FB.Login opening in new window

Body:
I have this code

FB.login(function(response) {
   if (response.authResponse) {
     self.location.href='javascript:postToWall()';
   } else {
     window.top.location='https://www.facebook.com/dialog/oauth?client_id=XXXXX&redirect_uri=XXXXX&state=5140df0126eae59fbc72ac733383bda3&canvas=1&fbconnect=0&scope=email+publish_stream';
   }
 }, {scope: 'email,publish_stream'});

it's working but opened in pop up, i need to open it in full window. How can i do ?

Body:
Try this

FB.getLoginStatus(function(response)
{
     if (response.status === 'connected')
                 {
                     self.location.href='javascript:postToWall()';
                 }
                 else
                 {
                    window.location.href = 'https://www.facebook.com/dialog/oauth?client_id=xxxx&redirect_uri=xxxx';
                 }
         }, {scope: 'email,publish_stream',
             return_scopes: true
        });


问:
Cookie expiration date won't change.
I'm trying to create a cookie and set an expiration date but it stays as "Session". I'm using Google Chrome.

What am I doing wrong?

document.cookie = "savedTests=[{'id':12345678}];expires=" + date.toUTCString() + ";path=/" ;

答:
Try This, Changed some layout for better understanding :

```<code>var cookieName = 'savedTests';
var cookieValue = [
{'id':12345678}
];
var cookieString = JSON.stringify(cookieValue);

var addDays = 2;
var newDate = new Date();
newDate.setTime(newDate.getTime() + (addDays*24*60*60*1000));
var expiresInTime = "expires="+ newDate.toUTCString();
document.cookie = cookieName + "=" + cookieString + ";" + expiresInTime + ";path=/";
</code>```

Result :

Title: Cookie expiration date won't change.

Body:
Try This, Changed some layout for better understanding :

var cookieName = 'savedTests';
var cookieValue = [
{'id':12345678}
];
var cookieString = JSON.stringify(cookieValue);

var addDays = 2;
var newDate = new Date();
newDate.setTime(newDate.getTime() + (addDays*24*60*60*1000));
var expiresInTime = "expires="+ newDate.toUTCString();
document.cookie = cookieName + "=" + cookieString + ";" + expiresInTime + ";path=/";

Result :


问:
MS SQL Server Row GUID Column
I apologize for asking what seems like a tired question, but no forum response or documentation I've read seems to provide an adequate answer.

What is the purpose of the Row GUID Column property in MS SQL Server 2008?

Let me extend on that. I've seen "Don't use GUID as the PK" repeated as the answer for this question, which seems to be completely unrelated to me. If I set Row GUID Column is it forcing that GUID column to be the primary key or something?

To rephrase my original question: If I have a GUID column in my table that does not play any role in indexing, do I stand to gain anything from setting that GUID column as the Row GUID Column?

答: It's not forcing it to be the primary key, the property merely determines if the field will be automatically updated. IF you want to create the GUID in the application and send it in, set this property to false, otherwise set it to true and let the database create it automatically. If the field is the clustered index make sure the default value is NEWSEQUENTIALID(). </p>

Title: MS SQL Server Row GUID Column


问:
MySql SELECT index benefits
Are there significant benefits between the two SQL select ?

```<code>SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;
</code>```

cod_clie is an INDEX field, of course!

答:
SQL indexes enhance performance of SQL select query through arranging values of indexed field in specific sort order which thereby minimizes number of rows in a table to be scanned until matching row is found which contains filter value in that column.

Usually indexes are applied on fields used as filters in SQL select query.

Title: MySql SELECT index benefits

Body:
Are there significant benefits between the two SQL select ?

SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

cod_clie is an INDEX field, of course!


问:
EF6 Querying for the string with newline character
How do I query a string in EF6 that has a newline character (\n) in it? For example, I have a string $"Hello {Environment.Newline} World".

Now I have to find it using Linq, so I'm trying to find it with the following query: (I want to find it using the exact same string with special characters)

```<code>GetEntities<TimeEntry>().FirstOrDefault(t => t.WorkDescription == $"Hello \r\n World")
</code>```

The code above throws an exception:

System.Data.Entity.Core.EntityCommandExecutionException: 'An error
  occurred while executing the command definition. See the inner
  exception for details.'
  Inner exception: SqlException: The data types nvarchar and text are
  incompatible in the equal to operator.

So how should we fix it? Is there any possibility to avoid special characters?

PS. There is a strong restriction for using ToList() methods, we want to avoid it as much as possible and ideally, everything should be done using IQueryable.

答:
Construct the string before the linq call:</p>

```<code>string workDescription = $"Hello {Environment.Newline} World";
GetEntities<TimeEntry>().FirstOrDefault(t => t.WorkDescription == workDescription);
</code>```

Body:
How do I query a string in EF6 that has a newline character (\n) in it? For example, I have a string $"Hello {Environment.Newline} World".

Now I have to find it using Linq, so I'm trying to find it with the following query: (I want to find it using the exact same string with special characters)

GetEntities<TimeEntry>().FirstOrDefault(t => t.WorkDescription == $"Hello \r\n World")

The code above throws an exception:

System.Data.Entity.Core.EntityCommandExecutionException: 'An error
  occurred while executing the command definition. See the inner
  exception for details.'
  Inner exception: SqlException: The data types nvarchar and text are
  incompatible in the equal to operator.

So how should we fix it? Is there any possibility to avoid special characters?

PS. There is a strong restriction for using ToList() methods, we want to avoid it as much as possible and ideally, everything should be done using IQueryable.

Body:
Construct the string before the linq call:

string workDescription = $"Hello {Environment.Newline} World";
GetEntities<TimeEntry>().FirstOrDefault(t => t.WorkDescription == workDescription);


问:
PHPExcell getActiveSheet() not getting all the Columns
When using the PHPExcel IOFactory library, I use the example methods to fetch the active sheet.
But it only returns the first 49 Columns and my Columns go up to 70 Columns.
For some reason it stops at column AW (maybe because that is a date column?)

Some code:

```<code>/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel/Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';

$inputFileName = $current;
$inputFileType = 'Excel2007';
$sheetname = 'Sheet1';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$sheetnames = $objReader->listWorksheetNames($inputFileName);
$objReader->setLoadSheetsOnly($sheetnames[0]);
$objPHPExcel = $objReader->load($inputFileName);

$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
</code>```

Screenshot of my XLS file :

Screenshot of my Debugger:

答:
Ok seems like my XLS file is corrupted. If I try and run an Excel Open and Repair... and I extract all the values, then it only extracts the values up to column AW

Some More Info: The xlsm file was generated using VB code to fill all the data after column AW. So there must be something extra that prevents PHPExcell from reading those fields

Body:
When using the PHPExcel IOFactory library, I use the example methods to fetch the active sheet.
But it only returns the first 49 Columns and my Columns go up to 70 Columns.
For some reason it stops at column AW (maybe because that is a date column?)

Some code:

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel/Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';

$inputFileName = $current;
$inputFileType = 'Excel2007';
$sheetname = 'Sheet1';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$sheetnames = $objReader->listWorksheetNames($inputFileName);
$objReader->setLoadSheetsOnly($sheetnames[0]);
$objPHPExcel = $objReader->load($inputFileName);

$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);

Screenshot of my XLS file :

Screenshot of my Debugger:


问:
Session from javascript
I'd like to inspect the session variable.  Best case something that works in the firebugs little interpreter, but if I have to put it in the file thats fine.  Right now I just made a short PHP to output $_SESSION, but if I could find something analogous to be done right in the browser that would be ideal.  document.cookie doesn't seem to do what im looking for, at least not that i see.

Basically looking for something analogous to $_SESSION that I can use in javascript

EDIT - was trying to see if i could get anything more than, or extract the meaning  PHPSESSID=o147cf52u9d7qr251hc3n6ilu2; ASESSIONID=101wvpe-3FA77F204CFF55BA61E696AD3F62F0F8 on the client-side.   As it stands I guess i can just write a small ajax function to a url that echos the session.  Thanks for the help!

PS - Do those document.cookie values have anything to do with whats inside the session, or are they just identifiers to tell one session from another?

答:
Just look at what cookies are set in your browser: Firefox,
Chrome, etc.

Edit: oooh, after re-reading your question, you want to ACCESS the session data.

That's not possible via JavaScript for very good reason. XSS would be a breeze. Besides, the data is stored on the server, which JS has no access to (thankfully).

It's not possible to do what you're asking.

Title: Session from javascript


问:
show dbs gives "Not Authorized to execute command" error
I've spent some time trying to figure out what is wrong but as I could not find out, I decided to ask here.

I am running MongoDB(Windows 64-bit 2008 R2+) version 3.2.3 on Windows 8, the paths are :

C:\MongoDB\bin for the installation

C:\data\db for the data folder

I've installed following this video and this tutorial from the official documentation.

The first issue might be, as I don't really know if it is an issue at all, the connection between the client(mongo.exe) and the server(mongod.exe).

I lauched mongod.exe via the command line (with administrator rights), everything went fine, I got the message :

```<code>waiting for connections on port 27017
</code>```

but when I launch mongo.exe via a new instance of the command line, the server(mongod.exe) doesn't print a message saying there is a new connection (it was the case in the tutorials I watched)

On the other side, mongo.exe prints

```<code>connecting to : test
</code>```

I don't know if everything is correct at this point but I still tried some basics commands like :

show dbs returns not authorized on admin to execute command

Basically, all the commands I tried had the same error message, even with "fresh" db I just created with use 'dbName'

Some answers online said I have to create a user with proper roles, I tried this one.
Still the same error message not authorized to execute command

My question is the following :

Is is normal that mongod.exe doesn't show a new connection when I launch mongo.exe ? If it is correct then what can I do to make even the basic commands work ?

Additional Informations :

I tried to uninstall/re-install few times, with the "Custom mode" and the "Complete mode" in the Windows installer but it always lead to the same problem.

I also tried to create a MongoDB Service following the official documentation but I'm not really sure if it was a good idea. (I can't add more links but it is in a section in the second link I shared.

Edit section :

I decided to try it on another computer which I have not touched for years, running on Windows 7 64-bit.

I copied the MongoDB installation folder at the root of this computer, created \data\db folder and launched mongod.exe.

Then I launched mongo.exe and this time, mongod.exe printed a message saying there is a new open connection which it doesn't on my actual computer. I think the problem is here because I was able to start the basic tutorial from the official documentation and perform simple commands like create a new db, insert, find, show dbs, etc. Everything that I am not able to do on my actual computer.

So I think the problem is coming from the connection between mongod.exe and mongo.exe

Do you have any idea how I could solve this problem as I have tried uninstalling few times.

答:
one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".

The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.

cmd-1：

```<code>use admin
db.createUser({
  user: "newUsername",
  pwd: "password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
</code>```

cmd-2:

```<code>db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])
</code>```

Body:
I've spent some time trying to figure out what is wrong but as I could not find out, I decided to ask here.

I am running MongoDB(Windows 64-bit 2008 R2+) version 3.2.3 on Windows 8, the paths are :

C:\MongoDB\bin for the installation

C:\data\db for the data folder

I've installed following this video and this tutorial from the official documentation.

The first issue might be, as I don't really know if it is an issue at all, the connection between the client(mongo.exe) and the server(mongod.exe).

I lauched mongod.exe via the command line (with administrator rights), everything went fine, I got the message :

waiting for connections on port 27017

but when I launch mongo.exe via a new instance of the command line, the server(mongod.exe) doesn't print a message saying there is a new connection (it was the case in the tutorials I watched)

On the other side, mongo.exe prints

connecting to : test

I don't know if everything is correct at this point but I still tried some basics commands like :

show dbs returns not authorized on admin to execute command

Basically, all the commands I tried had the same error message, even with "fresh" db I just created with use 'dbName'

Some answers online said I have to create a user with proper roles, I tried this one.
Still the same error message not authorized to execute command

My question is the following :

Is is normal that mongod.exe doesn't show a new connection when I launch mongo.exe ? If it is correct then what can I do to make even the basic commands work ?

Additional Informations :

I tried to uninstall/re-install few times, with the "Custom mode" and the "Complete mode" in the Windows installer but it always lead to the same problem.

I also tried to create a MongoDB Service following the official documentation but I'm not really sure if it was a good idea. (I can't add more links but it is in a section in the second link I shared.

Edit section :

I decided to try it on another computer which I have not touched for years, running on Windows 7 64-bit.

I copied the MongoDB installation folder at the root of this computer, created \data\db folder and launched mongod.exe.

Then I launched mongo.exe and this time, mongod.exe printed a message saying there is a new open connection which it doesn't on my actual computer. I think the problem is here because I was able to start the basic tutorial from the official documentation and perform simple commands like create a new db, insert, find, show dbs, etc. Everything that I am not able to do on my actual computer.

So I think the problem is coming from the connection between mongod.exe and mongo.exe

Do you have any idea how I could solve this problem as I have tried uninstalling few times.

Body:
one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".

The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.

cmd-1：

use admin
db.createUser({
  user: "newUsername",
  pwd: "password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

cmd-2:

db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])


问:
Sorting a multidimensional array in javascript?
I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks</p>

```<code>     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
     var nestedArrOne = nestedArr[0];
     var nestedArrTwo = nestedArr[1];
     var newArr = nestedArrOne.concat(nestedArrTwo);
      function showAll(){
        for(var i=0; i<newArr.length; i++){
        for(var j=0; j<newArr[i].length; j++){
        console.log(newArr[i][j]);
                }
            }
       }

       showAll();
</code>```

答:
You could iterate the nested array and check if the item is an array, then call the function again for the inner array.

function iter(array) {
    var i;                               // declare index
    for (i = 0; i < array.length; i++) { // iterate array
        if (Array.isArray(array[i])) {   // check if item is an array
            iter(array[i]);              // if so, call iter with item
            continue;                    // and continue the loop
        }
        console.log(array[i]);           // the wanted output
    }
}

var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
iter(nestedArr);```

Body:
I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks

     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
     var nestedArrOne = nestedArr[0];
     var nestedArrTwo = nestedArr[1];
     var newArr = nestedArrOne.concat(nestedArrTwo);
      function showAll(){
        for(var i=0; i<newArr.length; i++){
        for(var j=0; j<newArr[i].length; j++){
        console.log(newArr[i][j]);
                }
            }
       }

       showAll();


问:
How to restore gzipped Monogdb single collection?
Hye everyone, I am new to mongodb I dumped one of my collection using following command mongodump --db somedb --collection somecollection --out - | gzip > collectiondump.gz given on the link now when I try to restore it using mongorestore it gives Error dont know what to do with file.

kindly help me I used this way because the answer in the given link got too much upvotes

Error image

答:
You can just add gzip to the restore command:</p>

```<code>mongorestore --gzip --db projectx userprofiles/
</code>```

Body:
You can just add gzip to the restore command:

mongorestore --gzip --db projectx userprofiles/


问:
Converting a date to a (non human-readable) string in Swift 3
I have a Date object, like so:

```<code> 2017-06-08 08:36:16 +0000
</code>```

I need to convert this to a string, in this form:

```<code>"2017-06-08T08:36:16Z"
</code>```

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

答:
Try this

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SS'Z'"
let dateDate =  NSDate()
let stringDate = dateFormatter.string(from: date as Date)
</code>```

Where date is your Date object in 2017-06-08 08:36:16 +0000 format

Body:
I have a Date object, like so:

 2017-06-08 08:36:16 +0000

I need to convert this to a string, in this form:

"2017-06-08T08:36:16Z"

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

Body:
Try this

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SS'Z'"
let dateDate =  NSDate()
let stringDate = dateFormatter.string(from: date as Date)

Where date is your Date object in 2017-06-08 08:36:16 +0000 format


问:
Uncaught Exception at appium run (appium-14.1.16)
I am running appium 1.4.1.16 at Ubuntu. After Starting appium server using below command :

```<code>appium &
</code>```

I am getting below uncaught Exception:

error: uncaughtException: Cannot find module 'internal/fs' date=Sun Feb 26 2017 13:08:48 GMT+0600 (BDT), pid=18190, uid=1000, gid=1000, cwd=/home/pc/.linuxbrew/lib/node_modules/appium, execPath=/home/pc/.linuxbrew/Cellar/node/7.5.0/bin/node, version=v7.5.0, argv=[/home/pc/.linuxbrew/Cellar/node/7.5.0/bin/node, /home/pc/.linuxbrew/bin/appium], rss=99041280, heapTotal=79945728, heapUsed=46807408, external=204307, loadavg=[0.67529296875, 0.73681640625, 0.74658203125], uptime=3424, trace=[column=15, file=module.js, function=Function.Module._resolveFilename, line=470, method=Module._resolveFilename, native=false, column=25, file=module.js, function=Function.Module._load, line=418, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=20, file=evalmachine., function=null, line=18, method=null, native=false, column=1, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/fs.js, function=, line=11, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=27, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js, function=, line=3, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=10, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/lib/reader.js, function=, line=4, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=18, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/fstream.js, function=, line=2, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false], stack=[Error: Cannot find module 'internal/fs',     at Function.Module._resolveFilename (module.js:470:15),     at Function.Module._load (module.js:418:25),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at evalmachine.:18:20,     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/fs.js:11:1),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12),     at Function.Module._load (module.js:439:3),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js:3:27),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12),     at Function.Module._load (module.js:439:3),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/lib/reader.js:4:10),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12),     at Function.Module._load (module.js:439:3),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/fstream.js:2:18),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12)]

答: Looks like you have installed node using brew in Linux. Suggest downloading node directly and then unpack it and add bin folder to your path. Use the npm in the bin folder to install appium npm install -g appium.

Body:
I am running appium 1.4.1.16 at Ubuntu. After Starting appium server using below command :

appium &

I am getting below uncaught Exception:

error: uncaughtException: Cannot find module 'internal/fs' date=Sun Feb 26 2017 13:08:48 GMT+0600 (BDT), pid=18190, uid=1000, gid=1000, cwd=/home/pc/.linuxbrew/lib/node_modules/appium, execPath=/home/pc/.linuxbrew/Cellar/node/7.5.0/bin/node, version=v7.5.0, argv=[/home/pc/.linuxbrew/Cellar/node/7.5.0/bin/node, /home/pc/.linuxbrew/bin/appium], rss=99041280, heapTotal=79945728, heapUsed=46807408, external=204307, loadavg=[0.67529296875, 0.73681640625, 0.74658203125], uptime=3424, trace=[column=15, file=module.js, function=Function.Module._resolveFilename, line=470, method=Module._resolveFilename, native=false, column=25, file=module.js, function=Function.Module._load, line=418, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=20, file=evalmachine., function=null, line=18, method=null, native=false, column=1, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/fs.js, function=, line=11, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=27, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js, function=, line=3, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=10, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/lib/reader.js, function=, line=4, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=18, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/fstream.js, function=, line=2, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false], stack=[Error: Cannot find module 'internal/fs',     at Function.Module._resolveFilename (module.js:470:15),     at Function.Module._load (module.js:418:25),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at evalmachine.:18:20,     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/fs.js:11:1),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12),     at Function.Module._load (module.js:439:3),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js:3:27),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12),     at Function.Module._load (module.js:439:3),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/lib/reader.js:4:10),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12),     at Function.Module._load (module.js:439:3),     at Module.require (module.js:498:17),     at require (internal/module.js:20:19),     at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/fstream.js:2:18),     at Module._compile (module.js:571:32),     at Object.Module._extensions..js (module.js:580:10),     at Module.load (module.js:488:32),     at tryModuleLoad (module.js:447:12)]


问:
how to pass jquery variable one page to another?
index.php

```<code><script>
  $(document).ready(function() {
    $("#submit").click(function() {
    var field = $("#field").val();
    $("#popular_colleges" ).load( "xyz.php");
    $("#popular_colleges").on( "click", ".pagination a", function (e){
      e.preventDefault();
      $("imagen").show();
      var page = $(this).attr("data-page");
      $("#popular_colleges").load("xyz.php",{"page":page}, function(){
        $("imagen").hide();
      });
    });
  });
</script>
</code>```

xyz.php

```<code>//another page code
</code>```

Here I having two pages i.e. index.php and xyz.php now I want to post  index.php page variable (var field) to xyz.php. How can I do this ? can anyone help me please ?

Thank You

答:
You can use $.get(), or $.post(), or the more powerful and complex $.ajax().

For a simple value called page, get or post should be sufficient:

```<code>$.post('/path/to/other-page.php', {page: page}, function(data){
    console.log(data); // what your other page returned
});
</code>```

Body:
index.php

xyz.php

//another page code

Here I having two pages i.e. index.php and xyz.php now I want to post  index.php page variable (var field) to xyz.php. How can I do this ? can anyone help me please ?

Thank You

Body:
You can use $.get(), or $.post(), or the more powerful and complex $.ajax().

For a simple value called page, get or post should be sufficient:

$.post('/path/to/other-page.php', {page: page}, function(data){
    console.log(data); // what your other page returned
});


答:
Session data is stored on the server. It isn't accessible to client-side JavaScript unless you manually expose it (e.g. by writing a PHP program that dumps it to JSON and delivers it over HTTP).

The browser just gets a cookie containing a token that identifiers which packet of session data the server side programs should open for a given client.

Title: Session from javascript

Body:
I'd like to inspect the session variable.  Best case something that works in the firebugs little interpreter, but if I have to put it in the file thats fine.  Right now I just made a short PHP to output $_SESSION, but if I could find something analogous to be done right in the browser that would be ideal.  document.cookie doesn't seem to do what im looking for, at least not that i see.

Basically looking for something analogous to $_SESSION that I can use in javascript

EDIT - was trying to see if i could get anything more than, or extract the meaning  PHPSESSID=o147cf52u9d7qr251hc3n6ilu2; ASESSIONID=101wvpe-3FA77F204CFF55BA61E696AD3F62F0F8 on the client-side.   As it stands I guess i can just write a small ajax function to a url that echos the session.  Thanks for the help!

PS - Do those document.cookie values have anything to do with whats inside the session, or are they just identifiers to tell one session from another?


问:
How to select top 1 and ordered by date in Oracle SQL?
There is a clear answer how to select top 1:

```<code>select * from table_name where rownum = 1
</code>```

and how to order by date in descending order:

```<code>select * from table_name order by trans_date desc
</code>```

but they does not work togeather (rownum is not generated according to trans_date):

```<code>... where rownum = 1 order by trans_date desc
</code>```

The question is how to select top 1 also ordered by date?

答:
Modern Oracle versions have FETCH FIRST:

```<code>select * from table_name order by trans_date desc
fetch first 1 row only
</code>```

Body:
There is a clear answer how to select top 1:

select * from table_name where rownum = 1

and how to order by date in descending order:

select * from table_name order by trans_date desc

but they does not work togeather (rownum is not generated according to trans_date):

... where rownum = 1 order by trans_date desc

The question is how to select top 1 also ordered by date?

Body:
Modern Oracle versions have FETCH FIRST:

select * from table_name order by trans_date desc
fetch first 1 row only


答:
To post var field = $("#field").val(); from index.php to xyz.php you have to use the jquery ajax(). To use this you have to include the jquery library in your page and its syntax is like:

```<code>$.ajax({
    url : 'xyz.php',
    method : 'post',
    data : {
        field: field
        // key: value pair
    },
    success: function(response){
        // here response in the response you get from xyz.php
    }
});

xyz.php: you can get the posted value like:

$field = $_POST['field'];
</code>```

Title: how to pass jquery variable one page to another?

Body:
To post var field = $("#field").val(); from index.php to xyz.php you have to use the jquery ajax(). To use this you have to include the jquery library in your page and its syntax is like:

$.ajax({
    url : 'xyz.php',
    method : 'post',
    data : {
        field: field
        // key: value pair
    },
    success: function(response){
        // here response in the response you get from xyz.php
    }
});

xyz.php: you can get the posted value like:

$field = $_POST['field'];


问:
UITextField should accept only positive integers and give alert message for rest
What Code I need to write to make my UITextField accept only positive integers(Whole numbers) other than setting keyboard Type to numbers only. And it should alert user when they input characters/fractions/Negative numbers/Special Characters. Kindly, Let me know. Thank you.</p>

答:
What I do, is to create avalidate function, which I call every time the UITextFieldDelegate method - textFieldDidEndEditing is fired.

The other option is to validate all fields at the end when you save information.

For integers I found that the following works well (Using NSScanner):

```<code>- (bool)validateFields {
    if (textField.text.length > 0) {
        NSScanner *scanner = [NSScanner scannerWithString: textField.text.length.text];
        double d;
        BOOL success = [scanner scanDouble:&d];
        if (!success) {
            return false;
        }
        else
        {
            if(d < 0)
            {
                return false;
            }
        }
    }
}
</code>```

Hope this helps.

Body:
What I do, is to create avalidate function, which I call every time the UITextFieldDelegate method - textFieldDidEndEditing is fired.

The other option is to validate all fields at the end when you save information.

For integers I found that the following works well (Using NSScanner):

- (bool)validateFields {
    if (textField.text.length > 0) {
        NSScanner *scanner = [NSScanner scannerWithString: textField.text.length.text];
        double d;
        BOOL success = [scanner scanDouble:&d];
        if (!success) {
            return false;
        }
        else
        {
            if(d < 0)
            {
                return false;
            }
        }
    }
}

Hope this helps.


问:
"Use of unknown namespace" when adding custom namespace
I'm trying to use custom elements in an RSS feed (to render in XSLT), and I'm trying to namespace them to avoid validator errors. However, I'm getting "Use of unknown namespace".

My understanding is that I can use an arbitrary URL as the namespace URL. However, it seems like I can use only a specific set of namespaces that are built into RSS readers. Is there a way to define a custom namespace without triggering a validator error?

Also, would spec-compliant RSS readers be able to parse RSS feeds with this error?

答: I get the same message from feedvalidator. I think it's just a warning, but regardless the validator is wrong to flag it. One of the great things about xml is that you can create your own namespaces. That the validator complains indicates the authors, who are human, failed to understand the purpose of namespaces. Ignore the warning.</p>


问:
How to get mean directly from a csv row range in R?

Following is my code to read more than 1000 csv files, where each file has over 1000 rows and 4 columns. Each csv file has only 4 columns, such as ID, values, param1, param2. My current code snippet reads each file separately with their respective file names into a data frame. It's pretty clean frame per se. Because it's already implemented, I am only looking for a code that can be integrated to my function.

e.g. input

```<code>200 4.864 ne15 hx1
201 4.872 ne12 hx3
202 4.898 ne10 hx9
203 4.815 ne23 hx1
204 4.699 ne14 hx3
...
212 4.813 ne20 hx2
213 4.763 ne18 hx8
...
</code>```

Output :
e.g.

```<code>index  row#.   value     filename
# mean should be the value for row 2 to 20
# it needs to be output in R under row 202
154    202.0   4.337     1wq.csv
164    225.0   4.358     1wq.csv
174    250.0   4.421     1wq.csv
184    275.0   4.498     1wq.csv
194    300.0   4.513     1wq.csv
</code>```

Instead of getting 2 to 20 conseuctive values from csv file row (18 values) in that column, I want to get the mean value corresponding to values from row 2 to 20. How can I do that?

```<code>#set working directly to the folder where csv files are located
files <- list.files(pattern='.csv')
m = data.frame()
 for (k in 1:length(files)){
    csv = read.csv(files[k], header = FALSE)

    #picking up 2:20 consecutive values, value for row 50,120,150 so on
    data = csv[c(2:20, 50, 120, 150, 175, 200), c(1,2)]

    #-pivot transform col/row- data <- as.data.frame(t(data))
    #but that line screwed up the data
    #when those selected values are with NA/blanks
    data$file = files[k]

    m = rbind(m, data)
 }
</code>```

With thanks to both the answers, I managed the following:
I will try AdamQuek's answer separately again to improve mine.
For now, I am closing this question as solved.

```<code>m = data.frame()
for (k in 1:length(files)) {
  csv = read.csv(files[k], header = FALSE)
  data = csv[c(2:20, 225, 250, 275, 300, 325, 350), c(1,2)]
  data[1,] <- mean(data[c(2:19),c(2)], na.rm=T)
  data <- data[-2:-19,]
  data[c(1),c(1)] = 200
  data$file = files[k]
  data <- as.data.frame(t(data))
  m = rbind(m, data)
}
</code>```

答:
```<code>files <- list.files(pattern='\\.csv')
all <- lapply(files, read.csv, header=FALSE)
all.subset <- lapply(all, function(x)x[c(2:20, 50, 120, 150, 175, 200), c(1,2)])

col.means <- function(x) colMeans(x, na.rm=T)

do.call(rbind, lapply(all.subset, col.means))
</code>```

Edit:

```<code>files <- list.files(pattern='\\.csv')
m <- data.frame()

for (k in files){
    csv <- read.csv(k, header = FALSE)[, c(1,2)]

    v1 <- mean(csv[2:20,1], na.rm=T)
    v2 <- mean(csv[2:20,2], na.rm=T)
    mean.val <- data.frame(v1=v1, v2=v2, file=k)

    subset.data <- csv[c(50, 120, 150, 175, 200),]
    subset.data <- rbind(mean.val, subset.data)

    m <- rbind(m, subset.data)
}
</code>```

Body:
Following is my code to read more than 1000 csv files, where each file has over 1000 rows and 4 columns. Each csv file has only 4 columns, such as ID, values, param1, param2. My current code snippet reads each file separately with their respective file names into a data frame. It's pretty clean frame per se. Because it's already implemented, I am only looking for a code that can be integrated to my function.

e.g. input

200 4.864 ne15 hx1
201 4.872 ne12 hx3
202 4.898 ne10 hx9
203 4.815 ne23 hx1
204 4.699 ne14 hx3
...
212 4.813 ne20 hx2
213 4.763 ne18 hx8
...

Output :
e.g.

index  row#.   value     filename
# mean should be the value for row 2 to 20
# it needs to be output in R under row 202
154    202.0   4.337     1wq.csv
164    225.0   4.358     1wq.csv
174    250.0   4.421     1wq.csv
184    275.0   4.498     1wq.csv
194    300.0   4.513     1wq.csv

Instead of getting 2 to 20 conseuctive values from csv file row (18 values) in that column, I want to get the mean value corresponding to values from row 2 to 20. How can I do that?

#set working directly to the folder where csv files are located
files <- list.files(pattern='.csv')
m = data.frame()
 for (k in 1:length(files)){
    csv = read.csv(files[k], header = FALSE)

    #picking up 2:20 consecutive values, value for row 50,120,150 so on
    data = csv[c(2:20, 50, 120, 150, 175, 200), c(1,2)]

    #-pivot transform col/row- data <- as.data.frame(t(data))
    #but that line screwed up the data
    #when those selected values are with NA/blanks
    data$file = files[k]

    m = rbind(m, data)
 }

With thanks to both the answers, I managed the following:
I will try AdamQuek's answer separately again to improve mine.
For now, I am closing this question as solved.

m = data.frame()
for (k in 1:length(files)) {
  csv = read.csv(files[k], header = FALSE)
  data = csv[c(2:20, 225, 250, 275, 300, 325, 350), c(1,2)]
  data[1,] <- mean(data[c(2:19),c(2)], na.rm=T)
  data <- data[-2:-19,]
  data[c(1),c(1)] = 200
  data$file = files[k]
  data <- as.data.frame(t(data))
  m = rbind(m, data)
}

Body:
files <- list.files(pattern='\\.csv')
all <- lapply(files, read.csv, header=FALSE)
all.subset <- lapply(all, function(x)x[c(2:20, 50, 120, 150, 175, 200), c(1,2)])

col.means <- function(x) colMeans(x, na.rm=T)

do.call(rbind, lapply(all.subset, col.means))

Edit:

files <- list.files(pattern='\\.csv')
m <- data.frame()

for (k in files){
    csv <- read.csv(k, header = FALSE)[, c(1,2)]

    v1 <- mean(csv[2:20,1], na.rm=T)
    v2 <- mean(csv[2:20,2], na.rm=T)
    mean.val <- data.frame(v1=v1, v2=v2, file=k)

    subset.data <- csv[c(50, 120, 150, 175, 200),]
    subset.data <- rbind(mean.val, subset.data)

    m <- rbind(m, subset.data)
}


问:
How do I open Zend Studio/Eclipse Files from a project in Explorer/Finder
In dreamweaver they have  a "Reveal in Finder" function that opens a file that you add to the project in the the file management software of the OS (e.g. finder for the Mac).  I'm running Zend Studio on the Mac, this seems like a simple piece of functionality, yet I can't find it.  Any hints? </p>

答:
This can be done by installing a plugin called PathTools

http://code.google.com/p/pathtools/


问:
Error when connecting Rosbridge (Web Sockets)
I am developing an app for iOS with Swift 3, this application search with the Bonjour service some robots in the local network which use a specific service, for example robot.local and show them in a list. The Bonjour service gives me the domain of the device. This is a example of the domains searched.

Ex.:

robot1.local

robot2.local

The next step, is when the user click an element of the list. This action start a connection by web sockets with the device and connect it for control it with the Iphone. I am using a library called RBManager which use RocketSocket library for connect. This library helps me to connect to RosBridge.

I use this code for connect:

```<code>NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"wss://192.168.0.100:9090"]];
self.socket = [[SRWebSocket alloc] initWithURLRequest:request];
self.socket.delegate = self;
[self.socket open];
</code>```

The problem is when I am install the app by Xcode I have not any problem but when I am install the app by an ipa file or by TestFlight the connection is rejected and shows this error:

managerDidFailWithError Optional(ErrorDomain=NSOSTatusErrorDomain
  Code=-9807 "(null)" UserInfo={_kCFStreamErrorDomainKey=3,
  _kCFStreamErrorCodeKey=-9807})

I found this issue in the library but is not the solution that I need.

I am deactive ATS in the info.plist but I not know how to solve this error. Could anyone help me?

答:
I found the problem. The problem was that my RosBridge backend run with TLS and I didn't implement it.

The solution is implement the authentication in the client and all works :D

Body:
I am developing an app for iOS with Swift 3, this application search with the Bonjour service some robots in the local network which use a specific service, for example robot.local and show them in a list. The Bonjour service gives me the domain of the device. This is a example of the domains searched.

Ex.:

robot1.local

robot2.local

The next step, is when the user click an element of the list. This action start a connection by web sockets with the device and connect it for control it with the Iphone. I am using a library called RBManager which use RocketSocket library for connect. This library helps me to connect to RosBridge.

I use this code for connect:

NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"wss://192.168.0.100:9090"]];
self.socket = [[SRWebSocket alloc] initWithURLRequest:request];
self.socket.delegate = self;
[self.socket open];

The problem is when I am install the app by Xcode I have not any problem but when I am install the app by an ipa file or by TestFlight the connection is rejected and shows this error:

managerDidFailWithError Optional(ErrorDomain=NSOSTatusErrorDomain
  Code=-9807 "(null)" UserInfo={_kCFStreamErrorDomainKey=3,
  _kCFStreamErrorCodeKey=-9807})

I found this issue in the library but is not the solution that I need.

I am deactive ATS in the info.plist but I not know how to solve this error. Could anyone help me?


问:
Third party apps in Apple Watch without internet
I'm trying to compare the possibilities of use beetween Apple WatchOS and Android Wear when it comes to using them without the phone nearby. And without conection to internet (Wi-Fi).

I own a Android Wear and have tested the possibilities but cant get an Apple Watch and all the info I can find is this: https://support.apple.com/en-us/HT205547
It says that with wifi you can: Use apps that support Wi-Fi. But what does it mean to support Wi-Fi? Does that mean third party apps cannot be used without internet in any case?

Thanks very much for the help!

答:
Third party apps can run on watchOS without a network connection even if the Watch is not connected to the paired iPhone.
That piece of documentation you linked is only showing which system apps can be used without being connected to an iPhone with/without network connection.

If your watchOS app is not network based, it can fully function even when the Watch is not connected to the iPhone and there are no known Wifi networks available.


问:
How to continuously stream data to the client in rxjava?
Consider a situation where I have an infinite Stream (java.util.stream.Stream) of data on the server as follows.

```<code>Stream.iterate(0,k-> k++);
</code>```

I need a way, so that I can have a client which can subscribe to this stream and read it's contents using rx.Observable.

I did try to return an Observable from the Controller on the server side, but I get the following Exception java.lang.IllegalArgumentException: No converter found for return value of type : class rx.Observable

Project Setup:

Server and client are Spring Boot applications

Marshalling and Unmarshalling is done using jackson-databind

Specific questions:

What am I missing? (topics to read)

Is there a way to marshal the Observable using any other api?

P.S.

I need a setup where the client can actively subscribe and unsubscribe to the server.

Please feel free to suggest edits to make the question better as I am new to Reactive programming.

答:
I was able to come up with a solution to my question by following Spring Tips: the Spring Web Flux Reactive Client

Since, there is no javadoc available (yet) for the new WebFlux component of Spring 5 as it is not finalized yet (mentioned by  M. Deinum, in his comments), it is not really possible to get to a proper solution unless someone is patient enough to play around with the different methods provided by various classes.

Following links can be used for further viewing and references:

WebFlux Framework- spring doc

Spring Tips: Functional Reactive Endpoints with Spring Framework 5.0

P.S.

Please feel free to edit and update the answer, if you find better links and tutorials.

Body:
Consider a situation where I have an infinite Stream (java.util.stream.Stream) of data on the server as follows.

Stream.iterate(0,k-> k++);

I need a way, so that I can have a client which can subscribe to this stream and read it's contents using rx.Observable.

I did try to return an Observable from the Controller on the server side, but I get the following Exception java.lang.IllegalArgumentException: No converter found for return value of type : class rx.Observable

Project Setup:

Server and client are Spring Boot applications

Marshalling and Unmarshalling is done using jackson-databind

Specific questions:

What am I missing? (topics to read)

Is there a way to marshal the Observable using any other api?

P.S.

I need a setup where the client can actively subscribe and unsubscribe to the server.

Please feel free to suggest edits to make the question better as I am new to Reactive programming.


问:
How to convert las file to ply file?
I want to open my 3D point cloud in MATLAB. But they are in .las files. How can I display them in MATLAB???

I heard about .ply file can open 3D point data on MATLAB. So I want to know how to convert las files to ply files.

答:
There is a .las file reader for matlab here:

https://es.mathworks.com/matlabcentral/fileexchange/48073-lasdata

Once you have the data in matlab you can use these point cloud tools, which are part of the computer vision toolbox:

https://es.mathworks.com/help/vision/3-d-point-cloud-processing.html

If you want to embrace the open source force, I'm writing a Python (easy transition from matlab) library for point cloud processing:

https://github.com/daavoo/pyntcloud

Title: How to convert las file to ply file?