问:
Connection with Python to Webdav
I am trying to upload a file in a webdav server via Python, using webdavclient. I am using this script which is quite straightforward. I download the library both with Python 2 & 3.

```<code>import webdav.client as wc

options = {'webdav_hostname': "https://xxxxxx",
           'webdav_login': "xxx",
            'webdav_password': "xxx"
        }

client = wc.Client(options)
client.upload_sync(remote_path="/storage/test_dir/testfile.txt",
                   local_path="/home/ubuntu/testfile.txt")
</code>```

I constantly get this error:

```<code>    import webdav.client as wc
ImportError: No module named client
</code>```

Although

```<code>:~ nasiantalla$ pip install webdavclient
Requirement already satisfied: webdavclient in ./Library/Python/2.7/lib/python/site-packages
Requirement already satisfied: argcomplete in ./Library/Python/2.7/lib/python/site-packages (from webdavclient)
Requirement already satisfied: lxml in ./Library/Python/2.7/lib/python/site-packages (from webdavclient)
Requirement already satisfied: pycurl in ./Library/Python/2.7/lib/python/site-packages (from webdavclient)

~ nasiantalla$ pip3 install webdavclient
Requirement already satisfied: webdavclient in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
Requirement already satisfied: pycurl in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from webdavclient)
Requirement already satisfied: lxml in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from webdavclient)
Requirement already satisfied: argcomplete in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from webdavclient)
</code>```

Has anyone used this before or had any similar issue?
Thanks!

答:
installation

```<code>$ sudo apt-get install libxml2-dev libxslt-dev python-dev
$ sudo apt-get install libcurl4-openssl-dev python-pycurl
$ sudo easy_install webdavclient
</code>```

update

```<code>$ sudo pip install -U webdavclient
</code>```

Title: Connection with Python to Webdav

Body:
I am trying to upload a file in a webdav server via Python, using webdavclient. I am using this script which is quite straightforward. I download the library both with Python 2 & 3.

import webdav.client as wc

options = {'webdav_hostname': "https://xxxxxx",
           'webdav_login': "xxx",
            'webdav_password': "xxx"
        }

client = wc.Client(options)
client.upload_sync(remote_path="/storage/test_dir/testfile.txt",
                   local_path="/home/ubuntu/testfile.txt")

I constantly get this error:

    import webdav.client as wc
ImportError: No module named client

Although

:~ nasiantalla$ pip install webdavclient
Requirement already satisfied: webdavclient in ./Library/Python/2.7/lib/python/site-packages
Requirement already satisfied: argcomplete in ./Library/Python/2.7/lib/python/site-packages (from webdavclient)
Requirement already satisfied: lxml in ./Library/Python/2.7/lib/python/site-packages (from webdavclient)
Requirement already satisfied: pycurl in ./Library/Python/2.7/lib/python/site-packages (from webdavclient)

~ nasiantalla$ pip3 install webdavclient
Requirement already satisfied: webdavclient in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
Requirement already satisfied: pycurl in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from webdavclient)
Requirement already satisfied: lxml in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from webdavclient)
Requirement already satisfied: argcomplete in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from webdavclient)

Has anyone used this before or had any similar issue?
Thanks!

Body:
installation

$ sudo apt-get install libxml2-dev libxslt-dev python-dev
$ sudo apt-get install libcurl4-openssl-dev python-pycurl
$ sudo easy_install webdavclient

update

$ sudo pip install -U webdavclient


来源: stackexchange

问:
Java Process InputStream bug?
Hey guys. So here is the deal. I have a Java program run a C++ program. The C++ process sends some doubles to the Java program by simply calling write on std::cout with some pointer casting. The Java program uses Process's getInputStream(), reads in 8 bytes and converts them into a double using some byte shifting and Double.longBitsToDouble(). I have made sure that the type sizes as well as byte orders match up between the 2 applications. Now, while this works most of the time, every so often an error occurs.

I have isolated one of the errors to a simple sequence of bytes that I seem to be unable to transfer correctly. Check out the following snippets:

```<code>#include <iostream>

int main(int argc, char** argv) {
  long long l = 0x4048e398b90ae1b6;
  char* ptr = (char*) &l;
  std::cout.write(ptr, 8);
  std::cout.flush();

  //  for (int i = 0; i < 8; ++i)
  //    std::cout.put(ptr[i]);
  //  std::cout.flush()
}
</code>```

And the Java app:

```<code>public static void main(String[] argv) throws IOException {
  Process p = Runtime.getRuntime().exec("prog.exe");
  InputStream is = p.getInputStream();

  for (int i = 0 ; i < 8; ++i) {
    System.err.print(Long.toHexString(is.read()) + " ");
  }
}
</code>```

These are pretty simple examples but they server to demonstrate my problem. When I run this on my Windows 7 machine. I get the following Java output:

```<code>b6 e1 d a b9 98 e3 48
</code>```

The expected output is

```<code>b6 e1 a b9 98 e3 48 40
</code>```

Somehow, an extra 0x0d byte is inserted. However, what is really weird is that if inside the java app we read one more byte (change the 8 to a 9), we get

```<code>b6 e1 d a b9 98 e3 48 40
</code>```

This means that the InputStream actually contained 9 bytes of data and once that extra 0x0d is removed it contains the correct data.

What do you guys think? As I mentioned before, this doesn't happen often but when it does, it is disastrous.

Thanks in advance,
zienkikk

答:
cout is by default opened in text mode, what I would say is happening is that the 0xa (linefeed) character is getting converted to a <CRLF> sequence during output preprocessing.

I don't think it's possible to reliably write binary data to cout (see here for example), so I would convert your desired output into text, and then deserialize on the input side (Java).

ContentLicense: CC BY-SA 2.5

Title: Java Process InputStream bug?

Body:
Hey guys. So here is the deal. I have a Java program run a C++ program. The C++ process sends some doubles to the Java program by simply calling write on std::cout with some pointer casting. The Java program uses Process's getInputStream(), reads in 8 bytes and converts them into a double using some byte shifting and Double.longBitsToDouble(). I have made sure that the type sizes as well as byte orders match up between the 2 applications. Now, while this works most of the time, every so often an error occurs.

I have isolated one of the errors to a simple sequence of bytes that I seem to be unable to transfer correctly. Check out the following snippets:

#include <iostream>

int main(int argc, char** argv) {
  long long l = 0x4048e398b90ae1b6;
  char* ptr = (char*) &l;
  std::cout.write(ptr, 8);
  std::cout.flush();

  //  for (int i = 0; i < 8; ++i)
  //    std::cout.put(ptr[i]);
  //  std::cout.flush()
}

And the Java app:

public static void main(String[] argv) throws IOException {
  Process p = Runtime.getRuntime().exec("prog.exe");
  InputStream is = p.getInputStream();

  for (int i = 0 ; i < 8; ++i) {
    System.err.print(Long.toHexString(is.read()) + " ");
  }
}

These are pretty simple examples but they server to demonstrate my problem. When I run this on my Windows 7 machine. I get the following Java output:

b6 e1 d a b9 98 e3 48

The expected output is

b6 e1 a b9 98 e3 48 40

Somehow, an extra 0x0d byte is inserted. However, what is really weird is that if inside the java app we read one more byte (change the 8 to a 9), we get

b6 e1 d a b9 98 e3 48 40

This means that the InputStream actually contained 9 bytes of data and once that extra 0x0d is removed it contains the correct data.

What do you guys think? As I mentioned before, this doesn't happen often but when it does, it is disastrous.

Thanks in advance,
zienkikk


问:
Sizable input file and submit button on same line
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

```

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

答:
Like this?

.Column {
  display: inline;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Row">
  <label class="Column" style="width: 80px;">Text</label>
  <input class="Column" type="file" />
  <input class="Column" style="width:50px;" type="submit" value="Upload" />
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

Body:
Like this?

.Column {
  display: inline;
  background-color: red;
}

<div class="Row">
  <label class="Column" style="width: 80px;">Text</label>
  <input class="Column" type="file" />
  <input class="Column" style="width:50px;" type="submit" value="Upload" />
</div>


问:
Linear layout's background disappear once on child focus
I have a search layout, let's say named search_holder.xml It's a horizontal linearlayout that contain a search icon, then an edittext for input, and a X icon to clear the input.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:background="@drawable/button_search_images"
    android:orientation="horizontal"
    android:padding="@dimen/tick_icon_distance">

    <ImageView
        android:id="@+id/search_icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="-5dp"
        android:padding="@dimen/tick_icon_distance"
        android:layout_marginLeft="-5dp"
        android:src="@drawable/ic_search" />

    <EditText
        android:id="@+id/search_field"
        android:layout_width="@dimen/search_width"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        android:hint="@string/search_google_images_hint"
        android:inputType="text"
        android:padding="5dp"
        android:textSize="@dimen/search_text_size" />

    <ImageView
        android:id="@+id/btnClear"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/tick_icon_distance"
        android:paddingTop="@dimen/tick_icon_distance"
        android:src="@drawable/ic_x" />
</LinearLayout>
</code>```

Then I include it in another layout:

```<code><include android:id="@+id/search_block"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginRight="@dimen/normal_right_margin"
                layout="@layout/search_holder"
                />
</code>```

