问:
Reverse otp authentication
Iam designing a app where I need phone number authentication so we are using otp authentication
Is there any other way to do user authentication
Like I was thinking instead of sending sms to the user how about generated a otp and send it to the server from the client device using the device sms to authenticate the device</p>

答:
You can verify user only by using 3rd party OTP provider or Email verification.
And in your case if you generate OTP on device than with which data you compare on Server ?Server dosen't know the Original OTP generated by device is correct or not and this idea britches the security of your app.

So better try to use 3rd party library for OTP verification.It's Better and Secure way.

Title: Reverse otp authentication


来源: stackexchange

问:
How to avoid casting?
I add new global hight level interface:

```<code>    public interface MvpView {
    }
</code>```

My hight level interface:

```<code>public interface OfferDetailsView extends MvpView {

   public void showProgress();
}
</code>```

Another interface:

```<code>public interface OfferDetailsPdfMvp {

    interface View extends OfferDetailsView  {

        public void openLocalPdfFile(File file, int pageNumber);

    }

    interface Presenter extends OfferDetailsPresenter {

        public void onPageScrolled(int page, int pageCount);

    }
}
</code>```

Another interface:

```<code>public interface OfferDetailsPresenter extends MvpPresenter {

    public void downloadToAppDir(boolean isDownloadToAppCacheDir);

    public void onClickScreen(boolean isVisibleTopContainer);
}
</code>```

Another interface:

```<code>public interface MvpPresenter<V extends MvpView> {
    public void attachView(V mvpView);
}
</code>```

Base abstract class:

```<code>public abstract class BaseOfferDetailsPresenter<T extends MvpView> implements MvpPresenter<T> {
    private T view;

     @Override
    public void attachView(T mvpView) {
        this.view = mvpView;
    }

   public T getView() {
         return view;
    }
}
</code>```

And conrete class that extend from Base class:

```<code>public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {

    public void viewIsReady() {
      getView().showProgress(); //no cast
      getView().openLocalPdfFile(file, currentPageNumber); // no cast
    }
</code>```

But I get compile error:

```<code>myproject\app\src\main\java\com\myproject\android\customer\presenter\OfferDetailsPdfPresenterImpl.java:35: error: MvpPresenter cannot be inherited with different arguments: <> and <com.myproject.android.customer.mvp.OfferDetailsPdfMvp.View>
    public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {
</code>```

答:
You can't - with that signature.

Keep in mind, getView() says:

```<code>OfferDetailsView getView()
</code>```

Thus: the signature of this method uses one of your base interfaces.

There are only two choices:

change the return type to a more specific sub interface / class

do an instanceof check + cast

Just assuming that getView() returns some specific class and having an unchecked cast is not good practice. On other hand: when it is clear that getView() will return an instance of OfferDetailsPdfMvp then it shouldn't be a big deal to change the method signature accordingly.

ContentLicense: CC BY-SA 3.0

Title: How to avoid casting?

Body:
I add new global hight level interface:

    public interface MvpView {
    }

My hight level interface:

public interface OfferDetailsView extends MvpView {

   public void showProgress();
}

Another interface:

public interface OfferDetailsPdfMvp {

    interface View extends OfferDetailsView  {

        public void openLocalPdfFile(File file, int pageNumber);

    }

    interface Presenter extends OfferDetailsPresenter {

        public void onPageScrolled(int page, int pageCount);

    }
}

Another interface:

public interface OfferDetailsPresenter extends MvpPresenter {

    public void downloadToAppDir(boolean isDownloadToAppCacheDir);

    public void onClickScreen(boolean isVisibleTopContainer);
}

Another interface:

public interface MvpPresenter<V extends MvpView> {
    public void attachView(V mvpView);
}

Base abstract class:

public abstract class BaseOfferDetailsPresenter<T extends MvpView> implements MvpPresenter<T> {
    private T view;

     @Override
    public void attachView(T mvpView) {
        this.view = mvpView;
    }

   public T getView() {
         return view;
    }
}

And conrete class that extend from Base class:

public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {

    public void viewIsReady() {
      getView().showProgress(); //no cast
      getView().openLocalPdfFile(file, currentPageNumber); // no cast
    }

But I get compile error:

myproject\app\src\main\java\com\myproject\android\customer\presenter\OfferDetailsPdfPresenterImpl.java:35: error: MvpPresenter cannot be inherited with different arguments: <> and <com.myproject.android.customer.mvp.OfferDetailsPdfMvp.View>
    public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {

Body:
You can't - with that signature.

Keep in mind, getView() says:

OfferDetailsView getView()

Thus: the signature of this method uses one of your base interfaces.

There are only two choices:

change the return type to a more specific sub interface / class

do an instanceof check + cast

Just assuming that getView() returns some specific class and having an unchecked cast is not good practice. On other hand: when it is clear that getView() will return an instance of OfferDetailsPdfMvp then it shouldn't be a big deal to change the method signature accordingly.


问:
Google AMP - Save current page URL to local storage
Can anyone point me in the right direction? I'm building a landing page that is supposed to store the current page URL with query strings to local storage. I've looked all over, but can't find a solution that will keep my AMP page valid.</p>

答: This is not possible with AMP as you can't run custom Javascript. This means you won't be able to read from local storage either. </p>


问:
Check if element is clicked before removal
I have the following jquery code:

```<code>$(document).on('focusout', '#element_a', function(e){
     $('#element_b').remove();
});
$(document).on('click', '#element_b', function(e){
     // do other stuff here
});
</code>```

So basically, I want to remove #element_b on focusout BUT if it's clicked, execute the click function before removal. The problem is that focusout executes before the click so by the time the click is registered, the element is already removed, so the click doesn't register and does nothing.

答:
Not sure if you want to remove element a or b. Just Trigger click event and then remove the element.</p>

```<code>$(document).on('focusout', '#element_a', function(e){
     $('#element_b').trigger('click');
});
$(document).on('click', '#element_b', function(e){
     // do other stuff before remove element
     $('#element_b').remove();

});
</code>```

Body:
I have the following jquery code:

$(document).on('focusout', '#element_a', function(e){
     $('#element_b').remove();
});
$(document).on('click', '#element_b', function(e){
     // do other stuff here
});

So basically, I want to remove #element_b on focusout BUT if it's clicked, execute the click function before removal. The problem is that focusout executes before the click so by the time the click is registered, the element is already removed, so the click doesn't register and does nothing.

Body:
Not sure if you want to remove element a or b. Just Trigger click event and then remove the element.

$(document).on('focusout', '#element_a', function(e){
     $('#element_b').trigger('click');
});
$(document).on('click', '#element_b', function(e){
     // do other stuff before remove element
     $('#element_b').remove();

});


问:
using python commenting xml tags
for the below xml file , how can i comment(in xml) the heading tag including its children using python ? i am new to python , tried using lxml but only able to add a new comment, not able to comment existing tags. please do help , thanks in advance

```<code><note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
<body>Don't forget me this weekend!</body>
</note>
</code>```

i would want the output to be like

```<code><note>
<to>Tove</to>
<from>Jani</from>
<!--  <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>
</code>```

答:
try something like </p>

```<code>with open('test.xml', 'r+') as f:
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
    if '<heading>' or '</heading>' in line :
            line = line.replace('<heading>', '<-- <heading>').replace('</heading>', '</heading> -->')
    f.write(line)
</code>```

Title: using python commenting xml tags

Body:
for the below xml file , how can i comment(in xml) the heading tag including its children using python ? i am new to python , tried using lxml but only able to add a new comment, not able to comment existing tags. please do help , thanks in advance

<note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
Don't forget me this weekend!
</note>

i would want the output to be like

<note>
<to>Tove</to>
<from>Jani</from>

Don't forget me this weekend!
</note>

Body:
try something like

with open('test.xml', 'r+') as f:
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
    if '<heading>' or '</heading>' in line :
            line = line.replace('<heading>', '<-- <heading>').replace('</heading>', '</heading> -->')
    f.write(line)


问:
Persistence store options like database for rabbbit mq
We are using rabbit MQ as messaging broker in our project. we gone through some of the blogs and documents about persistence store in Rabbit MQ.

There are default options for the message store like in  memory , queue index and flat files on the disk.

As we are more concern on the message durability , we are searching for best approach for data store with rabbit mq.

Again just to confirm, can we use database like ** for another broker active mq we can use database as persistence store**.

Any help/thoughts would be appreciated.

答:
RabbitMQ uses a custom DB and it is not possible to change it as ActiveMQ.

Starting from the version 3.7.0 is possible to change the index DB using eleveldb, see:  https://github.com/rabbitmq/rabbitmq-msg-store-index-eleveldb


问:
Find and replace characters in brackets
I have a string kind of:

```<code>String text = "(plum) some other words, [apple], another words {pear}.";
</code>```

I have to find and replace the words in brackets, don't replacing the brackets themselves.

If I write:

```<code>text = text.replaceAll("(\\(|\\[|\\{).*?(\\)|\\]|\\})", "fruit");
</code>```

I get:

```<code>fruit some other words, fruit, another words fruit.
</code>```

So the brackets went away with the fruits, but I need to keep them.

Desired output:

```<code>(fruit) some other words, [fruit], another words {fruit}.
</code>```

答:
Here is your regex:

```<code>(?<=[({\[\(])[A-Za-z]*(?=[}\]\)])
</code>```

Test it here:

https://regex101.com/

In order to use it in Java, remember to add second backslashes:

```<code>(?<=[({\\[\\(])[A-Za-z]*(?=[}\\]\\)])
</code>```

It matches 0 or more letters (uppercase or lowercase) preceded by either of these [,{,( and followed by either of these ],},).

If you want to have at least 1 letter between brackets just replace '*' with '+' like this:

```<code>(?<=[({\[\(])[A-Za-z]+(?=[}\]\)])
</code>```

Title: Find and replace characters in brackets

Body:
I have a string kind of:

String text = "(plum) some other words, [apple], another words {pear}.";

I have to find and replace the words in brackets, don't replacing the brackets themselves.

If I write:

text = text.replaceAll("(\\(|\\[|\\{).*?(\\)|\\]|\\})", "fruit");

I get:

fruit some other words, fruit, another words fruit.

So the brackets went away with the fruits, but I need to keep them.

Desired output:

(fruit) some other words, [fruit], another words {fruit}.

Body:
Here is your regex:

(?<=[({\[\(])[A-Za-z]*(?=[}\]\)])

Test it here:

https://regex101.com/

In order to use it in Java, remember to add second backslashes:

(?<=[({\\[\\(])[A-Za-z]*(?=[}\\]\\)])

It matches 0 or more letters (uppercase or lowercase) preceded by either of these [,{,( and followed by either of these ],},).

If you want to have at least 1 letter between brackets just replace '*' with '+' like this:

(?<=[({\[\(])[A-Za-z]+(?=[}\]\)])


问:
Complete dataframe for few samples, from a vector
```<code>DF=structure(list(Ech = c(4L, 4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L,
13L), pos = c("BD", "BG", "HD", "n_BG", "n_HG", "BD", "HD", "HG",
"n_BG", "n_HG"), sm = c(5, 4, 2, 6, 1, 4, 1, 1, 2, 1)), .Names = c("Ech",
"pos", "sm"), row.names = c(NA, -10L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), vars = "Ech", drop = TRUE, indices = list(
    0:4, 5:9), group_sizes = c(5L, 5L), biggest_group_size = 5L, labels = structure(list(
    Ech = c(4L, 13L)), row.names = c(NA, -2L), class = "data.frame", vars = "Ech", drop = TRUE, .Names = "Ech"))
</code>```

The full list of pos value is :

```<code>column=c("BD","BG","HD","HG","n_BD","n_BG","n_HD","n_HG")
</code>```

these value shoulg be present for each Ech. I'm aiming to convert this dataframe:

From

```<code>  Ech   pos    sm
   <int> <chr> <dbl>
 1     4    BD     5
 2     4    BG     4
 3     4    HD     2
 4     4  n_BG     6
 5     4  n_HG     1
 6    13    BD     4
 7    13    HD     1
 8    13    HG     1
 9    13  n_BG     2
10    13  n_HG     1
</code>```

to (complete

```<code>  Ech   pos    sm
   <int> <chr> <dbl>
 1     4    BD     5
 2     4    BG     4
 3     4    HD     2
 4     4    HG     0
 5     4  n_BD     0
 6     4  n_BG     6
 7     4  n_HD     0
 8     4  n_HG     1
 9     13   BD     4
 10    13   BG     0
 11    13   HD     1
 12    13   HG     1
 13    13 n_BD     0
 14    13 n_BG     2
 15    13 n_HD     0
 16    13 n_HG     1
</code>```

So I used :

```<code>DF = DF %>%
complete(column=c("BD","BG","HD","HG","n_BD","n_BG","n_HD","n_HG"),nesting(pos,Ech))
</code>```

Error :by can't contain join column column which is missing from RHS

How to do this ?

答:
You can try:

```<code>library(tidyverse)
DF %>%
  mutate(pos=factor(pos, levels = c("BD","BG","HD","HG","n_BD","n_BG","n_HD","n_HG"))) %>%
  complete(pos, fill = list(sm = 0))
# A tibble: 16 x 3
# Groups:   Ech [2]
     Ech    pos    sm
   <int> <fctr> <dbl>
 1     4     BD     5
 2     4     BG     4
 3     4     HD     2
 4     4     HG     0
 5     4   n_BD     0
 6     4   n_BG     6
 7     4   n_HD     0
 8     4   n_HG     1
 9    13     BD     4
10    13     BG     0
11    13     HD     1
12    13     HG     1
13    13   n_BD     0
14    13   n_BG     2
15    13   n_HD     0
16    13   n_HG     1
</code>```

If the data is not grouped by Ech one have to use instead:

```<code>complete(Ech, pos, fill = list(sm = 0))
</code>```

From the help.

Factors: the full set of levels (not just those that appear in the data) are used.

Continuous variables: you may need to fill in values that don't appear in the data like in docendo discimus comment under this post.

Body:
DF=structure(list(Ech = c(4L, 4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L,
13L), pos = c("BD", "BG", "HD", "n_BG", "n_HG", "BD", "HD", "HG",
"n_BG", "n_HG"), sm = c(5, 4, 2, 6, 1, 4, 1, 1, 2, 1)), .Names = c("Ech",
"pos", "sm"), row.names = c(NA, -10L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), vars = "Ech", drop = TRUE, indices = list(
    0:4, 5:9), group_sizes = c(5L, 5L), biggest_group_size = 5L, labels = structure(list(
    Ech = c(4L, 13L)), row.names = c(NA, -2L), class = "data.frame", vars = "Ech", drop = TRUE, .Names = "Ech"))

The full list of pos value is :

column=c("BD","BG","HD","HG","n_BD","n_BG","n_HD","n_HG")

these value shoulg be present for each Ech. I'm aiming to convert this dataframe:

From

  Ech   pos    sm
   <int> <chr> <dbl>
 1     4    BD     5
 2     4    BG     4
 3     4    HD     2
 4     4  n_BG     6
 5     4  n_HG     1
 6    13    BD     4
 7    13    HD     1
 8    13    HG     1
 9    13  n_BG     2
10    13  n_HG     1

to (complete

  Ech   pos    sm
   <int> <chr> <dbl>
 1     4    BD     5
 2     4    BG     4
 3     4    HD     2
 4     4    HG     0
 5     4  n_BD     0
 6     4  n_BG     6
 7     4  n_HD     0
 8     4  n_HG     1
 9     13   BD     4
 10    13   BG     0
 11    13   HD     1
 12    13   HG     1
 13    13 n_BD     0
 14    13 n_BG     2
 15    13 n_HD     0
 16    13 n_HG     1

So I used :

DF = DF %>%
complete(column=c("BD","BG","HD","HG","n_BD","n_BG","n_HD","n_HG"),nesting(pos,Ech))

Error :by can't contain join column column which is missing from RHS

How to do this ?

Body:
You can try:

library(tidyverse)
DF %>%
  mutate(pos=factor(pos, levels = c("BD","BG","HD","HG","n_BD","n_BG","n_HD","n_HG"))) %>%
  complete(pos, fill = list(sm = 0))
# A tibble: 16 x 3
# Groups:   Ech [2]
     Ech    pos    sm
   <int> <fctr> <dbl>
 1     4     BD     5
 2     4     BG     4
 3     4     HD     2
 4     4     HG     0
 5     4   n_BD     0
 6     4   n_BG     6
 7     4   n_HD     0
 8     4   n_HG     1
 9    13     BD     4
10    13     BG     0
11    13     HD     1
12    13     HG     1
13    13   n_BD     0
14    13   n_BG     2
15    13   n_HD     0
16    13   n_HG     1

If the data is not grouped by Ech one have to use instead:

complete(Ech, pos, fill = list(sm = 0))

From the help.

Factors: the full set of levels (not just those that appear in the data) are used.

Continuous variables: you may need to fill in values that don't appear in the data like in docendo discimus comment under this post.


问:
How do I make Standards mode work as well as quirks mode?
The following Html works great for me in FireFox or IE7/8 (with or without the Style Tag)

```<code><!-- Deliberately no DocType to induce Quirks Mode -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        Input.quirks
        {
            margin: 1px 0px 1px 0px;
            border: solid black 1px;
        }
    </style>
</head>
<body>
Should work in Quirks Mode <br />
    <input class="quirks" type="text" style="width: 300px;" /><br />
    <input class="quirks" type="text" style="width: 147px;" /><img src="./Graphics/SpacerPixel.gif" border="0" /><input class="quirks" type="text" maxlength="25" style="width: 150px;" /><br />
    <input class="quirks" type="text" style="width: 94px;" /><img src="./Graphics/SpacerPixel.gif" border="0" /><input class="quirks" type="text" style="width: 100px;" /><img src="./Graphics/SpacerPixel.gif" border="0" /><input class="quirks" type="text" value="DA8 1DE" style="width: 100px;" />
</body>
</html>
</code>```

However I am told that the absence of a DocType at the top of said HTML is causing both both browsers to work in "Quirks" mode.

I am told this is bad.

I have tried several DocTypes but have not found a DocType/HTML combination which yields a correct rendering in both browsers.

Anything other than "Quirks" mode causes the browsers to react differently to the attempt to set the width of a textbox. This seems to lead to a position where I can correct my instructions for either FF or IE and suddenly the other will fail.

Some detail...

1.> The objective here is that the 3 rows should appear to be the same width exactly when rendered in each browser. It is not nessecary that the rendered widths are the same across browsers, merely that they appear correctly justified/alighned inside each browser.

2.> The image referenced is a spacer image 3 pixels wide and 1 high (an alternative to this would also be good)

3.> I do not want to introduce tables if at all possible.

It seems as though the Quirks mode is the only mode which is consistent across the browsers. I am worried however that the final version of IE8 or indeed in some future browser, the quirks mode will not be the default.

What should I do ? How do specify a DocType (and maybe alter my html) which will create a consistent look across browsers?

答: Since your problem was mostly caused by different default values in IE and Firefox, you may be interested in a Reset CSS stylesheet, which includes values for things like padding, effectively clearing the defaults for every browser so that they all render similarly.</p>

OwnerDisplayName: Rory Becker

ContentLicense: CC BY-SA 2.5

Body:
The following Html works great for me in FireFox or IE7/8 (with or without the Style Tag)

Should work in Quirks Mode

    <input class="quirks" type="text" style="width: 300px;" />

    <input class="quirks" type="text" style="width: 147px;" /><input class="quirks" type="text" maxlength="25" style="width: 150px;" />

    <input class="quirks" type="text" style="width: 94px;" /><input class="quirks" type="text" style="width: 100px;" /><input class="quirks" type="text" value="DA8 1DE" style="width: 100px;" />

However I am told that the absence of a DocType at the top of said HTML is causing both both browsers to work in "Quirks" mode.

I am told this is bad.

I have tried several DocTypes but have not found a DocType/HTML combination which yields a correct rendering in both browsers.

Anything other than "Quirks" mode causes the browsers to react differently to the attempt to set the width of a textbox. This seems to lead to a position where I can correct my instructions for either FF or IE and suddenly the other will fail.

Some detail...

1.> The objective here is that the 3 rows should appear to be the same width exactly when rendered in each browser. It is not nessecary that the rendered widths are the same across browsers, merely that they appear correctly justified/alighned inside each browser.

2.> The image referenced is a spacer image 3 pixels wide and 1 high (an alternative to this would also be good)

3.> I do not want to introduce tables if at all possible.

It seems as though the Quirks mode is the only mode which is consistent across the browsers. I am worried however that the final version of IE8 or indeed in some future browser, the quirks mode will not be the default.

What should I do ? How do specify a DocType (and maybe alter my html) which will create a consistent look across browsers?

LastEditorDisplayName: Rory Becker

OwnerDisplayName: A. Rex


问:
How can I add a delay to a JS redirect
how can I add a time delay of 5 seconds to this code?</p>

```<code><script type="text/javascript">
if (document.location.href.indexOf('url-wording') > -1) {
    document.location.href = 'http://www.google.com/';
}
</script>
</code>```

答:
```<code>if(document.location.href.indexOf('url-wording') > -1) {
  setTimeout(function() {
    document.location.href = 'http://www.google.com/';
  }, 5000); // 5000ms = 5s
}
</code>```

Title: How can I add a delay to a JS redirect


答:
Convert to RDD and map:

```<code>vectors = df.select("features").rdd.map(lambda row: row.features)
</code>```

Convert result to distributed matrix:

```<code>from pyspark.mllib.linalg.distributed import RowMatrix

matrix = RowMatrix(vectors)
</code>```

If you want DenseVectors (memory requirements!):

```<code>vectors = df.select("features").rdd.map(lambda row: row.features.toArray())
</code>```

ContentLicense: CC BY-SA 4.0

Title: PySpark - SparseVector Column to Matrix

Body:
I am very new to using PySpark. I have a column of SparseVectors in my PySpark dataframe.

rescaledData.select('features').show(5,False)

+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|features                                                                                |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|(262144,[43953,62425,66522,148962,174441,249180],[3.9219733362813143,3.9219733362813143,1.213923135179104,3.9219733362813143,3.9219733362813143,0.5720692490067093])|
|(262144,[57925,66522,90939,249180],[3.5165082281731497,1.213923135179104,3.9219733362813143,0.5720692490067093])                                                    |
|(262144,[23366,45531,73408,211290],[2.6692103677859462,3.005682604407159,3.5165082281731497,3.228826155721369])                                                     |
|(262144,[30913,81939,99546,137643,162885,249180],[3.228826155721369,3.9219733362813143,3.005682604407159,3.005682604407159,3.228826155721369,1.1441384980134186])   |
|(262144,[108134,152329,249180],[3.9219733362813143,2.6692103677859462,2.8603462450335466])                                                                          |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+

I need to convert the above dataframe into a matrix where every row in the matrix corresponds to a SparseVector in that exact row in the dataframe.

for example,

+-----------------+
|features         |
+-----------------+
|(7,[1,2],[45,63])|
|(7,[3,5],[85,69])|
|(7,[1,2],[89,56])|
+-----------------+

Must be converted to

[[0,45,63,0,0,0,0]
[0,0,0,85,0,69,0]
[0,89,56,0,0,0,0]]

I have read the link below, which shows that there is a function toArray() which does exactly what I want.
https://mingchen0919.github.io/learning-apache-spark/pyspark-vectors.html

However, I am having trouble using it.

vector_udf = udf(lambda vector: vector.toArray())
rescaledData.withColumn('features_', vector_udf(rescaledData.features)).first()

I need it to convert every row into an array and then convert the PySpark dataframe into a matrix.

Body:
Convert to RDD and map:

vectors = df.select("features").rdd.map(lambda row: row.features)

Convert result to distributed matrix:

from pyspark.mllib.linalg.distributed import RowMatrix

matrix = RowMatrix(vectors)

If you want DenseVectors (memory requirements!):

vectors = df.select("features").rdd.map(lambda row: row.features.toArray())


问:
How to move Multi Column List line items to another list box along with multi column value excel vba
Try to move listbox items with the below code.
its working, but its coming only one column value, there are total 6 columns in the list box

```<code> Private Sub ListBoxProSlt_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
 Dim ProList As String
    ProList = ListBoxProSlt.List(ListBoxProSlt.ListIndex)
    ListBoxProRec.AddItem ProList

End Sub
</code>```

Any suggestion to move all columns value to next list box!!

答:
using  loop you can add more item from one list  to another
here

```<code> Private Sub ListBoxProSlt_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
 Dim ProList As String
 count=0
columnIndex = 0

For rowIndex  = 0 To ListBoxProSit.ListCount - 1
  count = count + ListBox1.List(rowIndex , columnIndex )
Next
 i=0
 do until i > count
    ProList = ListBoxProSlt.List(i)
    ListBoxProRec.AddItem ProList
 i=i+1
loop

End Sub
</code>```

i hope it solve's your problem

Body:
Try to move listbox items with the below code.
its working, but its coming only one column value, there are total 6 columns in the list box

 Private Sub ListBoxProSlt_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
 Dim ProList As String
    ProList = ListBoxProSlt.List(ListBoxProSlt.ListIndex)
    ListBoxProRec.AddItem ProList

End Sub

Any suggestion to move all columns value to next list box!!

Body:
using  loop you can add more item from one list  to another
here

 Private Sub ListBoxProSlt_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
 Dim ProList As String
 count=0
columnIndex = 0

For rowIndex  = 0 To ListBoxProSit.ListCount - 1
  count = count + ListBox1.List(rowIndex , columnIndex )
Next
 i=0
 do until i > count
    ProList = ListBoxProSlt.List(i)
    ListBoxProRec.AddItem ProList
 i=i+1
loop

End Sub

i hope it solve's your problem


问:
React native-fbsdk unknown issue?
I am using react native 0.49.5 and react 16.0.0-beta.5 for making an App.

I am using react native-fbsdk(^0.6.3) for facebook login. All necessary steps are taken to link android with the facebook sdk.

But When I ran react-native run-android, It threw an error.

Error log in CLI(TERMINAL):

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

:react-native-fbsdk:processReleaseResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
  Execution failed for task ':react-native-fbsdk:processReleaseResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.015 secs
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have
  set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

Here is my android/build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}
</code>```

And here is my android/app/build.gradle

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    dexOptions {
        jumboMode true
    }
    defaultConfig {
        applicationId "com.reactnativeapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-fetch-blob')
    compile project(':react-native-camera-kit')
    compile(project(':react-native-fbsdk')){
      exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
    }
    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile project(':react-native-maps')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-linear-gradient')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
</code>```

How can I solve this issue? Any help on this?

答:
I have been searching for the solution for hours and finally fixed it with this post

You have to go to node-modules/react-native-fbsdk/android and changes compilesdkVersion to 26, buildToolVersion to 26.0.1, targetsdkVersion to 26 and finally com.android.support:appcompat-v7:26.+

Title: React native-fbsdk unknown issue?

Body:
I am using react native 0.49.5 and react 16.0.0-beta.5 for making an App.

I am using react native-fbsdk(^0.6.3) for facebook login. All necessary steps are taken to link android with the facebook sdk.

But When I ran react-native run-android, It threw an error.

Error log in CLI(TERMINAL):

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

:react-native-fbsdk:processReleaseResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
  Execution failed for task ':react-native-fbsdk:processReleaseResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.015 secs
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have
  set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

Here is my android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

And here is my android/app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    dexOptions {
        jumboMode true
    }
    defaultConfig {
        applicationId "com.reactnativeapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-fetch-blob')
    compile project(':react-native-camera-kit')
    compile(project(':react-native-fbsdk')){
      exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
    }
    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile project(':react-native-maps')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-linear-gradient')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

How can I solve this issue? Any help on this?


问:
RealmResults size is returning Zero
I have  a little problem, and I couldn't find any results. Yes I did some researches too.

I have a variable mResults = RealmResults < Drop > ;

and this has Data as you can see in the picture below

But when I type >>mResults.size<< it returns 0.
What could the problem be? btw. Im working in Android using kotlin.

The pröblem is in the Recyclerview getItemCöunt

ActivityMain::::

```<code>Realm.init(this)
        val configuration = RealmConfiguration.Builder().build()
        Realm.setDefaultConfiguration(configuration)
    mRealm = Realm.getDefaultInstance()
            val results:RealmResults<Drop> = mRealm.where(Drop::class.java).findAll()

            mToolbar = findViewById<Toolbar>(R.id.toolbar)
            mRecycler = findViewById<RecyclerView>(R.id.rv_drops)
            val manager = LinearLayoutManager(this)

            mRecycler.layoutManager = manager
            mRecycler.adapter = AdapterDrops(this, results)
</code>```

```<code>open class Drop : RealmObject {
private var what: String? = null
@PrimaryKey
private var added: Long? = null
private var whenT: Long? = null
private var completed: Boolean? = null

constructor(){}

constructor(what: String, added: Long, whenT: Long, completed: Boolean) : super() {
    this.what = what
    this.added = added
    this.whenT = whenT
    this.completed = completed
}

fun getWhat(): String? {
    return what
}

fun setWhat(what: String) {
    this.what = what
}

fun getAdded(): Long? {
    return added
}

fun setAdded(added: Long) {
    this.added = added
}

fun getWhenT(): Long? {
    return whenT
}

fun setWhenT(whenT: Long) {
    this.whenT = whenT
}

fun getCompleted(): Boolean? {
    return completed
}

fun setCompleted(completed: Boolean) {
    this.completed = completed
}
</code>```

}

```<code>class AdapterDrops: RecyclerView.Adapter<AdapterDrops.DropHolder> {
    private var mInflater:LayoutInflater
    private var mResults:RealmResults<Drop>
    constructor(context:Context, results: RealmResults<Drop>){
        mInflater = LayoutInflater.from(context)
        mResults = results

    }

    override fun onBindViewHolder(holder: DropHolder?, position: Int) {
        val drop:Drop = mResults[position]!!
        holder!!.mTextWhat.setText(drop.getWhat())

    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): DropHolder {
        val view = mInflater.inflate(R.layout.row_drop, parent, false)
        val holder = DropHolder(view)
        return holder
    }

    override fun getItemCount(): Int {
        return mResults.size   <<<<< pröblem
    }

    class DropHolder: RecyclerView.ViewHolder {

        var mTextWhat:TextView
        constructor(itemView: View):super(itemView){
            mTextWhat = itemView.findViewById<TextView>(R.id.tv_what)

        }

    }

}
</code>```

Thanks guys.

答:
Try this as you are fetching all records from db

```<code>var mResults:OrderedRealmCollection<Drop> = Realm.getDefaultInstance().where(Drop::class.java).findAll()
</code>```

Please define Drop class with empty constructor.

Please remove below code from activity and paste them in your application class

```<code>  //region initialise Realm for application
    Realm.init(this)
    //endregion

    //region creating realm config
    val realmConfig:RealmConfiguration = RealmConfiguration.Builder()
            .name("kotlin_demo.realm")
            .deleteRealmIfMigrationNeeded()
            .build()
    //endregion

    //region for development purpose getting new realm db each time
    Realm.deleteRealm(realmConfig)

    Realm.setDefaultConfiguration(realmConfig)
    //endregion
</code>```

in kotlin no need to define the getter setter methods for Drop class so remove that

Title: RealmResults size is returning Zero

Body:
I have  a little problem, and I couldn't find any results. Yes I did some researches too.

I have a variable mResults = RealmResults < Drop > ;

and this has Data as you can see in the picture below

But when I type >>mResults.size<< it returns 0.
What could the problem be? btw. Im working in Android using kotlin.

The pröblem is in the Recyclerview getItemCöunt

ActivityMain::::

Realm.init(this)
        val configuration = RealmConfiguration.Builder().build()
        Realm.setDefaultConfiguration(configuration)
    mRealm = Realm.getDefaultInstance()
            val results:RealmResults<Drop> = mRealm.where(Drop::class.java).findAll()

            mToolbar = findViewById<Toolbar>(R.id.toolbar)
            mRecycler = findViewById<RecyclerView>(R.id.rv_drops)
            val manager = LinearLayoutManager(this)

            mRecycler.layoutManager = manager
            mRecycler.adapter = AdapterDrops(this, results)

open class Drop : RealmObject {
private var what: String? = null
@PrimaryKey
private var added: Long? = null
private var whenT: Long? = null
private var completed: Boolean? = null

constructor(){}

constructor(what: String, added: Long, whenT: Long, completed: Boolean) : super() {
    this.what = what
    this.added = added
    this.whenT = whenT
    this.completed = completed
}

fun getWhat(): String? {
    return what
}

fun setWhat(what: String) {
    this.what = what
}

fun getAdded(): Long? {
    return added
}

fun setAdded(added: Long) {
    this.added = added
}

fun getWhenT(): Long? {
    return whenT
}

fun setWhenT(whenT: Long) {
    this.whenT = whenT
}

fun getCompleted(): Boolean? {
    return completed
}

fun setCompleted(completed: Boolean) {
    this.completed = completed
}

}

class AdapterDrops: RecyclerView.Adapter<AdapterDrops.DropHolder> {
    private var mInflater:LayoutInflater
    private var mResults:RealmResults<Drop>
    constructor(context:Context, results: RealmResults<Drop>){
        mInflater = LayoutInflater.from(context)
        mResults = results

    }

    override fun onBindViewHolder(holder: DropHolder?, position: Int) {
        val drop:Drop = mResults[position]!!
        holder!!.mTextWhat.setText(drop.getWhat())

    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): DropHolder {
        val view = mInflater.inflate(R.layout.row_drop, parent, false)
        val holder = DropHolder(view)
        return holder
    }

    override fun getItemCount(): Int {
        return mResults.size   <<<<< pröblem
    }

    class DropHolder: RecyclerView.ViewHolder {

        var mTextWhat:TextView
        constructor(itemView: View):super(itemView){
            mTextWhat = itemView.findViewById<TextView>(R.id.tv_what)

        }

    }

}

Thanks guys.

Body:
Try this as you are fetching all records from db

var mResults:OrderedRealmCollection<Drop> = Realm.getDefaultInstance().where(Drop::class.java).findAll()

Please define Drop class with empty constructor.

Please remove below code from activity and paste them in your application class

  //region initialise Realm for application
    Realm.init(this)
    //endregion

    //region creating realm config
    val realmConfig:RealmConfiguration = RealmConfiguration.Builder()
            .name("kotlin_demo.realm")
            .deleteRealmIfMigrationNeeded()
            .build()
    //endregion

    //region for development purpose getting new realm db each time
    Realm.deleteRealm(realmConfig)

    Realm.setDefaultConfiguration(realmConfig)
    //endregion

in kotlin no need to define the getter setter methods for Drop class so remove that


问:
How do I capture response of form.submit
I have the following code:

```<code><script type="text/javascript">
        function SubmitForm()
        {

            form1.submit();
        }

        function ShowResponse()
        {

        }
</script>
.
.
.
<div>
    <a href="#" onclick="SubmitForm();">Click</a>
</div>
</code>```

I want to capture the html response of form1.submit? How do I do this? Can I register any callback function to form1.submit method?

答:
The non-jQuery vanilla Javascript way, extracted from 12me21's comment:

```<code>var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php");
xhr.onload = function(event){
    alert("Success, server responded with: " + event.target.response); // raw response
};
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm"));
xhr.send(formData);
</code>```

For POST's the default content type is "application/x-www-form-urlencoded" which matches what we're sending in the above snippet.  If you want to send "other stuff" or tweak it somehow see here for some nitty gritty details.

OwnerDisplayName: Ngm

Body:
I have the following code:

.
.
.

    Click

I want to capture the html response of form1.submit? How do I do this? Can I register any callback function to form1.submit method?

LastEditorDisplayName: sblundy

Body:
The non-jQuery vanilla Javascript way, extracted from 12me21's comment:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php");
xhr.onload = function(event){
    alert("Success, server responded with: " + event.target.response); // raw response
};
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm"));
xhr.send(formData);

For POST's the default content type is "application/x-www-form-urlencoded" which matches what we're sending in the above snippet.  If you want to send "other stuff" or tweak it somehow see here for some nitty gritty details.


问:
How to send a get to a server and wait a get in my app in Ruby on Rails
I am using Zapier to search some information in google sheets. I used Webhocks to send a GET to his server with a JSON information. The response of GET is an "OK" and I can't custom this.
So, they will execute a task, find what a I want and return a value, but the response must be a GET in my server, and I don't know how to intercept this response in my route.
I'm trying to study Rails Rack to intercept de request in my app, but I don't know how to send the response to the event that sent the first GET.

How is my middleware:

```<code>class DeltaLogger
    def initialize app
        @app = app
    end

    def call env
        Rails.logger.debug "#{env['QUERY_STRING']}"
        @status, @headers, @response = @app.call(env)
        [@status, @headers, @response]
    end
end
</code>```

Thanks!

Example

答:
So, to get the value returned from Zapier, I created two routes and a global class cache.

```<code>class Zapier
require 'httparty'
    def initialize
        @answer = ""
        @id = 0
    end

    def request(uri, task)
        last_event = Event.last
        puts last_event.inspect
        if last_event.nil?
            last_id = 0
        else
            last_id = last_event.event_id
        end
        event_id = last_id + 1
        Event.find_or_create_by(event_id: event_id)
        result = HTTParty.post(uri.to_str,
        :body => {id: event_id, task: task}.to_json,
        :headers => {'content-Type' => 'application/json'})
        @answer = ""
        @id = event_id
    end

    def response(event_id, value)
        if event_id != @id
            @answer = ""
        else
            @answer = value
        end
    end

    def get_answer
        @answer
    end
end
</code>```

And my controller:

```<code>class ZapierEventsController < ApplicationController
  require 'zapier_class'
  before_action :get_task, only: [:get]
  before_action :get_response, only: [:set]
  @@zapier ||= Zapier.new
  def get
    @@zapier.request('https://hooks.zapier.com',@task)
    sleep 10 #Wait for response
    @value = @@zapier.get_answer
    render json: { 'value': @value }, status:
  end

  def set
    @@zapier.response(@id, @value)
    render json: { 'status': 'ok' }, status: 200
  end

  def get_task
    @task = params["task"]
  end
  def get_response
    @id = Integer(params["id"])
    @value = params["value"]
  end
end
</code>```

Now i have to make a Task Mananger

Body:
I am using Zapier to search some information in google sheets. I used Webhocks to send a GET to his server with a JSON information. The response of GET is an "OK" and I can't custom this.
So, they will execute a task, find what a I want and return a value, but the response must be a GET in my server, and I don't know how to intercept this response in my route.
I'm trying to study Rails Rack to intercept de request in my app, but I don't know how to send the response to the event that sent the first GET.

How is my middleware:

class DeltaLogger
    def initialize app
        @app = app
    end

    def call env
        Rails.logger.debug "#{env['QUERY_STRING']}"
        @status, @headers, @response = @app.call(env)
        [@status, @headers, @response]
    end
end

Thanks!

Example

Body:
So, to get the value returned from Zapier, I created two routes and a global class cache.

class Zapier
require 'httparty'
    def initialize
        @answer = ""
        @id = 0
    end

    def request(uri, task)
        last_event = Event.last
        puts last_event.inspect
        if last_event.nil?
            last_id = 0
        else
            last_id = last_event.event_id
        end
        event_id = last_id + 1
        Event.find_or_create_by(event_id: event_id)
        result = HTTParty.post(uri.to_str,
        :body => {id: event_id, task: task}.to_json,
        :headers => {'content-Type' => 'application/json'})
        @answer = ""
        @id = event_id
    end

    def response(event_id, value)
        if event_id != @id
            @answer = ""
        else
            @answer = value
        end
    end

    def get_answer
        @answer
    end
end

And my controller:

class ZapierEventsController < ApplicationController
  require 'zapier_class'
  before_action :get_task, only: [:get]
  before_action :get_response, only: [:set]
  @@zapier ||= Zapier.new
  def get
    @@zapier.request('https://hooks.zapier.com',@task)
    sleep 10 #Wait for response
    @value = @@zapier.get_answer
    render json: { 'value': @value }, status:
  end

  def set
    @@zapier.response(@id, @value)
    render json: { 'status': 'ok' }, status: 200
  end

  def get_task
    @task = params["task"]
  end
  def get_response
    @id = Integer(params["id"])
    @value = params["value"]
  end
end

Now i have to make a Task Mananger


问:
Remove the original variables after converting into dummy variable by dummy.data.frame
I have a dataset having multiple categorical variables and did the conversion through dummy.data.frame function in dummies package.

It seems that I have the original columns also being kept in my output data frame. Is there any option in dummy.data.frame command to remove these originals columns so that i can have only dummy ones for converted ones?

Ex: I wanted to drop Gender and keep only Gender.Female and Gender.Male columns in the output data frame...

My code is:

```<code>my_loan_data.conv <- dummy.data.frame(my_loan_data[,-1],sep = ".")
</code>```

Before conversion, this shows the output of the data frame having categorical variables..

```<code>'data.frame':   614 obs. of  13 variables:
 $ Loan_ID          : chr  "LP001002" "LP001003" "LP001005" "LP001006" ...
 $ Gender           : Factor w/ 3 levels "","Female","Male": 3 3 3 3 3 3 3 3 3 3 ...
 $ Married          : Factor w/ 3 levels "","No","Yes": 2 3 3 3 2 3 3 3 3 3 ...
 $ Dependents       : Factor w/ 5 levels "","0","1","2",..: 2 3 2 2 2 4 2 5 4 3 ...
 $ Education        : Factor w/ 2 levels "Graduate","Not Graduate": 1 1 1 2 1 1 2 1 1 1 ...
 $ Self_Employed    : Factor w/ 3 levels "","No","Yes": 2 2 3 2 2 3 2 2 2 2 ...
 $ ApplicantIncome  : int  5849 4583 3000 2583 6000 5417 2333 3036 4006 12841 ...
 $ CoapplicantIncome: num  0 1508 0 2358 0 ...
 $ LoanAmount       : num  128 128 66 120 141 267 95 158 168 349 ...
 $ Loan_Amount_Term : num  360 360 360 360 360 360 360 360 360 360 ...
 $ Credit_History   : num  1 1 1 1 1 1 1 0 1 1 ...
 $ Property_Area    : Factor w/ 3 levels "Rural","Semiurban",..: 3 1 3 3 3 3 3 2 3 2 ...
 $ Loan_Status      : Factor w/ 2 levels "N","Y": 2 1 2 2 2 2 2 1 2 1 ...
</code>```

After conversion, this shows the output of the data frame having dummy variables:

```<code>'data.frame':   614 obs. of  26 variables:
 $ Gender.                : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Gender.Female          : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Gender.Male            : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Married.               : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Married.No             : int  1 0 0 0 1 0 0 0 0 0 ...
 $ Married.Yes            : int  0 1 1 1 0 1 1 1 1 1 ...
 $ Dependents.            : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Dependents.0           : int  1 0 1 1 1 0 1 0 0 0 ...
 $ Dependents.1           : int  0 1 0 0 0 0 0 0 0 1 ...
 $ Dependents.2           : int  0 0 0 0 0 1 0 0 1 0 ...
 $ Dependents.3+          : int  0 0 0 0 0 0 0 1 0 0 ...
 $ Education.Graduate     : int  1 1 1 0 1 1 0 1 1 1 ...
 $ Education.Not Graduate : int  0 0 0 1 0 0 1 0 0 0 ...
 $ Self_Employed.         : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Self_Employed.No       : int  1 1 0 1 1 0 1 1 1 1 ...
 $ Self_Employed.Yes      : int  0 0 1 0 0 1 0 0 0 0 ...
 $ ApplicantIncome        : int  5849 4583 3000 2583 6000 5417 2333 3036 4006 12841 ...
 $ CoapplicantIncome      : num  0 1508 0 2358 0 ...
 $ LoanAmount             : num  128 128 66 120 141 267 95 158 168 349 ...
 $ Loan_Amount_Term       : num  360 360 360 360 360 360 360 360 360 360 ...
 $ Credit_History         : num  1 1 1 1 1 1 1 0 1 1 ...
 $ Property_Area.Rural    : int  0 1 0 0 0 0 0 0 0 0 ...
 $ Property_Area.Semiurban: int  0 0 0 0 0 0 0 1 0 1 ...
 $ Property_Area.Urban    : int  1 0 1 1 1 1 1 0 1 0 ...
 $ Loan_Status.N          : int  0 1 0 0 0 0 0 1 0 1 ...
 $ Loan_Status.Y          : int  1 0 1 1 1 1 1 0 1 0 ...
</code>```

答:
To illustrate the problem with a small example:

```<code># example data
df1 <- data.frame(x = as.factor(1:3),
                  y = as.factor(c(10:11, "")))
df1
#   x  y
# 1 1 10
# 2 2 11
# 3 3

str(df1)
# 'data.frame': 3 obs. of  2 variables:
#   $ x: Factor w/ 3 levels "1","2","3": 1 2 3
#   $ y: Factor w/ 3 levels "","10","11": 2 3 1

dummy.data.frame(df1, sep = ".")
#   x.1 x.2 x.3 y. y.10 y.11
# 1   1   0   0  0    1    0
# 2   0   1   0  0    0    1
# 3   0   0   1  1    0    0
</code>```

Notice, the "y." column, this is not the original column, but the "" level of y.

Now, do I need to keep the blanks or not for analysis is another question.

Body:
I have a dataset having multiple categorical variables and did the conversion through dummy.data.frame function in dummies package.

It seems that I have the original columns also being kept in my output data frame. Is there any option in dummy.data.frame command to remove these originals columns so that i can have only dummy ones for converted ones?

Ex: I wanted to drop Gender and keep only Gender.Female and Gender.Male columns in the output data frame...

My code is:

my_loan_data.conv <- dummy.data.frame(my_loan_data[,-1],sep = ".")

Before conversion, this shows the output of the data frame having categorical variables..

'data.frame':   614 obs. of  13 variables:
 $ Loan_ID          : chr  "LP001002" "LP001003" "LP001005" "LP001006" ...
 $ Gender           : Factor w/ 3 levels "","Female","Male": 3 3 3 3 3 3 3 3 3 3 ...
 $ Married          : Factor w/ 3 levels "","No","Yes": 2 3 3 3 2 3 3 3 3 3 ...
 $ Dependents       : Factor w/ 5 levels "","0","1","2",..: 2 3 2 2 2 4 2 5 4 3 ...
 $ Education        : Factor w/ 2 levels "Graduate","Not Graduate": 1 1 1 2 1 1 2 1 1 1 ...
 $ Self_Employed    : Factor w/ 3 levels "","No","Yes": 2 2 3 2 2 3 2 2 2 2 ...
 $ ApplicantIncome  : int  5849 4583 3000 2583 6000 5417 2333 3036 4006 12841 ...
 $ CoapplicantIncome: num  0 1508 0 2358 0 ...
 $ LoanAmount       : num  128 128 66 120 141 267 95 158 168 349 ...
 $ Loan_Amount_Term : num  360 360 360 360 360 360 360 360 360 360 ...
 $ Credit_History   : num  1 1 1 1 1 1 1 0 1 1 ...
 $ Property_Area    : Factor w/ 3 levels "Rural","Semiurban",..: 3 1 3 3 3 3 3 2 3 2 ...
 $ Loan_Status      : Factor w/ 2 levels "N","Y": 2 1 2 2 2 2 2 1 2 1 ...

After conversion, this shows the output of the data frame having dummy variables:

'data.frame':   614 obs. of  26 variables:
 $ Gender.                : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Gender.Female          : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Gender.Male            : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Married.               : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Married.No             : int  1 0 0 0 1 0 0 0 0 0 ...
 $ Married.Yes            : int  0 1 1 1 0 1 1 1 1 1 ...
 $ Dependents.            : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Dependents.0           : int  1 0 1 1 1 0 1 0 0 0 ...
 $ Dependents.1           : int  0 1 0 0 0 0 0 0 0 1 ...
 $ Dependents.2           : int  0 0 0 0 0 1 0 0 1 0 ...
 $ Dependents.3+          : int  0 0 0 0 0 0 0 1 0 0 ...
 $ Education.Graduate     : int  1 1 1 0 1 1 0 1 1 1 ...
 $ Education.Not Graduate : int  0 0 0 1 0 0 1 0 0 0 ...
 $ Self_Employed.         : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Self_Employed.No       : int  1 1 0 1 1 0 1 1 1 1 ...
 $ Self_Employed.Yes      : int  0 0 1 0 0 1 0 0 0 0 ...
 $ ApplicantIncome        : int  5849 4583 3000 2583 6000 5417 2333 3036 4006 12841 ...
 $ CoapplicantIncome      : num  0 1508 0 2358 0 ...
 $ LoanAmount             : num  128 128 66 120 141 267 95 158 168 349 ...
 $ Loan_Amount_Term       : num  360 360 360 360 360 360 360 360 360 360 ...
 $ Credit_History         : num  1 1 1 1 1 1 1 0 1 1 ...
 $ Property_Area.Rural    : int  0 1 0 0 0 0 0 0 0 0 ...
 $ Property_Area.Semiurban: int  0 0 0 0 0 0 0 1 0 1 ...
 $ Property_Area.Urban    : int  1 0 1 1 1 1 1 0 1 0 ...
 $ Loan_Status.N          : int  0 1 0 0 0 0 0 1 0 1 ...
 $ Loan_Status.Y          : int  1 0 1 1 1 1 1 0 1 0 ...

Body:
To illustrate the problem with a small example:

# example data
df1 <- data.frame(x = as.factor(1:3),
                  y = as.factor(c(10:11, "")))
df1
#   x  y
# 1 1 10
# 2 2 11
# 3 3

str(df1)
# 'data.frame': 3 obs. of  2 variables:
#   $ x: Factor w/ 3 levels "1","2","3": 1 2 3
#   $ y: Factor w/ 3 levels "","10","11": 2 3 1

dummy.data.frame(df1, sep = ".")
#   x.1 x.2 x.3 y. y.10 y.11
# 1   1   0   0  0    1    0
# 2   0   1   0  0    0    1
# 3   0   0   1  1    0    0

Notice, the "y." column, this is not the original column, but the "" level of y.

Now, do I need to keep the blanks or not for analysis is another question.


问:
Watermark not showing when, print the html file to pdf
I have a HTML webpage. In center, the page have a watermark image(any format jpg, png, svg) placed using CSS. If i print the html page. It showing all webpage contents, except the watermark. What i'll do for showing that watermark.

CSS

```<code>.inner-print-content {
    margin-left: 15mm;
    margin-right: 15mm;
    text-align: justify;
    font-size: 12px;
    background-image: url(/logo.svg);
    background-repeat: no-repeat;
    background-position: center top;
}
</code>```

答:
Way do you not just use a normal IMG tag for the watermark? Here is a basic example, if you print this page the happy emoji will be printed but the sad one won't, because the sad one is a css background image and the happy one is just an normal img tag.

div  {
    background-image: url("https://emojipedia-us.s3.amazonaws.com/thumbs/120/google/119/crying-face_1f622.png");
    background-size: cover;
    width:100px;
    height: 100px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<img src="https://emojipedia-us.s3.amazonaws.com/thumbs/120/google/119/grinning-face_1f600.png"  width=100" height="100"></img></code>```

Body:
I have a HTML webpage. In center, the page have a watermark image(any format jpg, png, svg) placed using CSS. If i print the html page. It showing all webpage contents, except the watermark. What i'll do for showing that watermark.

CSS

.inner-print-content {
    margin-left: 15mm;
    margin-right: 15mm;
    text-align: justify;
    font-size: 12px;
    background-image: url(/logo.svg);
    background-repeat: no-repeat;
    background-position: center top;
}

Body:
Way do you not just use a normal IMG tag for the watermark? Here is a basic example, if you print this page the happy emoji will be printed but the sad one won't, because the sad one is a css background image and the happy one is just an normal img tag.

div  {
    background-image: url("https://emojipedia-us.s3.amazonaws.com/thumbs/120/google/119/crying-face_1f622.png");
    background-size: cover;
    width:100px;
    height: 100px;

}

<div></div>
<img src="https://emojipedia-us.s3.amazonaws.com/thumbs/120/google/119/grinning-face_1f600.png"  width=100" height="100"></img>


问:
Python Date format conversion to UK
I have a CSV file which has a date column with some dirty data i.e. dates stored in different formats (US and UK). I'd like to create another CSV file with the dates converted so they are consistently stored in the UK format enabling me to import correctly into my SQL database.

I'd like the dates to be converted to the following format:

'05-12-2017'
'07-11-2017'
'24-04-1999'
'28-01-1987'..

I tried the following code:

```<code>df = F.pd.read_csv('Book1.csv', parse_dates = [0], dayfirst = True)
df['Date'] = df['Date'].apply(F.pd.to_datetime, format = '%m/%d/%Y')
df['date_eu'] = df['Date'].dt.strftime('%m-%d-%Y')
df
</code>```

, but it throws an error while trying to convert the US dates

```<code>ValueError: time data '20/01/2018' does not match format '%m/%d/%Y' (match)
</code>```

Can someone please help?

Thanks

答:
You could use a Try-Parse-Else-Approach:

```<code>from datetime import datetime

def normalizeDateString(ds):
    '''normalizes a date of format "d / d / dddd " to "dd/dd/dddd"'''
    sp = ds.replace(" ","").split("/")
    if len(sp[0])==1:
        sp[0]="0"+sp[0]
    if len(sp[1])==1:
        sp[1]="0"+sp[1]

    return sp[0]+"/"+sp[1]+"/"+sp[2]

def parseDT(dateString):
    ''' parses "dd/dd/yyyy" as US (month/day/year). Fallback: day/month/year on error'''
    try:
        repl =  normalizeDateString(dateString)
        return datetime.strptime(repl, "%m/%d/%Y").date()
    except:
        return datetime.strptime(repl, "%d/%m/%Y").date()

print(parseDT("14/12/2018"))
print(parseDT("2/5/2018")) # ok for US
print(parseDT("22/5/2018")) # not ok for US
print(parseDT("12/2/2018"))
print(parseDT("2/1/2018"))
</code>```

Output:

```<code>2018-12-14
2018-02-05  # US ok
2018-05-22  # EN by except
2018-12-02
2018-02-01
</code>```

HTH

Title: Python Date format conversion to UK

Body:
I have a CSV file which has a date column with some dirty data i.e. dates stored in different formats (US and UK). I'd like to create another CSV file with the dates converted so they are consistently stored in the UK format enabling me to import correctly into my SQL database.

I'd like the dates to be converted to the following format:

'05-12-2017'
'07-11-2017'
'24-04-1999'
'28-01-1987'..

I tried the following code:

df = F.pd.read_csv('Book1.csv', parse_dates = [0], dayfirst = True)
df['Date'] = df['Date'].apply(F.pd.to_datetime, format = '%m/%d/%Y')
df['date_eu'] = df['Date'].dt.strftime('%m-%d-%Y')
df

, but it throws an error while trying to convert the US dates

ValueError: time data '20/01/2018' does not match format '%m/%d/%Y' (match)

Can someone please help?

Thanks

Body:
You could use a Try-Parse-Else-Approach:

from datetime import datetime

def normalizeDateString(ds):
    '''normalizes a date of format "d / d / dddd " to "dd/dd/dddd"'''
    sp = ds.replace(" ","").split("/")
    if len(sp[0])==1:
        sp[0]="0"+sp[0]
    if len(sp[1])==1:
        sp[1]="0"+sp[1]

    return sp[0]+"/"+sp[1]+"/"+sp[2]

def parseDT(dateString):
    ''' parses "dd/dd/yyyy" as US (month/day/year). Fallback: day/month/year on error'''
    try:
        repl =  normalizeDateString(dateString)
        return datetime.strptime(repl, "%m/%d/%Y").date()
    except:
        return datetime.strptime(repl, "%d/%m/%Y").date()

print(parseDT("14/12/2018"))
print(parseDT("2/5/2018")) # ok for US
print(parseDT("22/5/2018")) # not ok for US
print(parseDT("12/2/2018"))
print(parseDT("2/1/2018"))

Output:

2018-12-14
2018-02-05  # US ok
2018-05-22  # EN by except
2018-12-02
2018-02-01

HTH


问:
What are these ^M's that keep showing up in my files in emacs?
I think it may have to do with TextMate, but we work in a small team and are having some issues with full-file conflicts of nearly identical files in git – in one branch the files have a ^M appended to each line.

What is this mysterious ^M character supposed to do, and where could it be coming from?

Our developers use emacs on Windows/Mac, TextMate on Mac, coda on Mac, and occasionally the wp-admin text editor.

Did anybody ever have this issue stemming from one of those?

答:
I'm using Android Studio (JetBrains IntelliJ IDEA) on Mac OS and my problem was that ^M started to show up in some files in my pull request on GitHub.
What worked for me was changing line separator for a file.

Open the desired file in the editor go to
File go to
Line Separators then
choose the best option for you
(for me it was LF - Unix and OS X(\n) )

According to the next article this problem is a result of confused line endings between operating systems:
http://jonathonstaff.com/blog/issues-with-line-endings/

And more information you can find here:
https://www.jetbrains.com/help/idea/configuring-line-separators.html#d84378e48


问:
Chef windows how to click a button in a GUI
There is a bat file which does some configurations and launch a GUI .In that GUI some buttons need to be clicked to install some other software components .Chef supports these scenarios? How to automate them using Chef? It's a 3rd party installer and has lot of code so deciding it is difficult .Launching a GUI and clicking on a button is easier..vendor has not provided any commands or API..</p>

答: Have you tried typing app.exe /? to see if the usage was implemented. Also, use procmon (sysinternals) to monitor the parameters passed when executed.</p>


问:
Db Structure Issue with EF
I have been messing around with Entity Framework code first for the last while trying to see what I can do with it.
One scenario I tested out was trying to duplicate the following DB schema:

Tables:

Person

Player

Manager

Person table holds basic data name,age etc.

Player table only holds information related to a player: currentclubId, positionId etc
The players basic details would be provided through a 1:1 relationship with the Person table on the Player Id and the PersonId.

Manager table is very similar to player table holds a 1:1 relationship with Person Table on the Manager Id and the person Id.

The idea behind this schema is that a person can be player and a manager throughout their career and I wanted to avoid duplication the basic details.

My issue is that EF Generates the Player Model with a Person Property.

```<code>public class Player {
    public Person Person {get;set;}
    .....
}
</code>```

Therefore to get the Players first name you must call Player.Person.FirstName.
This flow was fine for the beginning but I'm starting to see a performance issue with the Player and Manager queries as they have to fetch from two tables.

Is there any way I can refactor this schema to improve the performance while not violating the requirements?

答:
Based on the schema in the diagram you provided i'd expect something like ...

```<code>public class Person
{
   [Key]
   public int PersonId {get;set;}

   [ForeignKey("Player")]
   public int player {get;set;} // make this int? if a person can optionally be a player

   public virtual Player Player {get;set;}
   ...
}
</code>```

You'd then repeat this property model for the manager properties on the person object.
Having then done this, when querying the db you should use .Include() to avoid recursive subqueries back to the db in a "lazy loading situation".

For example:

```<code>var allJoes = Db.Persons
   .Where(p => p.Name.Contains("Joe"))
   .Include(p => p.Player)
   .Include(p => p.Manager);
</code>```

You can optionally then add sub selection to pull only the fields you need from that data from the db.

```<code>var joePieces = allJoes
    .Select(j => new { j.Name, j.Player.PlayerId, j.Manager.ManagerId });
</code>```

With the final result being the execution from ...

```<code>var results = joePieces.ToArray();
</code>```

Title: Db Structure Issue with EF

Body:
I have been messing around with Entity Framework code first for the last while trying to see what I can do with it.
One scenario I tested out was trying to duplicate the following DB schema:

Tables:

Person

Player

Manager

Person table holds basic data name,age etc.

Player table only holds information related to a player: currentclubId, positionId etc
The players basic details would be provided through a 1:1 relationship with the Person table on the Player Id and the PersonId.

Manager table is very similar to player table holds a 1:1 relationship with Person Table on the Manager Id and the person Id.

The idea behind this schema is that a person can be player and a manager throughout their career and I wanted to avoid duplication the basic details.

My issue is that EF Generates the Player Model with a Person Property.

public class Player {
    public Person Person {get;set;}
    .....
}

Therefore to get the Players first name you must call Player.Person.FirstName.
This flow was fine for the beginning but I'm starting to see a performance issue with the Player and Manager queries as they have to fetch from two tables.

Is there any way I can refactor this schema to improve the performance while not violating the requirements?

Body:
Based on the schema in the diagram you provided i'd expect something like ...

public class Person
{
   [Key]
   public int PersonId {get;set;}

   [ForeignKey("Player")]
   public int player {get;set;} // make this int? if a person can optionally be a player

   public virtual Player Player {get;set;}
   ...
}

You'd then repeat this property model for the manager properties on the person object.
Having then done this, when querying the db you should use .Include() to avoid recursive subqueries back to the db in a "lazy loading situation".

For example:

var allJoes = Db.Persons
   .Where(p => p.Name.Contains("Joe"))
   .Include(p => p.Player)
   .Include(p => p.Manager);

You can optionally then add sub selection to pull only the fields you need from that data from the db.

var joePieces = allJoes
    .Select(j => new { j.Name, j.Player.PlayerId, j.Manager.ManagerId });

With the final result being the execution from ...

var results = joePieces.ToArray();


问:
Rewriterule -> 500 internal error with .htaccess
I tried everything for my problem, but nothing works.

I'm not familiar with regex, but I did my best.

Here is the code:

```<code>Options +FollowSymlinks

RewriteEngine on

RewriteRule ^series/([A-Z]+)?$ series.php?code=$1 [L,QSA,NC]
RewriteRule ^exercices/([A-Z]+)-([0-9]+)/([0-9]+)?$ exercices.php?code=$1&serie=$2&question=$3 [L,QSA,NC]

# Remove php extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

# Redirect to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect to 404 if url is not correct
RewriteCond %{THE_REQUEST} \s.+?\.php[\s?] [NC]
RewriteCond %{REQUEST_URI} !/index\.php [NC]
RewriteRule ^ https://www.test.com/404 [L]

# Errors
ErrorDocument 404 https://www.test.com/404
ErrorDocument 403 https://www.test.com/
ErrorDocument 500 https://www.test.com/
</code>```

With that, I have a beautiful 500 internal error...

I've really did some research, but I'm still stuck.

Can someone help me please ?
(sorry for my bad english)

答:
I just added " /? " just before the " $ " sign, and it's working :

```<code>RewriteRule ^series/([A-Z]+)/?$ /series.php?code=$1 [L]
RewriteRule ^exercices/([A-Z]+)-([0-9]+)-([0-9]+)/?$ /exercices.php?code=$1&serie=$2&question=$3 [L]
</code>```

I hope it will help for people who have the same issue.

Thanks.

Body:
I tried everything for my problem, but nothing works.

I'm not familiar with regex, but I did my best.

Here is the code:

Options +FollowSymlinks

RewriteEngine on

RewriteRule ^series/([A-Z]+)?$ series.php?code=$1 [L,QSA,NC]
RewriteRule ^exercices/([A-Z]+)-([0-9]+)/([0-9]+)?$ exercices.php?code=$1&serie=$2&question=$3 [L,QSA,NC]

# Remove php extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

# Redirect to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect to 404 if url is not correct
RewriteCond %{THE_REQUEST} \s.+?\.php[\s?] [NC]
RewriteCond %{REQUEST_URI} !/index\.php [NC]
RewriteRule ^ https://www.test.com/404 [L]

# Errors
ErrorDocument 404 https://www.test.com/404
ErrorDocument 403 https://www.test.com/
ErrorDocument 500 https://www.test.com/

With that, I have a beautiful 500 internal error...

I've really did some research, but I'm still stuck.

Can someone help me please ?
(sorry for my bad english)

Body:
I just added " /? " just before the " $ " sign, and it's working :

RewriteRule ^series/([A-Z]+)/?$ /series.php?code=$1 [L]
RewriteRule ^exercices/([A-Z]+)-([0-9]+)-([0-9]+)/?$ /exercices.php?code=$1&serie=$2&question=$3 [L]

I hope it will help for people who have the same issue.

Thanks.


问:
SASS is prepending unicode content with backslash (\)

Problem

I'm trying to produce some unicode characters after compiling my *.scss file.

As an example, I have the following (SCSS):

```<code>.element:after {
    content: "\a0";
}
</code>```

When the file is compiled, it outputs the following (CSS):

```<code>.element:after {
    content: "\\a0";
}
</code>```

Notice the extra unwanted backslash (\).

Attempted Solution #1

I did try the solution here: Sass: unicode escape is not preserved in .css file, which suggests introducing the following function:

```<code>@function unicode($str) {
    @return unquote("\"")+unquote(str-insert($str, "\\", 1))+unquote("\"")
}
</code>```

And using it like so (SCSS):

```<code>.element:after {
    content: unicode("a0");
}
</code>```

However, this produces the following (CSS)

```<code>.element:after {
    content: "\\" ")+unquote(str-insert($str, " \\\\ ", 1))+unquote(" \\ "";
}
</code>```

Notice, it's not even invoking the function as intended. Why is that?

Project Details

I'm using these libraries in Maven:

```<code><dependency>
    <groupId>net.jawr</groupId>
    <artifactId>jawr-core</artifactId>
    <version>3.9</version>
</dependency>

<dependency>
    <groupId>net.jawr.extensions</groupId>
    <artifactId>jawr-spring-extension</artifactId>
    <version>3.9</version>
</dependency>

<dependency>
    <groupId>com.darrinholst</groupId>
    <artifactId>sass-java-gems</artifactId>
    <version>3.4.20.0</version>
</dependency>

<dependency>
    <groupId>org.jruby</groupId>
    <artifactId>jruby-core</artifactId>
    <version>9.1.5.0</version>
</dependency>

<dependency>
    <groupId>org.jruby</groupId>
    <artifactId>jruby-stdlib</artifactId>
    <version>9.1.5.0</version>
</dependency>
</code>```

Temporary solution

Don't use unicodes in SCSS. Instead, use Font Awesome in the HTML (keeping Font Awesome in a CSS file).

答:
I had the same issue while trying to use a custom icons font. The solution I found is creating a mixin which looks like this :

```<code>@mixin class-for-icon($name, $code) {
    .icon-#{$name}::before {
        content: unquote("\"\\#{$code}\"");
    }
}
</code>```

And then I can use it like this :

```<code>@include class-for-icon('myIcon', 'e1ff');

/* generates */

.icon-myIcon::before {
    content: "\e1ff";
}
</code>```

I use node-sass 4.5.3 to compile my sass files into css, and this is working well (currently using it in production on a few projects)

Hope this helps !

Body:
Problem

I'm trying to produce some unicode characters after compiling my *.scss file.

As an example, I have the following (SCSS):

.element:after {
    content: "\a0";
}

When the file is compiled, it outputs the following (CSS):

.element:after {
    content: "\\a0";
}

Notice the extra unwanted backslash (\).

Attempted Solution #1

I did try the solution here: Sass: unicode escape is not preserved in .css file, which suggests introducing the following function:

@function unicode($str) {
    @return unquote("\"")+unquote(str-insert($str, "\\", 1))+unquote("\"")
}

And using it like so (SCSS):

.element:after {
    content: unicode("a0");
}

However, this produces the following (CSS)

.element:after {
    content: "\\" ")+unquote(str-insert($str, " \\\\ ", 1))+unquote(" \\ "";
}

Notice, it's not even invoking the function as intended. Why is that?

Project Details

I'm using these libraries in Maven:

<dependency>
    <groupId>net.jawr</groupId>
    <artifactId>jawr-core</artifactId>
    <version>3.9</version>
</dependency>

<dependency>
    <groupId>net.jawr.extensions</groupId>
    <artifactId>jawr-spring-extension</artifactId>
    <version>3.9</version>
</dependency>

<dependency>
    <groupId>com.darrinholst</groupId>
    <artifactId>sass-java-gems</artifactId>
    <version>3.4.20.0</version>
</dependency>

<dependency>
    <groupId>org.jruby</groupId>
    <artifactId>jruby-core</artifactId>
    <version>9.1.5.0</version>
</dependency>

<dependency>
    <groupId>org.jruby</groupId>
    <artifactId>jruby-stdlib</artifactId>
    <version>9.1.5.0</version>
</dependency>

Temporary solution

Don't use unicodes in SCSS. Instead, use Font Awesome in the HTML (keeping Font Awesome in a CSS file).

Body:
I had the same issue while trying to use a custom icons font. The solution I found is creating a mixin which looks like this :

@mixin class-for-icon($name, $code) {
    .icon-#{$name}::before {
        content: unquote("\"\\#{$code}\"");
    }
}

And then I can use it like this :

@include class-for-icon('myIcon', 'e1ff');

/* generates */

.icon-myIcon::before {
    content: "\e1ff";
}

I use node-sass 4.5.3 to compile my sass files into css, and this is working well (currently using it in production on a few projects)

Hope this helps !


问:
How to skip JAR deploy in maven and deploy the assembly only
My project packages to a Spring Boot fat-jar.

I configured 2 extra build plugins:

Generate an executable using Launch4j Plugin (it get the resulting fat-jar and embed it on a executable file)

Assembly the resulting executable in a ZIP

Now I want to deploy only the assembly resulting zip to my maven repository.

This is my build section:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.akathist.maven.plugins.launch4j</groupId>
            <artifactId>launch4j-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>l4j-clui</id>
                    <phase>package</phase>
                    <goals>
                        <goal>launch4j</goal>
                    </goals>
                    <configuration>
                        <headerType>console</headerType>
                        <outfile>target/${project.build.finalName}.exe</outfile>
                        <jar>target/${project.build.finalName}.jar</jar>
                        <manifest>launch4j/besser-updater.manifest</manifest>
                        <classPath>
                            <mainClass>org.springframework.boot.loader.JarLauncher</mainClass>
                        </classPath>
                        <jre>
                            <minVersion>1.8.0_131</minVersion>
                            <jdkPreference>preferJre</jdkPreference>
                            <runtimeBits>32/64</runtimeBits>
                        </jre>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <id>assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <descriptors>
                            <descriptor>launch4j/assembly.xml</descriptor>
                        </descriptors>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

How can I configure the deploy phase to ignore the jar artifact and deploy only the zip assembly file?

答:
I found the solution. I just ignored the default-deploy execution id.

```<code><build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <executions>
                <!-- disable standard deploy -->
                <execution>
                    <id>default-deploy</id>
                    <phase>none</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

Body:
My project packages to a Spring Boot fat-jar.

I configured 2 extra build plugins:

Generate an executable using Launch4j Plugin (it get the resulting fat-jar and embed it on a executable file)

Assembly the resulting executable in a ZIP

Now I want to deploy only the assembly resulting zip to my maven repository.

This is my build section:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.akathist.maven.plugins.launch4j</groupId>
            <artifactId>launch4j-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>l4j-clui</id>
                    <phase>package</phase>
                    <goals>
                        <goal>launch4j</goal>
                    </goals>
                    <configuration>
                        <headerType>console</headerType>
                        <outfile>target/${project.build.finalName}.exe</outfile>
                        <jar>target/${project.build.finalName}.jar</jar>
                        <manifest>launch4j/besser-updater.manifest</manifest>
                        <classPath>
                            <mainClass>org.springframework.boot.loader.JarLauncher</mainClass>
                        </classPath>
                        <jre>
                            <minVersion>1.8.0_131</minVersion>
                            <jdkPreference>preferJre</jdkPreference>
                            <runtimeBits>32/64</runtimeBits>
                        </jre>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <id>assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <descriptors>
                            <descriptor>launch4j/assembly.xml</descriptor>
                        </descriptors>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

How can I configure the deploy phase to ignore the jar artifact and deploy only the zip assembly file?

Body:
I found the solution. I just ignored the default-deploy execution id.

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <executions>
                <!-- disable standard deploy -->
                <execution>
                    <id>default-deploy</id>
                    <phase>none</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


问:
fragment error at transaction add function's 2nd parameter
transaction add() Function and replace function error in android error in second argument of function</p>

```<code>  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        FragmentManager fm=getFragmentManager();
        FragmentTransaction transaction=fm.beginTransaction();
        switch (item.getItemId()) {
            case R.id.navigation_home:

                Chats c=new Chats();
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.content, Chats).commit();
                transaction.commit();
                return true;
            case R.id.navigation_dashboard:
                mTextMessage.setText(R.string.title_dashboard);
                return true;
            case R.id.navigation_notifications:
                mTextMessage.setText(R.string.title_notifications);
                return true;
        }
        return false;
    }
};
</code>```

答:
You need to pass fragment object and not the class name as argument.

Change this

```<code>getSupportFragmentManager().beginTransaction()
                    .add(R.id.content, Chats).commit();
</code>```

to

```<code>getSupportFragmentManager().beginTransaction()
                    .add(R.id.content, c).commit();
</code>```

Body:
transaction add() Function and replace function error in android error in second argument of function

  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        FragmentManager fm=getFragmentManager();
        FragmentTransaction transaction=fm.beginTransaction();
        switch (item.getItemId()) {
            case R.id.navigation_home:

                Chats c=new Chats();
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.content, Chats).commit();
                transaction.commit();
                return true;
            case R.id.navigation_dashboard:
                mTextMessage.setText(R.string.title_dashboard);
                return true;
            case R.id.navigation_notifications:
                mTextMessage.setText(R.string.title_notifications);
                return true;
        }
        return false;
    }
};

Body:
You need to pass fragment object and not the class name as argument.

Change this

getSupportFragmentManager().beginTransaction()
                    .add(R.id.content, Chats).commit();

to

getSupportFragmentManager().beginTransaction()
                    .add(R.id.content, c).commit();


问:
pandas - construct column depending on values in 2 separate columns of dataframe
I have a pandas dataframe which looks similar to this(i have cooked up an example, since I can't share the data)

```<code>raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Scouts'],
        'company': ['1st', '2nd', '1st', '2nd', '2nd'],
        'thisValue': [1, 2, 3, 2, 7],
        'total': [3, 3, 5, 5, 7]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'thisValue', 'total'])
df
</code>```

The output is :

```<code>    regiment    company thisValue   total
0   Nighthawks  1st         1         3
1   Nighthawks  2nd         2         3
2   Dragoons    1st         3         5
3   Dragoons    2nd         2         5
4   Scouts      2nd         7         7
</code>```

I want to have statistics about count of values of eachValue for a regiment. That is I need the resulting dataframe to be like this:

```<code>regiment    1stCompanyValue 2nd_Company_Value   total
Nighthawks         1               2              3
Dragoons           3               2              5
Scouts             0               7              7
</code>```

I tried grouping it on company values, but then not sure how to proceed. How can this be done in pandas?

答:
We can make use of pivot,groupby and concat i.e

```<code>one  = df.pivot(columns='company',values='thisValue',index='regiment').add_suffix('_company_value').fillna(0)
two = df.groupby('regiment')['total'].first()

ndf = pd.concat([one,two],1)

              1st_company_value  2nd_company_value  total
regiment
Dragoons                  3.0                2.0      5
Nighthawks                1.0                2.0      3
Scouts                    0.0                7.0      7
</code>```

Body:
I have a pandas dataframe which looks similar to this(i have cooked up an example, since I can't share the data)

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Scouts'],
        'company': ['1st', '2nd', '1st', '2nd', '2nd'],
        'thisValue': [1, 2, 3, 2, 7],
        'total': [3, 3, 5, 5, 7]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'thisValue', 'total'])
df

The output is :

    regiment    company thisValue   total
0   Nighthawks  1st         1         3
1   Nighthawks  2nd         2         3
2   Dragoons    1st         3         5
3   Dragoons    2nd         2         5
4   Scouts      2nd         7         7

I want to have statistics about count of values of eachValue for a regiment. That is I need the resulting dataframe to be like this:

regiment    1stCompanyValue 2nd_Company_Value   total
Nighthawks         1               2              3
Dragoons           3               2              5
Scouts             0               7              7

I tried grouping it on company values, but then not sure how to proceed. How can this be done in pandas?

Body:
We can make use of pivot,groupby and concat i.e

one  = df.pivot(columns='company',values='thisValue',index='regiment').add_suffix('_company_value').fillna(0)
two = df.groupby('regiment')['total'].first()

ndf = pd.concat([one,two],1)

              1st_company_value  2nd_company_value  total
regiment
Dragoons                  3.0                2.0      5
Nighthawks                1.0                2.0      3
Scouts                    0.0                7.0      7


问:
Confused by asynchronous mechanism
I am confused by the fact that android is multi-threaded. If the code of a particular activity method is executing, can it be interrupted in the middle by onPause(), onStop() or onDestroy() or by another method like the onPostExecute() of an asynctask?

Edit 1

This question is not about activities life-cycle. What i am really asking is if the onPause() method can interrupt the onClick() method (just an example) and i would like to read more about how exactly android manages activities, calls their async methods etc...

Edit 2

Ok, it seems that i have found the relevant information i needed in the developer docs (don't know if it is explained better somewhere else): Threading Performance:

Internals

The main thread has a very simple design: Its only job is to take and
  execute blocks of work from a thread-safe work queue until its app is
  terminated. The framework generates some of these blocks of work from
  a variety of places. These places include callbacks associated with
  lifecycle information, user events such as input, or events coming
  from other apps and processes. In addition, app can explicitly enqueue
  blocks on their own, without using the framework.

It states that callbacks relative to activity lifecycle, user events such as input and other code are all managed using a "thread-safe work queue". This is central to understanding Android asynchronous programming. It explains a lots of things, such as why onClick() will be never be interrupted by activity onPause(), or why onClick() will be never be interrupted by a runnable posted using a Handler object (allocated in the main thread). So, for example, the onPostExecute() of an AsyncTask cannot interrupt the onClick() method (or onStart(), onResume(), onPause() etc...). As a novice android programmer, it was a bit confusing at first.

答:
This is a good question to ask I think. However, Here is my understanding:

When an Application starts, a Dalvik Virtual Machine (DVM) is assigned to it and works separately. So no two Applications interrupt each other as each of the application is managed by separate DVM.

Coming to Activity, it is a component of Android and runs on main thread. Android OS manages priority level to it's components. It gives high priority level to Activity, Services and may be other component(s). The OS maintains the non interruption behaviour of main thread.

Further when you run an AsyncTask, it is a long running task in background but dependent on Application context. So the OS does not guarantee to manage it.

Now regarding activity life cycle. As @nihal_softy said, activity has it's own life cycle which start from onCreate() and encounters onStart(), onResume(), onPause(), onStop() and onDestroy(). You can call these methods from anywhere of your Activity or from an AsyncTask and it will called but does not mean that the Activity will go in background or will destroy. In a simpler word, if you call onPause() from an AsyncTask, it does not mean that the Activity will be sent to background (if in foreground). Because when an Activity will go in background then it calls it's life cycle methods such as onPause() and onStop() as callback. But converse is not true.

I hope my understanding will help you to get the answer.

Title: Confused by asynchronous mechanism


问:
How can I extract a filename from a path using Perl?
I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

```<code>$file = $path =~ s/.*\///;
</code>```

I am very new to Perl.

答:
Why reinvent the wheel? Use the File::Basename module:

```<code>use File::Basename;
...
$file = basename($path);
</code>```

Why did $file=$path=~s/.*\///; not work?

=~ has higher precedence than =

So

```<code>$file = $path =~s/.*\///;
</code>```

is treated as:

```<code>$file = ($path =~s/.*\///);
</code>```

which does the replacement in $path and assigns either 1 (if replacement occurs) or '' (if no replacement occurs).

What you want is:

```<code>($file = $path) =~s/.*\///;
</code>```

which assigns the value of $path to $file and then does the replacement in $path.

But again there are many problems with this solution:

It is incorrect. A filename in Unix based systems (not sure about Windows) can contain newline. But . by default does not match a newline. So you'll have to use a s modifier so that . matches newline as well:

```<code>($file = $path) =~s/.*\///s;
</code>```

Most importantly it is not portable as it is assuming / is the path separator which is not the case with some platforms like Windows (which uses \), Mac (which uses :). So use the module and let it handle all these issues for you.

Body:
I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

$file = $path =~ s/.*\///;

I am very new to Perl.

Body:
Why reinvent the wheel? Use the File::Basename module:

use File::Basename;
...
$file = basename($path);

Why did $file=$path=~s/.*\///; not work?

=~ has higher precedence than =

So

$file = $path =~s/.*\///;

is treated as:

$file = ($path =~s/.*\///);

which does the replacement in $path and assigns either 1 (if replacement occurs) or '' (if no replacement occurs).

What you want is:

($file = $path) =~s/.*\///;

which assigns the value of $path to $file and then does the replacement in $path.

But again there are many problems with this solution:

It is incorrect. A filename in Unix based systems (not sure about Windows) can contain newline. But . by default does not match a newline. So you'll have to use a s modifier so that . matches newline as well:

($file = $path) =~s/.*\///s;

Most importantly it is not portable as it is assuming / is the path separator which is not the case with some platforms like Windows (which uses \), Mac (which uses :). So use the module and let it handle all these issues for you.