The problem occurs when I tap the edittext for the first time. The background of the linearlayout disappear (it became transparent).

Then when I tap outside, the background came back. Click the edittext again and nothing happens. It only happens once when the activity is first created.

This problem happens with API 21 and lower.

I tried to enable/disable hardware accelerator but it won't help.

I don't know if it's the version or am I missing something for the lower version.

Thank you for your time.

EDIT (Containing layout):

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
tools:context=".MyActivity" >

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"  >

    <!--Custom ImageView for drawing multiple drawable to canvas-->
    <MyCustomImageView
        android:id="@+id/editorImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipChildren="true"
        android:scaleType="fitXY" />

    <!--This is for a frame on top of the CustomImageView-->
    <ImageView
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="false" />

<!-- Tools Layouts - The container of the tool set on top -->

<RelativeLayout
    android:id="@+id/vb_action_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@drawable/top_icons_shadow" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="@dimen/small_top_margin"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:visibility="visible" >

        <!-- The included layout here -->
        <include android:id="@+id/search_block"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            layout="@layout/search_holder"
            />

        <!-- A few more button in the tool set -->
        <ImageView
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            android:background="@drawable/icon1" />

        <ImageView
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            android:background="@drawable/btn2" />

        <ImageView
            android:id="@+id/btn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            android:background="@drawable/btn3" />

        <ImageView
            android:id="@+id/btn4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/small_top_margin"
            android:background="@drawable/btn4" />
    </LinearLayout>

    <!-- A top left menu button -->
    <Button
        android:id="@+id/slideMenu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="@dimen/xsmall_bottom_margin"
        android:layout_marginTop="@dimen/xsmall_bottom_margin"
        android:background="@android:color/transparent" />
</RelativeLayout>
</code>```

Note: This layout is in landscape mode

答: The problem is solved by setting android:focusable="true" and  android:focusableInTouchMode="true" to the root LinearyLayout of the holder search_holder.xml

Body:
I have a search layout, let's say named search_holder.xml It's a horizontal linearlayout that contain a search icon, then an edittext for input, and a X icon to clear the input.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:background="@drawable/button_search_images"
    android:orientation="horizontal"
    android:padding="@dimen/tick_icon_distance">

    <ImageView
        android:id="@+id/search_icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="-5dp"
        android:padding="@dimen/tick_icon_distance"
        android:layout_marginLeft="-5dp"
        android:src="@drawable/ic_search" />

    <EditText
        android:id="@+id/search_field"
        android:layout_width="@dimen/search_width"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        android:hint="@string/search_google_images_hint"
        android:inputType="text"
        android:padding="5dp"
        android:textSize="@dimen/search_text_size" />

    <ImageView
        android:id="@+id/btnClear"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/tick_icon_distance"
        android:paddingTop="@dimen/tick_icon_distance"
        android:src="@drawable/ic_x" />
</LinearLayout>

Then I include it in another layout:

<include android:id="@+id/search_block"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginRight="@dimen/normal_right_margin"
                layout="@layout/search_holder"
                />

The problem occurs when I tap the edittext for the first time. The background of the linearlayout disappear (it became transparent).

Then when I tap outside, the background came back. Click the edittext again and nothing happens. It only happens once when the activity is first created.

This problem happens with API 21 and lower.

I tried to enable/disable hardware accelerator but it won't help.

I don't know if it's the version or am I missing something for the lower version.

Thank you for your time.

EDIT (Containing layout):

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
tools:context=".MyActivity" >

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"  >

    <MyCustomImageView
        android:id="@+id/editorImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipChildren="true"
        android:scaleType="fitXY" />

    <ImageView
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="false" />

<RelativeLayout
    android:id="@+id/vb_action_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@drawable/top_icons_shadow" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="@dimen/small_top_margin"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:visibility="visible" >

        <include android:id="@+id/search_block"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            layout="@layout/search_holder"
            />

        <ImageView
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            android:background="@drawable/icon1" />

        <ImageView
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            android:background="@drawable/btn2" />

        <ImageView
            android:id="@+id/btn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/normal_right_margin"
            android:background="@drawable/btn3" />

        <ImageView
            android:id="@+id/btn4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/small_top_margin"
            android:background="@drawable/btn4" />
    </LinearLayout>

    <Button
        android:id="@+id/slideMenu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="@dimen/xsmall_bottom_margin"
        android:layout_marginTop="@dimen/xsmall_bottom_margin"
        android:background="@android:color/transparent" />
</RelativeLayout>

Note: This layout is in landscape mode


问:
Pattern Matcher Android Split a String
Problem Statement: I want to read the USSD codes in the background and want to fetch some values:

E.g

Your data balance left is 400 MB, validity is 20 APR 2017. (need to extract '400 MB')

Your data balance left is 0.04 GB, validity is 20 APR 2017. (I need to extract 0.04 GB)

and so on...

How can I ? Can anyone please help. How can I do these types of splits

答:
Here is a solution to extract what you are looking for, it does not need any pattern matcher class

```<code> private String ussdString = "Your data balance left is 400 MB, validity is 20 APR 2017";
 String[] stringArray = ussdString.split(",");
        String ussdStringData = stringArray[0];
        ussdStringData = ussdStringData.replace("Your data balance left is ", "");
        System.out.println("Data is " + ussdStringData);
</code>```

Simple solution for it

Title: Pattern Matcher Android Split a String

Body:
Here is a solution to extract what you are looking for, it does not need any pattern matcher class

 private String ussdString = "Your data balance left is 400 MB, validity is 20 APR 2017";
 String[] stringArray = ussdString.split(",");
        String ussdStringData = stringArray[0];
        ussdStringData = ussdStringData.replace("Your data balance left is ", "");
        System.out.println("Data is " + ussdStringData);

Simple solution for it


问:
How to save public key from a certificate in .pem format
I am using the below openssl command for storing my public key into a .pem file.

```<code>openssl> x509 -in E:/mycert.pem -pubkey  -out E:/mypubkey.pem
</code>```

But when i try to use this command, it is storing the whole certificate info in the mypubkey.pem file.

I have seen that i can save my public key using

```<code>openssl> x509 -pubkey -noout -in cert.pem > pubkey.pem
</code>```

But it is throwing an error. I can't use ">" operator.

答:
if it is a RSA key

```<code>openssl rsa  -pubout -in my_rsa_key.pem
</code>```

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

Body:
I am using the below openssl command for storing my public key into a .pem file.

openssl> x509 -in E:/mycert.pem -pubkey  -out E:/mypubkey.pem

But when i try to use this command, it is storing the whole certificate info in the mypubkey.pem file.

I have seen that i can save my public key using

openssl> x509 -pubkey -noout -in cert.pem > pubkey.pem

But it is throwing an error. I can't use ">" operator.

Body:
if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.


问:
Many to many sequence prediction with different sequence length
My problem is to predict a sequence of values (t_0, t_1, ... t_{n_post-1}) given the previous timesteps (t_{-n_pre}, t_{-n_pre+1} ... t_{-1}) with Keras' LSTM layer.

Keras supports the the following two cases well:

n_post == 1 (many to one forecast)

n_post == n_pre (many to many
forecast with equal sequence lengths)

But not the version where n_post < n_pre.

To illustrate what I need, I built a simple toy example using a sine wave.

Many to one model forecast

With the following model:

```<code>model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
</code>```

predictions look like this:

Many to many model forecast with n_pre == n_post

The network learns to fit a sine wave with n_pre == n_post pretty well with a model like this:

```<code>model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
</code>```

Many to many model forecast with n_post < n_pre

But now, assume my data looks like this:
dataX or input: (nb_samples, nb_timesteps, nb_features) -> (1000, 50, 1)
dataY or output: (nb_samples, nb_timesteps, nb_features) -> (1000, 10, 1)

After some research I found a way on how to handle these input sizes in Keras, using a model like this:

```<code>model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))
model.add(RepeatVector(10))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
</code>```

But the predictions are really bad:
<img src="https://i.stack.imgur.com/0tYqO.png" alt="Many to many with n_post < n_pre">

Now my questions are:

How can I build a model with n_post < n_pre that doesn't lose information because it has a return_sequences=False?

Using n_post == n_pre and then cropping the output (after training) doesn't work for me because it would still try to fit on a lot of timesteps while only the first few can be predicted with a neural network (the others are not nicely correlated and would distort the result)

答:
After asking this question on the Keras Github page, I got an answer, which I post here for completeness.

The solution is to use a second LSTM layer, after shaping the output with RepeatVector to the desired number of output steps.

```<code>model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))
model.add(RepeatVector(10))
model.add(LSTM(output_dim=hidden_neurons, return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
</code>```

The predictions are looking better now and look like this:

Body:
My problem is to predict a sequence of values (t_0, t_1, ... t_{n_post-1}) given the previous timesteps (t_{-n_pre}, t_{-n_pre+1} ... t_{-1}) with Keras' LSTM layer.

Keras supports the the following two cases well:

n_post == 1 (many to one forecast)

n_post == n_pre (many to many
forecast with equal sequence lengths)

But not the version where n_post < n_pre.

To illustrate what I need, I built a simple toy example using a sine wave.

Many to one model forecast

With the following model:

model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')

predictions look like this:

Many to many model forecast with n_pre == n_post

The network learns to fit a sine wave with n_pre == n_post pretty well with a model like this:

model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')

Many to many model forecast with n_post < n_pre

But now, assume my data looks like this:
dataX or input: (nb_samples, nb_timesteps, nb_features) -> (1000, 50, 1)
dataY or output: (nb_samples, nb_timesteps, nb_features) -> (1000, 10, 1)

After some research I found a way on how to handle these input sizes in Keras, using a model like this:

model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))
model.add(RepeatVector(10))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')

But the predictions are really bad:
<img src="https://i.stack.imgur.com/0tYqO.png" alt="Many to many with n_post < n_pre">

Now my questions are:

How can I build a model with n_post < n_pre that doesn't lose information because it has a return_sequences=False?

Using n_post == n_pre and then cropping the output (after training) doesn't work for me because it would still try to fit on a lot of timesteps while only the first few can be predicted with a neural network (the others are not nicely correlated and would distort the result)

Body:
After asking this question on the Keras Github page, I got an answer, which I post here for completeness.

The solution is to use a second LSTM layer, after shaping the output with RepeatVector to the desired number of output steps.

model = Sequential()
model.add(LSTM(input_dim=1, output_dim=hidden_neurons, return_sequences=False))
model.add(RepeatVector(10))
model.add(LSTM(output_dim=hidden_neurons, return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')

The predictions are looking better now and look like this:


问:
Are histogram bins left or right closed?
When plotting a histogram, do the bins include everything less than and equal to the bin value?

For instance, if I have a bin between 0 and 1, will that bin include everything greater than 0 but less than or equal to 1?

答:
From the NumPy documentation:

All but the last (righthand-most) bin is half-open. In other words, if bins is:

[1, 2, 3, 4]

then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.

matplotlib.pyplot.hist uses this NumPy method.


答:
Looks to me like your Windows shell converts UNIX style line terminator LF ( 0xA ) to Windows Line Terminator CRLF( 0xD OxA ).

Generally it is not advisable to write binary data to the program output stream for this particular reason.  Convert your long data to text and then parse it on a Java side.

Title: Java Process InputStream bug?


问:
Generate and display preview thumbnails for videos html5
I'm working on a video website and I am trying to display preview thumbnails for the videos on a page.

I'm looking for a way to generate and display on hover those mutliple thumbnails for a video. The same way as on adult websites...

答:
Use something like ffmpeg, it's pretty efficient and is available for all platforms. This is an example to make thumbnail every 1 minute:

```<code>ffmpeg -i myvideo.avi -vf fps=1/60 img%03d.jpg
</code>```

More examples: https://trac.ffmpeg.org/wiki/Create%20a%20thumbnail%20image%20every%20X%20seconds%20of%20the%20video

Body:
Use something like ffmpeg, it's pretty efficient and is available for all platforms. This is an example to make thumbnail every 1 minute:

ffmpeg -i myvideo.avi -vf fps=1/60 img%03d.jpg

More examples: https://trac.ffmpeg.org/wiki/Create%20a%20thumbnail%20image%20every%20X%20seconds%20of%20the%20video


问:
Correct format for DateTime.ParseExact when the time is in hh:mmtt format
I am trying to convert time string into a DateTime variable but it throws me an invalid time string exception. Can you please explain what is the problem and how to fix it ?

Here is my code:

```<code>string tmp = "1:30am";
DateTime d = DateTime.ParseExact(tmp, "hh:mmtt", CultureInfo.InvariantCulture);
</code>```

答:
You have to use h:mmtt if 1:30 is allowed as opposed to 01:30, hh is from 01 through 12:

```<code>DateTime d = DateTime.ParseExact(tmp, "h:mmtt", CultureInfo.InvariantCulture);
</code>```

Read: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx#hSpecifier

Body:
I am trying to convert time string into a DateTime variable but it throws me an invalid time string exception. Can you please explain what is the problem and how to fix it ?

Here is my code:

string tmp = "1:30am";
DateTime d = DateTime.ParseExact(tmp, "hh:mmtt", CultureInfo.InvariantCulture);

Body:
You have to use h:mmtt if 1:30 is allowed as opposed to 01:30, hh is from 01 through 12:

DateTime d = DateTime.ParseExact(tmp, "h:mmtt", CultureInfo.InvariantCulture);

Read: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx#hSpecifier


问:
Is there a way to call the `[<-` function in `[` form?
Let's assume that I am a lazy programmer with bad habits (who also happens to not know about plyr/dplyr), I like doing operations like this:

```<code>`[<-`((z<-reshape2::melt(iris)), z[,"value"]>5, 3, 100)
</code>```

Melt iris, then assign the value 100 to the rows where the value is greater than 5, then return all the rows, not just the selected rows. This function is described on the page for ?"["

The same code with replace() (well almost the same)

```<code> z[,"value"] <- replace(i <- ((z <- reshape2::melt(iris))[,"value"]), i > 5, 100)
</code>```

1) But the question is: is there a way to call the [<- function using the standard bracket notation iris[<-, blah, blah, blah, ?]?

edit July 2016: so the purpose of this question is NOT to replicate the operation. The data doesn't matter, the example doesn't matter, the convoluted way of reshaping the data doesn't matter.

答:
To answer your question: ofcourse not. For

```<code>iris[<-, blah, blah, blah, ?]
</code>```

to work, the [ function should take another function (or operator) as a second argument, and [ is a primitive that doesn't allow that.

You might argue "but the function is called [<-". It is not. If you write

```<code>x[i,j,...]
</code>```

Then you call a function [ with first argument x, second argument i and so forth. In your line of code, i is the function <-. The assignment operator is a function indeed:

```<code>> `<-`
.Primitive("<-")
> `<-`("x",1)
> x
[1] 1
</code>```

So what you write in that line, boils down to:

```<code>`[`(iris, <-, blah, blah ... )
</code>```

and that will give an error in R's interpreter; the assignment operator is interpreted as an attempt to assign something. This is clearly invalid code.

You might propose using backticks so it becomes:

```<code>iris[`<-`, blah, blah, ... ]
</code>```

which translates to

```<code>`[`(iris, `<-`, blah, blah ,... )
</code>```

but also that is something that is not and never will be allowed by the primitive [.

Some people suggested you could write your own method, and you can - for classes you defined yourself. But you can't redefine [ itself to allow this for any generic data frame, unless you rewrite the R interpreter to recognize your construct as a call to [<- instead of [.

Body:
Let's assume that I am a lazy programmer with bad habits (who also happens to not know about plyr/dplyr), I like doing operations like this:

`[<-`((z<-reshape2::melt(iris)), z[,"value"]>5, 3, 100)

Melt iris, then assign the value 100 to the rows where the value is greater than 5, then return all the rows, not just the selected rows. This function is described on the page for ?"["

The same code with replace() (well almost the same)

 z[,"value"] <- replace(i <- ((z <- reshape2::melt(iris))[,"value"]), i > 5, 100)

1) But the question is: is there a way to call the [<- function using the standard bracket notation iris[<-, blah, blah, blah, ?]?

edit July 2016: so the purpose of this question is NOT to replicate the operation. The data doesn't matter, the example doesn't matter, the convoluted way of reshaping the data doesn't matter.

Body:
To answer your question: ofcourse not. For

iris[<-, blah, blah, blah, ?]

to work, the [ function should take another function (or operator) as a second argument, and [ is a primitive that doesn't allow that.

You might argue "but the function is called [<-". It is not. If you write

x[i,j,...]

Then you call a function [ with first argument x, second argument i and so forth. In your line of code, i is the function <-. The assignment operator is a function indeed:

> `<-`
.Primitive("<-")
> `<-`("x",1)
> x
[1] 1

So what you write in that line, boils down to:

`[`(iris, <-, blah, blah ... )

and that will give an error in R's interpreter; the assignment operator is interpreted as an attempt to assign something. This is clearly invalid code.

You might propose using backticks so it becomes:

iris[`<-`, blah, blah, ... ]

which translates to

`[`(iris, `<-`, blah, blah ,... )

but also that is something that is not and never will be allowed by the primitive [.

Some people suggested you could write your own method, and you can - for classes you defined yourself. But you can't redefine [ itself to allow this for any generic data frame, unless you rewrite the R interpreter to recognize your construct as a call to [<- instead of [.


问:
.Net Full Text Search Library
I posted a question yesterday about using Nhibernate search with nhibernate v2 and have recieved no responses. This has confirmed to me that I need to reconsider using NHibernate.Search and look at an alternative full text search solution. I want to be able to index and search documents and display the relevant extracts of the documents in the search results.

If I cant use Nhibernate.search there doesnt seem to be much point integrating Lucene into Nhibernate myself, are there any alternatives. I've had a look at Searcharoo, which I like because its code is so well documented that I would be comfortable integrating it into Nhibernate.

Are there any more libraries I should be looking at? Should i just use lucene without Nhibernate.Search?

答:
I used to use DotLucene but ran into a number of problems. a major one was the fact that it required full trust to run.

I have since moved to using SearchAroo: http://www.searcharoo.net/

it uses an XML data store, and i have found its performance to be VERY similar to dot lucene.

if you are looking for another option, i'd definitely take a look.

Title: .Net Full Text Search Library


问:
Form too Large Exception
When I send a large file using a post request the system shows an exception:

```<code>java.lang.IllegalStateException: Form too large1105723>200000
at org.mortbay.jetty.Request.extractParameters(Request.java:1404)
at org.mortbay.jetty.Request.getParameter(Request.java:749)......
</code>```

When I search help for this in Google they give some help e.g.,
         webappcontext.setMaxFormContentSize(5000000);

I am using this code but the problem is not solved

Also I am using the code
    jettyServer.setAttribute("org.mortbay.jetty.Request.maxFormContentSize", 5000000);

But no result

Note:-I am using Jetty-6.1.0

答:
If you use jetty in embedded mode,try this.</p>

```<code>    ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletHandler.setMaxFormContentSize(1024*1024*1024);//size you want to allow.
</code>```

Title: Form too Large Exception

Body:
When I send a large file using a post request the system shows an exception:

java.lang.IllegalStateException: Form too large1105723>200000
at org.mortbay.jetty.Request.extractParameters(Request.java:1404)
at org.mortbay.jetty.Request.getParameter(Request.java:749)......

When I search help for this in Google they give some help e.g.,
         webappcontext.setMaxFormContentSize(5000000);

I am using this code but the problem is not solved

Also I am using the code
    jettyServer.setAttribute("org.mortbay.jetty.Request.maxFormContentSize", 5000000);

But no result

Note:-I am using Jetty-6.1.0

Body:
If you use jetty in embedded mode,try this.

    ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletHandler.setMaxFormContentSize(1024*1024*1024);//size you want to allow.


问:
Kotlin Coroutines the right way in Android
I'm trying to update a list inside the adapter using async, I can see there is too much boilerplate.

Is it the right way to use Kotlin Coroutines?

can this be optimized more?

```<code>fun loadListOfMediaInAsync() = async(CommonPool) {
        try {
            //Long running task
            adapter.listOfMediaItems.addAll(resources.getAllTracks())
            runOnUiThread {
                adapter.notifyDataSetChanged()
                progress.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {progress.dismiss()}
        } catch (o: OutOfMemoryError) {
            o.printStackTrace()
            runOnUiThread {progress.dismiss()}
        }
    }
</code>```

答:
I think you can get rid of runOnUiThread { ... } by using UI context for Android applications instead of CommonPool.

The UI context is provided by the kotlinx-coroutines-android module.

Body:
I'm trying to update a list inside the adapter using async, I can see there is too much boilerplate.

Is it the right way to use Kotlin Coroutines?

can this be optimized more?

fun loadListOfMediaInAsync() = async(CommonPool) {
        try {
            //Long running task
            adapter.listOfMediaItems.addAll(resources.getAllTracks())
            runOnUiThread {
                adapter.notifyDataSetChanged()
                progress.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {progress.dismiss()}
        } catch (o: OutOfMemoryError) {
            o.printStackTrace()
            runOnUiThread {progress.dismiss()}
        }
    }


问:
Ansible: Synchronize from local machine to all other machines in a group
I am trying to transfer a root owned folder on my local machine to root owned folders on all other machines in a group called 'group'.

When I run the playbook it hangs, which makes me think that it might be an ssh issue. However, I can ssh to the remote machines without a password through the command line as user 'me'.

I have the following but I believe it tries to copy from the remote machine to the same remote machine. But I don't think ansible even makes it this far so I think I have two issues to fix.

```<code>  synchronize:
    src: /root/owned/dir/
    dest: /root/owned/dir/
  delegate_to: "{{ hostvars[item].ip_address }}"
  with_items: "{{ groups['group'] }}"
  when: inventory_hostname != "{{item}}"
  become: yes
  become_user: me
</code>```

答:
I went with this workaround</p>

```<code>- local_action: command rsync -av /root/owned/dir/ {{ item }}:/root/owned/dir/
  with_items: "{{ groups['group'] }}"
  when: inventory_hostname != "{{item}}"
  become: no
</code>```

Body:
I am trying to transfer a root owned folder on my local machine to root owned folders on all other machines in a group called 'group'.

When I run the playbook it hangs, which makes me think that it might be an ssh issue. However, I can ssh to the remote machines without a password through the command line as user 'me'.

I have the following but I believe it tries to copy from the remote machine to the same remote machine. But I don't think ansible even makes it this far so I think I have two issues to fix.

  synchronize:
    src: /root/owned/dir/
    dest: /root/owned/dir/
  delegate_to: "{{ hostvars[item].ip_address }}"
  with_items: "{{ groups['group'] }}"
  when: inventory_hostname != "{{item}}"
  become: yes
  become_user: me

Body:
I went with this workaround

- local_action: command rsync -av /root/owned/dir/ {{ item }}:/root/owned/dir/
  with_items: "{{ groups['group'] }}"
  when: inventory_hostname != "{{item}}"
  become: no


问:
How to change inside background color of UISearchBar component on iOS
I know how to remove/change UISearchBar background color around search field:

```<code>[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];
</code>```

But don't know how to do this inside it like that:

This needs to be compatible with iOS 4.3+.

答:
For Swift 3+, use this:

```<code>for subView in searchController.searchBar.subviews {

    for subViewOne in subView.subviews {

        if let textField = subViewOne as? UITextField {

           subViewOne.backgroundColor = UIColor.red

           //use the code below if you want to change the color of placeholder
           let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
        }
     }
}
</code>```

Body:
I know how to remove/change UISearchBar background color around search field:

[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];

But don't know how to do this inside it like that:

This needs to be compatible with iOS 4.3+.

Body:
For Swift 3+, use this:

for subView in searchController.searchBar.subviews {

    for subViewOne in subView.subviews {

        if let textField = subViewOne as? UITextField {

           subViewOne.backgroundColor = UIColor.red

           //use the code below if you want to change the color of placeholder
           let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
        }
     }
}


问:
How do you populate a field from a sibling collection using Mongoose?
I would like to use the populate method in Mongoose to query a collection. Here is my schema:

```<code>var UnitSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    unitNumber: Number,
    members: [MemberSchema],
    orgs: [OrgSchema]
});

var MemberSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    },
    phone: String,
    email: String
});

var OrgSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    sortIndex: Number,
    roles: [RoleSchema]
});

var RoleSchema = new mongoose.Schema({
    name: String,
    sortIndex: Number,
    member: {
        type: Schema.Types.ObjectId,
        ref: 'Member'
    }
});
</code>```

Here is a sample Unit collection:

```<code>{
    "_id": "58da7bd6e7092e8735646ba0",
    "name": "Unit Name",
    "orgs": [
        {
            "name": "Org name",
            "sortIndex": 0,
            "_id": "58da7bd6e7092e8735646c2d",
            "roles": [
                {
                    "name": "Role Name",
                    "sortIndex": 0,
                    "member": "58dbd1e6c9a893a7840472ad"
                }
            ]
        }
     ],
     "members": [
         {
             "name": {
                 "first": "First Name",
                 "last": "Last Name"
             },
             "_id": "58dbd1e6c9a893a7840472ad"
         }
     ]
 }
</code>```

How do I populate a Member doc to the member field in the Roles collection so my output would be like this:

```<code>[
    {
        "name": "Org name",
        "sortIndex": 0,
        "_id": "58da7bd6e7092e8735646c2d",
        "roles": [
            {
                "name": "Role Name",
                "sortIndex": 0,
                "member": {
                    "name": {
                        "first": "First Name",
                        "last": "Last Name"
                     },
                     "_id": "58dbd1e6c9a893a7840472ad"
                }
             }
         ]
     }
 ]
</code>```

Here is the query I was thinking of:

```<code>Unit.findOne({unitNumber: unitNumber}).populate('roles.callings.member').exec(...)
</code>```

答:
Here you go!

```<code>unit.findOne({unitNumber: 543})
.populate('orgs')
.exec(function(err, unitDoc){
    var subDoc = unitDoc.orgs;
    for(var org of subDoc){
        org.populate('roles', function(err, data){
            var rolesDoc = data.roles;
            for(var role of rolesDoc){
                role.populate('member', function(err, rdata){
                    console.log(JSON.stringify(unitDoc));
                })
            }
        })
    }
})
</code>```

You need to populate each sub-documents as done above.

Body:
I would like to use the populate method in Mongoose to query a collection. Here is my schema:

var UnitSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    unitNumber: Number,
    members: [MemberSchema],
    orgs: [OrgSchema]
});

var MemberSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    },
    phone: String,
    email: String
});

var OrgSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    sortIndex: Number,
    roles: [RoleSchema]
});

var RoleSchema = new mongoose.Schema({
    name: String,
    sortIndex: Number,
    member: {
        type: Schema.Types.ObjectId,
        ref: 'Member'
    }
});

Here is a sample Unit collection:

{
    "_id": "58da7bd6e7092e8735646ba0",
    "name": "Unit Name",
    "orgs": [
        {
            "name": "Org name",
            "sortIndex": 0,
            "_id": "58da7bd6e7092e8735646c2d",
            "roles": [
                {
                    "name": "Role Name",
                    "sortIndex": 0,
                    "member": "58dbd1e6c9a893a7840472ad"
                }
            ]
        }
     ],
     "members": [
         {
             "name": {
                 "first": "First Name",
                 "last": "Last Name"
             },
             "_id": "58dbd1e6c9a893a7840472ad"
         }
     ]
 }

How do I populate a Member doc to the member field in the Roles collection so my output would be like this:

[
    {
        "name": "Org name",
        "sortIndex": 0,
        "_id": "58da7bd6e7092e8735646c2d",
        "roles": [
            {
                "name": "Role Name",
                "sortIndex": 0,
                "member": {
                    "name": {
                        "first": "First Name",
                        "last": "Last Name"
                     },
                     "_id": "58dbd1e6c9a893a7840472ad"
                }
             }
         ]
     }
 ]

Here is the query I was thinking of:

Unit.findOne({unitNumber: unitNumber}).populate('roles.callings.member').exec(...)

Body:
Here you go!

unit.findOne({unitNumber: 543})
.populate('orgs')
.exec(function(err, unitDoc){
    var subDoc = unitDoc.orgs;
    for(var org of subDoc){
        org.populate('roles', function(err, data){
            var rolesDoc = data.roles;
            for(var role of rolesDoc){
                role.populate('member', function(err, rdata){
                    console.log(JSON.stringify(unitDoc));
                })
            }
        })
    }
})

You need to populate each sub-documents as done above.


问:
SQLite.swift pod: Swift Compiler Error in Xcode 8.3 beta 2
Project builds fine in Xcode 8.2.1, but in 8.3b2 the pod SQLite.swift produces >18 issues like:

```<code>Swift Compiler Error
  Build a shadowed submodule 'Darwin.POSIX.basic'
  module.modulemap
</code>```

Errors appear to relate to redefinition of basic types such as _int8_t

Is there a simple resolution/workaround?

答:
I was hoping to see this resolved in subsequent betas, but happy to note that this is no longer an issue.

I'm not quite sure which of these items actually resolved it for me:

Xcode Version 8.3 (8E162) - release version

Using SQLite.swift (0.11.2) - I don't think this has changed

Clean Build Folder (Cmd-Opt-Shift-K)

This issue (suspiciously similar to this post) confirms that 0.11.3 of the pod tests against Xcode 8.3

Body:
Project builds fine in Xcode 8.2.1, but in 8.3b2 the pod SQLite.swift produces >18 issues like:

Swift Compiler Error
  Build a shadowed submodule 'Darwin.POSIX.basic'
  module.modulemap

Errors appear to relate to redefinition of basic types such as _int8_t

Is there a simple resolution/workaround?


问:
Big O Notation Time Question
We have 3 functions with big o notations:

```<code>Func A: O(n)
Func B: O(n^2)
Func C: O(2^n)
</code>```

If these functions does n proccesses in 10 seconds, how much time need to proccess 2 * n processes for each functions ? Also if you explain why i will be happy.

Thank You

答:
EDIT: C is 10*2^n, I made a mistake in my answer. I'll leave it below but here is the mistake:

The real formula includes the processing rate, which I left out in my original answer. The processing rate falls away in the first two, but it doesn't in C.

```<code>2^n/p=10 (where p is the processing rate of units/second)
2^n=10*p
y=2^(n*2)/p
y=(2^n)^2/p
y=(10*p)^2/p
y=100*p^2/p
y=100*p (so we need to know the processing rate. If we know n, then we know the processing rate)
</code>```

The units are fine above, as we have seconds^2/seconds = seconds.

Original Answer:

A: 20
B: 40
C: 100
The existing answers already explain A and B. Regarding the C equation, if my mathematics serve me correctly....

Part 1: What does n equal

```<code>2^n=10
log(2^n)=log(10)
n*log(2)=log(10)
n=log(10)/log(2)
</code>```

Part 2: Now replace n with 2*n

```<code>x = 2^(2*n)
x = 2^(2*log(10)/log(2))
x = 100 (thanks excel: =2^(2*LOG(10)/LOG(2)))
</code>```

Still I haven't used logarithms in 6 years, so please be forgiving if I'm wrong.

EDIT: Found a simpler way.

```<code>Given t is orginal time, and y is the new time.
t=2^n
y=2^(n*2)
y=(2^n)^2
y=t^2
y=10^2
y=100
</code>```

Title: Big O Notation Time Question

Body:
We have 3 functions with big o notations:

Func A: O(n)
Func B: O(n^2)
Func C: O(2^n)

If these functions does n proccesses in 10 seconds, how much time need to proccess 2 * n processes for each functions ? Also if you explain why i will be happy.

Thank You

Body:
EDIT: C is 10*2^n, I made a mistake in my answer. I'll leave it below but here is the mistake:

The real formula includes the processing rate, which I left out in my original answer. The processing rate falls away in the first two, but it doesn't in C.

2^n/p=10 (where p is the processing rate of units/second)
2^n=10*p
y=2^(n*2)/p
y=(2^n)^2/p
y=(10*p)^2/p
y=100*p^2/p
y=100*p (so we need to know the processing rate. If we know n, then we know the processing rate)

The units are fine above, as we have seconds^2/seconds = seconds.

Original Answer:

A: 20
B: 40
C: 100
The existing answers already explain A and B. Regarding the C equation, if my mathematics serve me correctly....

Part 1: What does n equal

2^n=10
log(2^n)=log(10)
n*log(2)=log(10)
n=log(10)/log(2)

Part 2: Now replace n with 2*n

x = 2^(2*n)
x = 2^(2*log(10)/log(2))
x = 100 (thanks excel: =2^(2*LOG(10)/LOG(2)))

Still I haven't used logarithms in 6 years, so please be forgiving if I'm wrong.

EDIT: Found a simpler way.

Given t is orginal time, and y is the new time.
t=2^n
y=2^(n*2)
y=(2^n)^2
y=t^2
y=10^2
y=100


问:
Sizable input file and submit button on same line
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

```

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

答:
You can go through the following snippet and I think the issue your facing will be resolved.

.Column {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Row">
  <label class="Column">Text</label>
  <input class="Column" type="file" />
  <input class="Column" type="submit" value="Upload" />
</div></code>```

Body:
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

Body:
You can go through the following snippet and I think the issue your facing will be resolved.

.Column {
  background-color: red;
}

<div class="Row">
  <label class="Column">Text</label>
  <input class="Column" type="file" />
  <input class="Column" type="submit" value="Upload" />
</div>


问:
poedit 2.0 not working with zend framework 3 not catching $this->translate
the problem is that the application is bot getting the sentences to be translated form the views of the web application that have the keyword translate like the one below :

```<code>$this->translate('Login');
</code>```

but the ones from the forms and controllers like this _('Login') is getting

i uninstalled Poedit 2.0 and installed back Poedit 1.8 and now its working

thanks

答:
This is a known problem (Z.F. using the .phtml extension deprecated 20 years ago) that will be fixed in 2.0.1 in a few days.

(BTW, might want to consider emailing support when you have an issue with an app instead of posting on SO…)

Body:
the problem is that the application is bot getting the sentences to be translated form the views of the web application that have the keyword translate like the one below :

$this->translate('Login');

but the ones from the forms and controllers like this _('Login') is getting

i uninstalled Poedit 2.0 and installed back Poedit 1.8 and now its working

thanks


问:
How to handle Microsoft Visual C++ Redistributable for Visual Studio 2017?
First of all, why can't I download it from Microsoft like before?

Second, when I install vcredist 2017 it will replace vcredist 2015(it's removed from "Add or remove program" list), is it fully backward compatible? Version is changed from 14.0.x.x to 14.10.x.x.

C++ Redistributable 14 conflict with VS2017 C++ Redistributable

答:
Thanks @edtheprogrammerguy

Solution from the link:
I found them at : https://www.visualstudio.com/downloads/
by clicking "Expand All",
at the bottom of the page


问:
Python class instance circular referencing in different files using 'IMPORT AS'
I am encountering a problem using a circular importation in Python 2.7

For some reasons, I need this structure, here reduced for the explanation to 4 python files :

```<code>- main.py
- folder
  \- __init__.py
  \- loader.py
  \- folder1
     \- __init__.py
     \- class1.py
  \- folder2
     \- __init__.py
     \- class2.py
</code>```

main.py :

```<code>import folder.loader as LD

LD.a.change_class2()
LD.b.change_class1()
</code>```

loader.py :

```<code>from folder1.class1 import Class1
from folder2.class2 import Class2

a=Class1()
b=Class2()
</code>```

class1.py :

```<code>import folder.loader as LD

class Class1():
    def __init__(self):
        self.pty1=0
    def change_class2(self):
        LD.b.pty2=2
</code>```

class2.py :

```<code>import folder.loader as LD

class Class2():
    def __init__(self):
        self.pty2=0
    def change_class1(self):
        LD.a.pty1=6
</code>```

The code executed is main.py. This script calls the file loader.py which creates an instance for Class1 and Class2. The instances have to communicate and modify each other, explaining the necessity (if I am not wrong) of the file loader.py.

Executing this code returns the error from class1.py :

```<code>    import folder.loader as LD
AttributeError: 'module' object has no attribute 'loader'
</code>```

I have no idea of what is going on here.

Surprisingly, when I remove the part as LD from the importation command line in the classes files, it works perfecly :

class1.py :

```<code>import folder.loader

class Class1():
    def __init__(self):
        self.pty1=0
    def change_class2(self):
        folder.loader.b.pty2=2
</code>```

class2.py :

```<code>import folder.loader

class Class2():
    def __init__(self):
        self.pty2=0
    def change_class1(self):
        folder.loader.a.pty1=6
</code>```

For this example, it's ok, but in the real program I am trying to make, based on this structure, I can't use the complete module path each time I need to communicate with another class instance.

Why am I getting this error ? What can I do to solve this ?
Thank you in advance for your help.

EDIT : replacing import folder.loader as LD by from .. import loader as LD now returns another error, that I don't understand :

```<code>    from .. import loader as LD
ImportError: cannot import name loader
</code>```

答: I solved the problem simply by using Python 3, without code changes.</p>

Body:
I am encountering a problem using a circular importation in Python 2.7

For some reasons, I need this structure, here reduced for the explanation to 4 python files :

- main.py
- folder
  \- __init__.py
  \- loader.py
  \- folder1
     \- __init__.py
     \- class1.py
  \- folder2
     \- __init__.py
     \- class2.py

main.py :

import folder.loader as LD

LD.a.change_class2()
LD.b.change_class1()

loader.py :

from folder1.class1 import Class1
from folder2.class2 import Class2

a=Class1()
b=Class2()

class1.py :

import folder.loader as LD

class Class1():
    def __init__(self):
        self.pty1=0
    def change_class2(self):
        LD.b.pty2=2

class2.py :

import folder.loader as LD

class Class2():
    def __init__(self):
        self.pty2=0
    def change_class1(self):
        LD.a.pty1=6

The code executed is main.py. This script calls the file loader.py which creates an instance for Class1 and Class2. The instances have to communicate and modify each other, explaining the necessity (if I am not wrong) of the file loader.py.

Executing this code returns the error from class1.py :

    import folder.loader as LD
AttributeError: 'module' object has no attribute 'loader'

I have no idea of what is going on here.

Surprisingly, when I remove the part as LD from the importation command line in the classes files, it works perfecly :

class1.py :

import folder.loader

class Class1():
    def __init__(self):
        self.pty1=0
    def change_class2(self):
        folder.loader.b.pty2=2

class2.py :

import folder.loader

class Class2():
    def __init__(self):
        self.pty2=0
    def change_class1(self):
        folder.loader.a.pty1=6

For this example, it's ok, but in the real program I am trying to make, based on this structure, I can't use the complete module path each time I need to communicate with another class instance.

Why am I getting this error ? What can I do to solve this ?
Thank you in advance for your help.

EDIT : replacing import folder.loader as LD by from .. import loader as LD now returns another error, that I don't understand :

    from .. import loader as LD
ImportError: cannot import name loader


问:
Replace text not contained in a tag using either Regex or XmlParser
I know that using Regular expressions to parse or manipulate HTML/XML is a bad idea and I usually would never do it. But considering it because of lack of alternatives.

I need to replace text inside a string that is not already part of a  tag (ideally a span tag with specific id) using C#.

For example, Lets say I want to replace all instaces of ABC in the following text that are not inside a span with Alternate text (another span in my case)

ABC at start of line or ABC here must be replaced but, ABC inside span must not be replaced with anything. Another ABC here  this ABC must also be replaced

I tried using regex with both look ahead and look behind assertion. Various combinations along the lines of

```<code>string regexPattern = "(?<!id=\"__publishingReusableFragment\").*?" + stringToMatch + ".*?(?!span)";
</code>```

but gave up on that.

I tried loading it into an XElement and trying to create a writer from there and getting text not inside of a  node. But couldn't figure that out either.

```<code>XElement xel = XElement.Parse("<payload>" + inputString + @"</payload>");
XmlWriter requiredWriter = xel.CreateWriter();
</code>```

I am hoping somehow to use the writer to get the strings that are not part of a node and replacing them.

Basically I am open to any suggestions/solutions to solve this problem.

Thanks in advance for the help.

答:
I know its slightly ugly, but this will work</p>

```<code>var s =
    @"ABC at start of line or ABC here must be replaced but, <span id=""__publishingReusableFragment"" >ABC inside span must not be replaced with anything. Another ABC here </span> this ABC must also be replaced";
var newS = string.Join("</span>",s.Split(new[] {"</span>"}, StringSplitOptions.None)
    .Select(t =>
        {
            var bits = t.Split(new[] {"<span"}, StringSplitOptions.None);
            bits[0] = bits[0].Replace("ABC","DEF");
            return string.Join("<span", bits);
        }));
</code>```

Body:
I know that using Regular expressions to parse or manipulate HTML/XML is a bad idea and I usually would never do it. But considering it because of lack of alternatives.

I need to replace text inside a string that is not already part of a  tag (ideally a span tag with specific id) using C#.

For example, Lets say I want to replace all instaces of ABC in the following text that are not inside a span with Alternate text (another span in my case)

ABC at start of line or ABC here must be replaced but, ABC inside span must not be replaced with anything. Another ABC here  this ABC must also be replaced

I tried using regex with both look ahead and look behind assertion. Various combinations along the lines of

string regexPattern = "(?<!id=\"__publishingReusableFragment\").*?" + stringToMatch + ".*?(?!span)";

but gave up on that.

I tried loading it into an XElement and trying to create a writer from there and getting text not inside of a  node. But couldn't figure that out either.

XElement xel = XElement.Parse("<payload>" + inputString + @"</payload>");
XmlWriter requiredWriter = xel.CreateWriter();

I am hoping somehow to use the writer to get the strings that are not part of a node and replacing them.

Basically I am open to any suggestions/solutions to solve this problem.

Thanks in advance for the help.

Body:
I know its slightly ugly, but this will work

var s =
    @"ABC at start of line or ABC here must be replaced but, <span id=""__publishingReusableFragment"" >ABC inside span must not be replaced with anything. Another ABC here </span> this ABC must also be replaced";
var newS = string.Join("</span>",s.Split(new[] {"</span>"}, StringSplitOptions.None)
    .Select(t =>
        {
            var bits = t.Split(new[] {"<span"}, StringSplitOptions.None);
            bits[0] = bits[0].Replace("ABC","DEF");
            return string.Join("<span", bits);
        }));


问:
How to achieve high availability of instance in openstack
I wanted to launch an instance with high availability with out having risk factor i.e, an instance will be launched in multiple regions(zones) that to sync the state like database(master-slave). When some applications got installed, same should reflect in another region/zone also(mostly image format). Can we do that?.

I have checked some links based on this. I got a confusion after reading all the docs.

Host-aggregate/Cell in openstack

Nova evacuate command

Buildbot tool

Exactly what is the difference among. VM replication & syncing is possiblein Openstack?

答:
To the best of my knowledge, Open Stack does not support VM replication for now.

There is a component called Remus under the Xen project, which could potentially used by manual configuration as Open Stack supports Xen (https://www.xenproject.org/directory/directory/projects/70-remus.html). But it seems to be slow and unstable.

The newest approach is called reversed virtual machine replication (http://dl.acm.org/citation.cfm?id=2996894&CFID=918229768&CFTOKEN=85577813), this one seems to be very interesting and some critical problems in VM replication is well defined and elegantly solved. However, I did not find the open source project for it.


问:
Default template arguments when using template template parameters
The following code compiles using gcc 5.2, gcc 4.9, and clang 3.7 at C++11 standard:

```<code>template <typename T, typename U, template<typename...> class M>
U * find_item(M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

template <typename T, typename U, template<typename...> class M>
const U * find_item(const M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

#include <map>
#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::map<std::string, int> foo;

  foo["asdf"] = 5;
  if (find_item(foo, std::string{"bar"})) { std::cerr << "hmm\n"; }
}
</code>```

However, when I compile it with the latest version of emscripten, I get a compiler error stemming from too few arguments for class template 'map':

```<code>main.cpp:24:7: error: no matching function for call to 'find_item'
  if (find_item(foo, std::string{"bar"})) { std::cerr << "hmm\n"; }
      ^~~~~~~~~
main.cpp:2:5: note: candidate template ignored: substitution failure [with T =
      std::__1::basic_string<char>, U = int, M = map]: too few template
      arguments for class template 'map'
U * find_item(M<T, U> & m, const T & t) {
    ^         ~
main.cpp:9:11: note: candidate template ignored: substitution failure [with T =
      std::__1::basic_string<char>, U = int, M = map]: too few template
      arguments for class template 'map'
const U * find_item(const M<T, U> & m, const T & t) {
          ^               ~
1 error generated.
ERROR:root:compiler frontend failed to generate LLVM bitcode, halting
</code>```

This is a bit odd because my emscripten claims to be based on clang-3.7. Regardless, it seems to have difficulty deducing the default parameters while instantiating the find_item template.

If the code is changed in the following way, then all compilers seem to be happy with it:

```<code>template <typename T, typename U, template<typename...> class M, typename... dummy>
U * find_item(M<T, U, dummy...> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

template <typename T, typename U, template<typename...> class M, typename... dummy>
const U * find_item(const M<T, U, dummy...> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

#include <map>
#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::map<std::string, int> foo;

  foo["asdf"] = 5;
  if (find_item(foo, std::string{"bar"})) { std::cerr << "hmm\n"; }
}
</code>```

The question is, should the "dummy" part actually be necessary according to the C++11 standard, or is emscripten defective in not figuring out the default template parameters here?

My reading of section [temp.deduct.type] 14.8.2.6.8 is that it should be able to bind std::map to a template template parameter of the form M<T, U> because of the wording "at least one" in this sentence:

Similarly, <T> represents template argument
  lists where at least one argument contains a T

But, I'm not sure about that.

答:
I hit this problem and found that I didn't need the dummy template parameter, specifying the template template as variadic was enough (this is on clang 3.6):</p>

```<code>template <typename T, typename U, template<typename...> class M>
U * find_item(M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

template <typename T, typename U, template<typename...> class M>
const U * find_item(const M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}
</code>```

Body:
The following code compiles using gcc 5.2, gcc 4.9, and clang 3.7 at C++11 standard:

template <typename T, typename U, template<typename...> class M>
U * find_item(M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

template <typename T, typename U, template<typename...> class M>
const U * find_item(const M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

#include <map>
#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::map<std::string, int> foo;

  foo["asdf"] = 5;
  if (find_item(foo, std::string{"bar"})) { std::cerr << "hmm\n"; }
}

However, when I compile it with the latest version of emscripten, I get a compiler error stemming from too few arguments for class template 'map':

main.cpp:24:7: error: no matching function for call to 'find_item'
  if (find_item(foo, std::string{"bar"})) { std::cerr << "hmm\n"; }
      ^~~~~~~~~
main.cpp:2:5: note: candidate template ignored: substitution failure [with T =
      std::__1::basic_string<char>, U = int, M = map]: too few template
      arguments for class template 'map'
U * find_item(M<T, U> & m, const T & t) {
    ^         ~
main.cpp:9:11: note: candidate template ignored: substitution failure [with T =
      std::__1::basic_string<char>, U = int, M = map]: too few template
      arguments for class template 'map'
const U * find_item(const M<T, U> & m, const T & t) {
          ^               ~
1 error generated.
ERROR:root:compiler frontend failed to generate LLVM bitcode, halting

This is a bit odd because my emscripten claims to be based on clang-3.7. Regardless, it seems to have difficulty deducing the default parameters while instantiating the find_item template.

If the code is changed in the following way, then all compilers seem to be happy with it:

template <typename T, typename U, template<typename...> class M, typename... dummy>
U * find_item(M<T, U, dummy...> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

template <typename T, typename U, template<typename...> class M, typename... dummy>
const U * find_item(const M<T, U, dummy...> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

#include <map>
#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::map<std::string, int> foo;

  foo["asdf"] = 5;
  if (find_item(foo, std::string{"bar"})) { std::cerr << "hmm\n"; }
}

The question is, should the "dummy" part actually be necessary according to the C++11 standard, or is emscripten defective in not figuring out the default template parameters here?

My reading of section [temp.deduct.type] 14.8.2.6.8 is that it should be able to bind std::map to a template template parameter of the form M<T, U> because of the wording "at least one" in this sentence:

Similarly, <T> represents template argument
  lists where at least one argument contains a T

But, I'm not sure about that.

Body:
I hit this problem and found that I didn't need the dummy template parameter, specifying the template template as variadic was enough (this is on clang 3.6):

template <typename T, typename U, template<typename...> class M>
U * find_item(M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}

template <typename T, typename U, template<typename...> class M>
const U * find_item(const M<T, U> & m, const T & t) {
  auto it = m.find(t);
  if (it != m.end()) { return &it->second; }
  return nullptr;
}


问:
How to match a specified character after the nth occurrence of a delimiter
I just tested a regex on regex101 and getting a somewhat unexpected results. The expression I tried is

^[^-]*(?:-[^-]*){1}\Kt

on this string

this is a test - try to split -this- string - into its substrings

the matching result on regex101 is the "t" at the end of the word "split"

this is a test - try to split -this- string - into its substrings

why didn't it return the first "t" in the word "try"?

this is a test - try to split -this- string - into its substrings

答:
There are a couple of things here to note:

The [^-] matches t, and with the * greedy quantifier it matches up to the last t it finds on its way

The t can be added to the negated character class to match up to the first t, or makelazy with?`

{1} limiting quantifier is redundant since each pattern atom matches once by default

There is no point using a non-capturing group for only one branch in it or without a quantifier

Use

```<code>^[^-]*-[^-]*?\Kt
</code>```

or

```<code>^[^-]*-[^-t]*\Kt
</code>```

Body:
There are a couple of things here to note:

The [^-] matches t, and with the * greedy quantifier it matches up to the last t it finds on its way

The t can be added to the negated character class to match up to the first t, or makelazy with?`

{1} limiting quantifier is redundant since each pattern atom matches once by default

There is no point using a non-capturing group for only one branch in it or without a quantifier

Use

^[^-]*-[^-]*?\Kt

or

^[^-]*-[^-t]*\Kt


问:
Does BigDecimal#min method qualify as a BinaryOperator?
The Stream.reduce method takes a BinaryOperator as an argument. The function signature of a BinaryOperator is (T,T) -> T. The BigDecimal::min method has only 1 parameter in its method signature (ie. (T) -> T ).

Why doesn't the compiler complain when I pass BigDecimal::min to the Stream.reduce method?

Sample code:

```<code>List<BigDecimal> bigDecimalList = new ArrayList<>();
        bigDecimalList.add(BigDecimal.valueOf(1));
        bigDecimalList.add(BigDecimal.valueOf(2));
        bigDecimalList.add(BigDecimal.valueOf(3));
BigDecimal minResult = bigDecimalList.stream().reduce(BigDecimal::min).orElse(BigDecimal.ZERO);
</code>```

Thanks.

答: Because BigDecimal::min is an instance method. Javac is smart enough to turn it into a (T, T) -> T if you use BigDecimal::min. The first paramter passed to the resulting BinaryOperator will be the instance and the second will be the parameter of min (though in BinaryOperator's case it is required that the order can be reversed). It will be (T) -> T if you use something like new BigInteger(1)::min.

Body:
The Stream.reduce method takes a BinaryOperator as an argument. The function signature of a BinaryOperator is (T,T) -> T. The BigDecimal::min method has only 1 parameter in its method signature (ie. (T) -> T ).

Why doesn't the compiler complain when I pass BigDecimal::min to the Stream.reduce method?

Sample code:

List<BigDecimal> bigDecimalList = new ArrayList<>();
        bigDecimalList.add(BigDecimal.valueOf(1));
        bigDecimalList.add(BigDecimal.valueOf(2));
        bigDecimalList.add(BigDecimal.valueOf(3));
BigDecimal minResult = bigDecimalList.stream().reduce(BigDecimal::min).orElse(BigDecimal.ZERO);

Thanks.


问:
use regex to match multiple ip address separated by comma or only one ip address?
it can check like:

"192.168.1.2,118.123.10.25,123.145.67.88"

and it can also check "192.168.4.56" ??

答:
Yes when i asked this question I have found the similar questions on the net, but the best answers does not worked for me. I use laravel5's validation in FormRequest file.

A similar question's answer is :

```<code>/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)(,|,?$))$/
</code>```

(this one ↑　doesnot worked here)

this one worked for me :

```<code>/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(,|,?$)$/
</code>```

Body:
Yes when i asked this question I have found the similar questions on the net, but the best answers does not worked for me. I use laravel5's validation in FormRequest file.

A similar question's answer is :

/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)(,|,?$))$/

(this one ↑　doesnot worked here)

this one worked for me :

/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(,|,?$)$/


问:
CPLEX: How to get feasible solutions after abortion of optimization?
I have a very long lasting optimization process (>100h) and I cannot wait until the end of that process. Nevertheless, I want to get the so far generated solutions (i.e. exact decision variables) of CPLEX. I am using the CPLEX Optimization Studio 12.6. Is this possible and if so, how?

Greetings!

Edit: I'm using OPL inside CPLEX Opt. Studio.

答:
You can use a time limit

```<code>execute timeTermination {
    cplex.tilim = 3600; // maximum Runtime = 1h
  }
</code>```

OR you can use gap limit:

```<code>execute gapTermination {
    cplex.epgap = 0.05; // result at gap of 5%
  }
</code>```

for the optimization process to stop and output the results.

I added one of those limits on the top of my optimization program (OPL) in CPLEX.

Body:
You can use a time limit

execute timeTermination {
    cplex.tilim = 3600; // maximum Runtime = 1h
  }

OR you can use gap limit:

execute gapTermination {
    cplex.epgap = 0.05; // result at gap of 5%
  }

for the optimization process to stop and output the results.

I added one of those limits on the top of my optimization program (OPL) in CPLEX.


问:
Screen Layout doesn't scroll
I have one outer ScrollView in which there is one RecyclerView and three tabs. Every tab has a fragment and that fragment loads in corresponding tab using ViewPager but outer ScrollView does not scroll my layout. I used nested ScrollView but it also does not scroll. Maybe I did something wrong. Does any one have a suggestion? Please share with me.
Here is my xml code structure</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/parent_scroll"
    android:layout_weight="1"
    android:background="@color/business_price_bg"
    android:focusableInTouchMode="false">

    <RelativeLayout
        android:id="@+id/business_detail_main_rl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/activity_main_search_top_main_ll"
            android:layout_width="match_parent"
            android:layout_height="@dimen/activity_main_search_top_main_ll_height"
            android:background="@color/location_setting_bottom_button_color"
            android:gravity="center"
            android:orientation="vertical">

        </LinearLayout>

        <RelativeLayout
            android:id="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/activity_main_search_top_main_ll">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/business_detail_activity_slider_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="vertical" />
        </RelativeLayout>

        <TextView
            android:id="@+id/business_detail_activity_business_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_margin="10dp"
            android:text=""
            android:textColor="@android:color/black"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/business_detail_activity_business_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_title"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:text=""
            android:textSize="13sp" />

        <android.support.design.widget.TabLayout
            android:id="@+id/business_detail_activity_tabslayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_description"
            android:background="@android:color/transparent"
            app:tabIndicatorColor="@color/pencilin_orange_color"
            app:tabIndicatorHeight="5dp"
            app:tabTextAppearance="@style/MyTabLayoutTextAppearance" />

        <android.support.v4.view.ViewPager
            android:id="@+id/business_detail_activity_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/business_detail_activity_tabslayout"
            android:background="@android:color/white" />

    </RelativeLayout>
</ScrollView>
</code>```

答: You are going against the Android's UI Standards that's why you can never achieve your goals. Try to stick with Android UI Standards and make less complex UI.</p>

Title: Screen Layout doesn't scroll

Body:
I have one outer ScrollView in which there is one RecyclerView and three tabs. Every tab has a fragment and that fragment loads in corresponding tab using ViewPager but outer ScrollView does not scroll my layout. I used nested ScrollView but it also does not scroll. Maybe I did something wrong. Does any one have a suggestion? Please share with me.
Here is my xml code structure

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/parent_scroll"
    android:layout_weight="1"
    android:background="@color/business_price_bg"
    android:focusableInTouchMode="false">

    <RelativeLayout
        android:id="@+id/business_detail_main_rl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/activity_main_search_top_main_ll"
            android:layout_width="match_parent"
            android:layout_height="@dimen/activity_main_search_top_main_ll_height"
            android:background="@color/location_setting_bottom_button_color"
            android:gravity="center"
            android:orientation="vertical">

        </LinearLayout>

        <RelativeLayout
            android:id="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/activity_main_search_top_main_ll">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/business_detail_activity_slider_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="vertical" />
        </RelativeLayout>

        <TextView
            android:id="@+id/business_detail_activity_business_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_margin="10dp"
            android:text=""
            android:textColor="@android:color/black"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/business_detail_activity_business_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_title"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:text=""
            android:textSize="13sp" />

        <android.support.design.widget.TabLayout
            android:id="@+id/business_detail_activity_tabslayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_description"
            android:background="@android:color/transparent"
            app:tabIndicatorColor="@color/pencilin_orange_color"
            app:tabIndicatorHeight="5dp"
            app:tabTextAppearance="@style/MyTabLayoutTextAppearance" />

        <android.support.v4.view.ViewPager
            android:id="@+id/business_detail_activity_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/business_detail_activity_tabslayout"
            android:background="@android:color/white" />

    </RelativeLayout>
</ScrollView>


问:
How do you use the ? : (conditional) operator in JavaScript?
What is the ?: (question mark and colon operator aka. conditional or "ternary") operator and how can I use it?

答:
```<code> (sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";

 sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"
</code>```

ContentLicense: CC BY-SA 4.0


问:
Will providing APIs help deter screen scraping?
I have been thinking quite a bit here lately about screen scraping and what a task it can be. So I pose the following question.

Would you as a site developer expose simple APIs to prevent users from screen scraping, such as JSON results?

These results could then implement caching, and they are much smaller for traffic than the huge amounts of markup that could potentially be downloaded.

I am not looking at prevention, but deterring scraping.

Scraping Bandwidth Sample

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

users: 200,000

% of users using utility: 5

filesize: 1kb

freq: 1 minute

Formula:

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

10,000 * 1440 * 1

14400000kb or 13.73291015625gb

Assuming your JSON result is 200 bytes that's now (10,000 * 1440 * 0.2) or 2.74658203125gb a day.

That's a change of about 11gb of traffic a day.

My Stack Overflow profile is 96k for reference.

The reason for this question prompted asking for a JSON result from users profiles:

http://stackoverflow.uservoice.com/pages/general/suggestions/101342-add-json-for-user-information

I wanted to find out if other developers would expose this type of API, and if it is worth your time to provide these APIs to reduce bandwidth.

答:
Screen scraping is not realistically preventable. Providing an API, while nice to those who consume your data, can't prevent it. Since the data ultimately has to be human readable, it therefore is machine readable. You would be better off spending your energy working on your site and not working for those who would consume your data (legally or not).

wget, perl, regular expressions is the common mechanism for scraping data.

OwnerDisplayName: Tom Anderson

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: Michael


问:
Understand SQL Read committed & Read uncommitted
I am using SQL Server Express 2008 w/ AdventureWorksLT2008 DB to understand the different between Read committed & Read uncommitted.

According to Wikipedia:
http://en.wikipedia.org/wiki/Isolation_%28database_systems%29

READ COMMITTED

Data records retrieved by a query are
  not prevented from modification by
  some other transactions.

Assume there is a table named SalesLT.Address and a column AddressLine2 which all rows has blank value

Then i run this query :

```<code>SET TRANSACTION ISOLATION LEVEL READ COMMITTED

BEGIN TRANSACTION
    update SalesLT.Address set AddressLine2 = 'new value'

        BEGIN TRANSACTION
            select AddressLine2 from SalesLT.Address

--Break Here
/*
        COMMIT TRANSACTION
COMMIT TRANSACTION
*/
</code>```

So, you can see the first transaction haven't commited yet, and the second one start to query the data.

It resulting:

So why the second transaction can be retrieved the phantom data even the 1st transaction still not committed?

答:
When data is read inside a transaction, any changes that have been made by that transaction are visible - within that tranasction only (although READ UNCOMMITTED changes this).  So above, even though you've started a second, nested, transaction, you're still in scope of the first transaction and can thus read changed data and get 'the changed values'.

Another transaction, on a separate SPID for example, would block if it was using READ COMMITTED and attempted to read this data.

Body:
I am using SQL Server Express 2008 w/ AdventureWorksLT2008 DB to understand the different between Read committed & Read uncommitted.

According to Wikipedia:
http://en.wikipedia.org/wiki/Isolation_%28database_systems%29

READ COMMITTED

Data records retrieved by a query are
  not prevented from modification by
  some other transactions.

Assume there is a table named SalesLT.Address and a column AddressLine2 which all rows has blank value

Then i run this query :

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

BEGIN TRANSACTION
    update SalesLT.Address set AddressLine2 = 'new value'

        BEGIN TRANSACTION
            select AddressLine2 from SalesLT.Address

--Break Here
/*
        COMMIT TRANSACTION
COMMIT TRANSACTION
*/

So, you can see the first transaction haven't commited yet, and the second one start to query the data.

It resulting:

So why the second transaction can be retrieved the phantom data even the 1st transaction still not committed?


问:
How can I create a webpage where the user can enter data in form, which is then added in a new table row
Using html and php, i want to create a webpage where a user can add an entry and this will then appear at the end of a html table which will increase as more entries are added, and each row keeps its css style rules.
One section of table includes a row for date, a row for title and a row for entry, each have their own style rule. The user enters each of these in a form and a new 'section' of table is added to the existing table with 3 new rows.

How can i do this

答:
Simply create one form and below that display table with form data.
After filling form data will be added into database using ajax jquery.

Create one php page with only table in it.

If successfully data inserted then load that new page in table div which contain only table on success of insert data ajax jquery function.


问:
search bar and segmented control
I add UISegmentedControl on storyboard and add SearchBar in code:

```<code>searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
searchController.dimsBackgroundDuringPresentation = false
discountTableView.tableHeaderView = searchController.searchBar
</code>```

Invalid position of Search Bar after its activation.
How fix it?
Before clicking,
After clicking

答:
I overcame this by implementing delegate method of UISearchController

```<code>- (void)willPresentSearchController:(UISearchController *)searchController {

    if (searchController.searchBar.scopeButtonTitles.count == 0) {
        //somewhere I got this
        // there is an Apple bug when first time configuring search bar scope buttons
        // will be displayed no matter what with minimal searchbar
        // to fix this adding scope buttons right before user activates search bar
        searchController.searchBar.showsScopeBar = NO;
        searchController.searchBar.scopeButtonTitles = @[@"title 1", @"title 2"];
    }

}
</code>```

Hope it will help you too.

Title: search bar and segmented control

Body:
I add UISegmentedControl on storyboard and add SearchBar in code:

searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
searchController.dimsBackgroundDuringPresentation = false
discountTableView.tableHeaderView = searchController.searchBar

Invalid position of Search Bar after its activation.
How fix it?
Before clicking,
After clicking

Body:
I overcame this by implementing delegate method of UISearchController

- (void)willPresentSearchController:(UISearchController *)searchController {

    if (searchController.searchBar.scopeButtonTitles.count == 0) {
        //somewhere I got this
        // there is an Apple bug when first time configuring search bar scope buttons
        // will be displayed no matter what with minimal searchbar
        // to fix this adding scope buttons right before user activates search bar
        searchController.searchBar.showsScopeBar = NO;
        searchController.searchBar.scopeButtonTitles = @[@"title 1", @"title 2"];
    }

}

Hope it will help you too.