问:
Replacements for switch statement in Python?
I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?

答:
The following works for my situation when I need a simple switch-case to call a bunch of methods and not to just print some text. After playing with lambda and globals it hit me as the simplest option for me so far. Maybe it will help someone also:</p>

```<code>def start():
    print("Start")

def stop():
    print("Stop")

def print_help():
    print("Help")

def choose_action(arg):
    return {
        "start": start,
        "stop": stop,
        "help": print_help,
    }.get(arg, print_help)

argument = sys.argv[1].strip()
choose_action(argument)()  # calling a method from the given string
</code>```

Body:
The following works for my situation when I need a simple switch-case to call a bunch of methods and not to just print some text. After playing with lambda and globals it hit me as the simplest option for me so far. Maybe it will help someone also:

def start():
    print("Start")

def stop():
    print("Stop")

def print_help():
    print("Help")

def choose_action(arg):
    return {
        "start": start,
        "stop": stop,
        "help": print_help,
    }.get(arg, print_help)

argument = sys.argv[1].strip()
choose_action(argument)()  # calling a method from the given string


来源: stackexchange

问:
Apply a vector-valued function to a vector. Result not as expected
In Matloff's The Art of R programming, he uses the function below (z12) to demonstrate the use of a vector-valued function.

My question is: When applying the function to 1:8, why does it return 1 2 3 4 ... 1 4 9 16 ... and not 1, 1, 2, 4, 3, 9 ...? After all, isn't z^2 right next to z in the return statement?

答:
The c() is the concatenation operator. It joins two vectors end to end. You can do

```<code>c(1, 2)
# [1]  1  2
c(1:3, 9:11)
# [1]  1  2  3  9 10 11
</code>```

So the function you've defined is running

```<code>c(1:8, (1:8)^2)
# [1]  1  2  3  4  5  6  7  8  1  4  9 16 25 36 49 64
</code>```

So the c() puts together the vectors after they have been extended. Not as the extension is happening.

ContentLicense: CC BY-SA 3.0

Body:
The c() is the concatenation operator. It joins two vectors end to end. You can do

c(1, 2)
# [1]  1  2
c(1:3, 9:11)
# [1]  1  2  3  9 10 11

So the function you've defined is running

c(1:8, (1:8)^2)
# [1]  1  2  3  4  5  6  7  8  1  4  9 16 25 36 49 64

So the c() puts together the vectors after they have been extended. Not as the extension is happening.


问:
special serial number generator
Please, I am building an app with python and want to generate serial numbers for people that register on my app, but I don't really know how to go about it.

the serial number is supposed to be of the format 1JA002, where the first number '1' determines the function or department of the user, the first two letters are extracted from the first and the last name in that order, but the last three digits are developed based on the time you register, for instance the very first person to register will have a number '001' as his number and these digits must just be three.

Also the last three digits are also dependent on the arrangement of the letters, so if two persons have letters 'AA' from their first and last name and they were to register at the same time, the second letter from the first name is used to separate the individuals and also give them their corresponding numbers.

#   below is my code and where I got stuck!!

```<code>firstName='sam'   # example names
LastName='john'
f=firstName
L=lastName
po=f[0]
ko=L[0]
firstUser='001'
def numbergen():#function to generate serial code
    count=0
    SerialNumber=''
    while True:
        if count==0:#count indicates the number time the user registered
            if (po<ko) or (po>ko) or (po==ko):
                SerialNumber+='1'+'po'+'ko'+firstUser
        count+=1
        if count==1:#serial number generation for very next user
            initialUser='002' # the very second user
</code>```

答:
Try https://github.com/vernondcole/idstring for ideas.

Generally, adding meaning into a serial number (like your proposal for department plus first and last initials) is a bad idea. What happens when Juile Jones (1JJ100) gets married to Jeffry Adams (2JA100)?  Does she have to get a new number (1JA100) or does she keep her old one?  If you ignore the name change, why bother with encoding the initials in the first place? What if she changes departments, too? 2JA101?

You also must maintain the state of your serial numbers outside of your generator program. If you encode using first-and-last initials, you will need a database to keep track of all 26 squared (times number of departments) possible combinations.

Having said all that, you could get close to what you want with...

```<code>import idstring
department = "1"
initials = department + firstname[0] + lastname[0]
try:
  seed_value = function_to_fetch_a_seed(initials)
except someError:
  seed_value = "100"
id = idstring.IDstring(None, seed_value, initials)
print('This id =', id)
id += 1
function_to_store_your_seed(id, initials)
</code>```

Which will meet your use case, except that the initials will follow, rather than lead, the serial portion -- and a check digit will be added.

Title: special serial number generator

Body:
Please, I am building an app with python and want to generate serial numbers for people that register on my app, but I don't really know how to go about it.

the serial number is supposed to be of the format 1JA002, where the first number '1' determines the function or department of the user, the first two letters are extracted from the first and the last name in that order, but the last three digits are developed based on the time you register, for instance the very first person to register will have a number '001' as his number and these digits must just be three.

Also the last three digits are also dependent on the arrangement of the letters, so if two persons have letters 'AA' from their first and last name and they were to register at the same time, the second letter from the first name is used to separate the individuals and also give them their corresponding numbers.

#   below is my code and where I got stuck!!

firstName='sam'   # example names
LastName='john'
f=firstName
L=lastName
po=f[0]
ko=L[0]
firstUser='001'
def numbergen():#function to generate serial code
    count=0
    SerialNumber=''
    while True:
        if count==0:#count indicates the number time the user registered
            if (po<ko) or (po>ko) or (po==ko):
                SerialNumber+='1'+'po'+'ko'+firstUser
        count+=1
        if count==1:#serial number generation for very next user
            initialUser='002' # the very second user

Body:
Try https://github.com/vernondcole/idstring for ideas.

Generally, adding meaning into a serial number (like your proposal for department plus first and last initials) is a bad idea. What happens when Juile Jones (1JJ100) gets married to Jeffry Adams (2JA100)?  Does she have to get a new number (1JA100) or does she keep her old one?  If you ignore the name change, why bother with encoding the initials in the first place? What if she changes departments, too? 2JA101?

You also must maintain the state of your serial numbers outside of your generator program. If you encode using first-and-last initials, you will need a database to keep track of all 26 squared (times number of departments) possible combinations.

Having said all that, you could get close to what you want with...

import idstring
department = "1"
initials = department + firstname[0] + lastname[0]
try:
  seed_value = function_to_fetch_a_seed(initials)
except someError:
  seed_value = "100"
id = idstring.IDstring(None, seed_value, initials)
print('This id =', id)
id += 1
function_to_store_your_seed(id, initials)

Which will meet your use case, except that the initials will follow, rather than lead, the serial portion -- and a check digit will be added.


问:
c queue linked list - printing queue changes value of pointers?
I have created a linked-list queue in C. my structs are as such:

```<code>typedef struct Node{
    int *data;
    struct Node *next;
} node;

typedef struct Queue{
    node *front, *rear;
} queue;
</code>```

In my main() function, I am getting a user input determining the length of the queue, creating an array of this length, and getting a user input for each element of the array. I then call a function called runQueue().

```<code>void runQueue(int array[], int len){
    queue *q = (queue *)malloc(sizeof(queue));
    q->front = q->rear = NULL;
    for(int i = len - 1; i >= 0; i--){ //len-1, user doesn't input 0-based index
        enQueue(q, array[i]);
    }
    printQueue(q);
    enQueue(q,4);
    printQueue(q);
    queueMenu(q);
}
</code>```

In this function I am calling a function enQueue() in a loop to enqueue all the nodes into the queue from the array. I am then calling printQueue().

```<code>void enQueue(queue *q, int data){
    node *tmp = (node *) malloc(sizeof(node));
    tmp->data = data;
    tmp->next = NULL;

    if (q->rear == NULL){
        q->front = q->rear = tmp;
        return;
    }

    q->rear->next = tmp;
    q->rear = tmp;
}

void printQueue(queue *q){
    int iterator = 0;
    queue *tmp = (queue *)malloc(sizeof(queue));
    tmp = q;
    while(tmp->front->next != tmp->rear->next && tmp->front != NULL){
        iterator += 1;
        //printf("in loop, i = %d\n",iterator);
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->front->data, tmp->front, tmp->front->next);
        tmp->front = tmp->front->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->front->data, tmp->front, tmp->front->next);
    free(tmp);
}
</code>```

The problem is as such: I can run this, and the enqueue function seems to work fine. The first time I call printQueue(), the function will print the correct result. However, after printing the queue, the values of the front and rear pointer change, and printing trying to perform any more operations on the queue of course results in a segfault since it's trying to access different areas of memory than those it is supposed to. How is it that the values of the pointers is being changed? I have copied the queue to a temporary queue before preceding to change pointer values, so why are the actual queue's pointers changing?

EDIT:
as an example of how the array is input to the queue -

```<code>int array[3] = {4,3,2};
runQueue(array,3);
</code>```

then within runQueue(), the for loop is decrementing through the array and calling enQueue() for each element in the array. In this case, calling enQueue(q,2) followed by enQueue(q,3) then enQueue(q,4).

EDIT 2:
I tried Thomas Blanquet's suggestion by changing the function to this:

```<code>void printQueue(queue *q){
    int iterator = 0;
    node *tmp = (node *)malloc(sizeof(node));
    tmp = q->front;
    while(tmp != NULL){
        iterator += 1;
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->data, tmp, tmp->next);
        tmp = tmp->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);
    free(tmp);
}
</code>```

After making this change, the pointers are correct, but I am still getting a segfault before exiting the function.

EDIT 3:
I tried commenting out free(tmp), but I am still getting a segfault. However I found the problem! Somehow I had a printf() outside the loop which I didn't notice:

```<code>printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);
</code>```

Removing this now stops the segfault and all the pointers are correct. Many thanks!

答:
There are some problems in your "printQueue" :

First of all, why do you allocate tmp with a malloc, then giving it q's value ?
Your malloc allocates memory and returns the address of this memory, but changing it using q, you lost this memory.

Then tmp contains the address of q, so when you do :

```<code>tmp->front = tmp->front->next;
</code>```

you change the front node of your queue.

You should do something like node *tmp = q->front; and use it to iterate over your linked list, almost as you already do with tmp->front. The difference is you will not change the address of your front node in your queue, but a tmp variable which points on the front node of it.

Finally, by using tmp != NULL as condition, you will not have to do a special case for your last node, after your loop.

Edit

I forgot something, by doing free(tmp), which have, in your post, the same value than q, you free the queue structure so you can't use it anymore in your code.

Body:
I have created a linked-list queue in C. my structs are as such:

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

typedef struct Queue{
    node *front, *rear;
} queue;

In my main() function, I am getting a user input determining the length of the queue, creating an array of this length, and getting a user input for each element of the array. I then call a function called runQueue().

void runQueue(int array[], int len){
    queue *q = (queue *)malloc(sizeof(queue));
    q->front = q->rear = NULL;
    for(int i = len - 1; i >= 0; i--){ //len-1, user doesn't input 0-based index
        enQueue(q, array[i]);
    }
    printQueue(q);
    enQueue(q,4);
    printQueue(q);
    queueMenu(q);
}

In this function I am calling a function enQueue() in a loop to enqueue all the nodes into the queue from the array. I am then calling printQueue().

void enQueue(queue *q, int data){
    node *tmp = (node *) malloc(sizeof(node));
    tmp->data = data;
    tmp->next = NULL;

    if (q->rear == NULL){
        q->front = q->rear = tmp;
        return;
    }

    q->rear->next = tmp;
    q->rear = tmp;
}

void printQueue(queue *q){
    int iterator = 0;
    queue *tmp = (queue *)malloc(sizeof(queue));
    tmp = q;
    while(tmp->front->next != tmp->rear->next && tmp->front != NULL){
        iterator += 1;
        //printf("in loop, i = %d\n",iterator);
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->front->data, tmp->front, tmp->front->next);
        tmp->front = tmp->front->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->front->data, tmp->front, tmp->front->next);
    free(tmp);
}

The problem is as such: I can run this, and the enqueue function seems to work fine. The first time I call printQueue(), the function will print the correct result. However, after printing the queue, the values of the front and rear pointer change, and printing trying to perform any more operations on the queue of course results in a segfault since it's trying to access different areas of memory than those it is supposed to. How is it that the values of the pointers is being changed? I have copied the queue to a temporary queue before preceding to change pointer values, so why are the actual queue's pointers changing?

EDIT:
as an example of how the array is input to the queue -

int array[3] = {4,3,2};
runQueue(array,3);

then within runQueue(), the for loop is decrementing through the array and calling enQueue() for each element in the array. In this case, calling enQueue(q,2) followed by enQueue(q,3) then enQueue(q,4).

EDIT 2:
I tried Thomas Blanquet's suggestion by changing the function to this:

void printQueue(queue *q){
    int iterator = 0;
    node *tmp = (node *)malloc(sizeof(node));
    tmp = q->front;
    while(tmp != NULL){
        iterator += 1;
        printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator, tmp->data, tmp, tmp->next);
        tmp = tmp->next;
    }
    printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);
    free(tmp);
}

After making this change, the pointers are correct, but I am still getting a segfault before exiting the function.

EDIT 3:
I tried commenting out free(tmp), but I am still getting a segfault. However I found the problem! Somehow I had a printf() outside the loop which I didn't notice:

printf("Queue node %d: data val %d ptr %p front ptr %p\n", iterator+1, tmp->data, tmp, tmp->next);

Removing this now stops the segfault and all the pointers are correct. Many thanks!

Body:
There are some problems in your "printQueue" :

First of all, why do you allocate tmp with a malloc, then giving it q's value ?
Your malloc allocates memory and returns the address of this memory, but changing it using q, you lost this memory.

Then tmp contains the address of q, so when you do :

tmp->front = tmp->front->next;

you change the front node of your queue.

You should do something like node *tmp = q->front; and use it to iterate over your linked list, almost as you already do with tmp->front. The difference is you will not change the address of your front node in your queue, but a tmp variable which points on the front node of it.

Finally, by using tmp != NULL as condition, you will not have to do a special case for your last node, after your loop.

Edit

I forgot something, by doing free(tmp), which have, in your post, the same value than q, you free the queue structure so you can't use it anymore in your code.


问:
Regex Syntax changes between POSIX and PCRE
We are currently in the process of upgrading our Varnish Cache servers.
As part of the process, we upgraded only one of them to see how it behaves compared to the older versions.

Some of the major changes made in this new version is changing the regex engine from POSIX to PCRE. That means that some of our purges (regex purges) have stopped working on the newer server.

I was wondering if anyone can list/point me to a list of actual syntax differences between POSIX and PCRE. Or maybe a function that converts a POSIX regex to PCRE regex.

This is so that I can convert only the purges going to the newer server - without affecting the current regex syntax that is implemented in the system for the other servers.

答:
See Regular Expression Engine Comparison Chart maintained by Roger Qui which a copy of the information available in the original answer. (Credit to Uberhumus for the new link.)

[Original Answer]
See Flavor Comparison at Regular-Expressions.info.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Why does jQuery event handler is not changing the value?
I have used the event handler to change the message but after clicking the link the message is not changing.

```<code><a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
</code>```

Here is the Javascript file:

```<code>$("a").bind("click", { message : msg }, function(event) {
    msg = "Changed msg";
    alert(event.data.message);
  });
</code>```

答:
If you want to change the text of the anchor tag, you can do so like this:

```<code>$("a").bind("click", function(event) {
  $(event.target).text('Changed msg');
});
</code>```

This can be shorted as this inside of the event handler will refer to event.target or what you've bound the function to (the anchor tag). So you can write the above like so:

```<code>$("a").bind("click", function() {
  $(this).text('Changed msg');
});
</code>```

You can't simply set values to mutate the document object model (DOM). You need to use methods like text and html to tell jQuery what you want to do. You can do so with vanilla JavaScript.

As mentioned in the comments, eventData is an object you can include to pass long to the event handler. But it can't mutate or change things.

Body:
I have used the event handler to change the message but after clicking the link the message is not changing.

Test 1
Test 2

Here is the Javascript file:

$("a").bind("click", { message : msg }, function(event) {
    msg = "Changed msg";
    alert(event.data.message);
  });

Body:
If you want to change the text of the anchor tag, you can do so like this:

$("a").bind("click", function(event) {
  $(event.target).text('Changed msg');
});

This can be shorted as this inside of the event handler will refer to event.target or what you've bound the function to (the anchor tag). So you can write the above like so:

$("a").bind("click", function() {
  $(this).text('Changed msg');
});

You can't simply set values to mutate the document object model (DOM). You need to use methods like text and html to tell jQuery what you want to do. You can do so with vanilla JavaScript.

As mentioned in the comments, eventData is an object you can include to pass long to the event handler. But it can't mutate or change things.


问:
Linux - Splash screen for Java application
On Windows I use Exe4J to start my Java Application. This has the following advantages:

Splashscreen which shows before Java starts

Possibility to update a Label on the splash screen during the startup, until the application is folly loaded ("Initializing Flux compensator","Reordering high nibbles", etc.)

Now I want to implement this on Linux. I start my App with a Shell script, but would love an easy way to show some kind of splash GUI with a label on it, which I can update from my shell script during startup.

Is there an easy way to fire up a minimal GUI from a shell script, and to update the label in it from the shell script, without having to compile a separate executable for it for linux (and maybe even Mac OS X)?

PS: I don't want to use the Java build in splash screen because of the Label which has to be updated dynamically.

答:
The standard Java 1.6+ solution for screen splash does support custom drawing on the splash Screensplash Tutorial.

Here is an example for a splash controller, which has a main method -- run it with a splash parameter to see the result.

```<code>package somepackage;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

public class SplashController implements ActionListener {
    private static final int X = 20, W = 300;
    private static final int TEXT_H = 10, BAR_H = 10;

    private int textY, barY;
    private int barPos = 0;

    private final SplashScreen splash;
    private Graphics2D graph;

    public SplashController(final int msgXOffset, final int msgYOffset) {
    splash = SplashScreen.getSplashScreen();
    if (splash == null) {
         System.out.println("Error: no splash image specified on the command line");
         return;
    }

   // compute base positions for text and progress bar
   final Dimension splashSize = splash.getSize();
   textY = splashSize.height - msgYOffset;
   barY = splashSize.height - msgYOffset;

   graph = splash.createGraphics();
   //timer.start();
}

public SplashController() {
    this(30, 30);
}

@Override
public void actionPerformed(final ActionEvent e) {
    drawSplashProgress(msg);
}

public void closeSplash() {
    if (splash != null) {
        splash.close();
    }
}

private String msg;

public void drawSplashProgress(final String msg) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            SplashController.this.msg = msg;
            graph.setRenderingHint(RenderingHints.KEY_INTERPOLATION,                              RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graph.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

            // clear what we don't need from previous state
            graph.setComposite(AlphaComposite.Clear);

            final FontMetrics fm = graph.getFontMetrics();
            final Rectangle2D textsize = fm.getStringBounds(msg, graph);

            graph.fillRect(X, textY - 1, W, (int) textsize.getHeight() + 5);
            if (barPos == 0) {
                graph.fillRect(X - 3, barY, W + 10, BAR_H);
            }

            // draw new state
            graph.setPaintMode();

            // draw message
            graph.setColor(Color.BLACK);
            graph.drawString(msg, X, textY + TEXT_H);
            try {
                splash.update();
            } catch (final IllegalStateException e) {
               // can be ignored
            }
        }
     });
}

public static void main(final String args[]) throws Exception {
    final SplashController test = new SplashController();
    for (int i = 0; i < 50; i++) {
       test.drawSplashProgress("Progress step number " + i);
       Thread.sleep(250);
    }
    test.closeSplash();
}
}
</code>```

Body:
The standard Java 1.6+ solution for screen splash does support custom drawing on the splash Screensplash Tutorial.

Here is an example for a splash controller, which has a main method -- run it with a splash parameter to see the result.

package somepackage;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

public class SplashController implements ActionListener {
    private static final int X = 20, W = 300;
    private static final int TEXT_H = 10, BAR_H = 10;

    private int textY, barY;
    private int barPos = 0;

    private final SplashScreen splash;
    private Graphics2D graph;

    public SplashController(final int msgXOffset, final int msgYOffset) {
    splash = SplashScreen.getSplashScreen();
    if (splash == null) {
         System.out.println("Error: no splash image specified on the command line");
         return;
    }

   // compute base positions for text and progress bar
   final Dimension splashSize = splash.getSize();
   textY = splashSize.height - msgYOffset;
   barY = splashSize.height - msgYOffset;

   graph = splash.createGraphics();
   //timer.start();
}

public SplashController() {
    this(30, 30);
}

@Override
public void actionPerformed(final ActionEvent e) {
    drawSplashProgress(msg);
}

public void closeSplash() {
    if (splash != null) {
        splash.close();
    }
}

private String msg;

public void drawSplashProgress(final String msg) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            SplashController.this.msg = msg;
            graph.setRenderingHint(RenderingHints.KEY_INTERPOLATION,                              RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graph.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

            // clear what we don't need from previous state
            graph.setComposite(AlphaComposite.Clear);

            final FontMetrics fm = graph.getFontMetrics();
            final Rectangle2D textsize = fm.getStringBounds(msg, graph);

            graph.fillRect(X, textY - 1, W, (int) textsize.getHeight() + 5);
            if (barPos == 0) {
                graph.fillRect(X - 3, barY, W + 10, BAR_H);
            }

            // draw new state
            graph.setPaintMode();

            // draw message
            graph.setColor(Color.BLACK);
            graph.drawString(msg, X, textY + TEXT_H);
            try {
                splash.update();
            } catch (final IllegalStateException e) {
               // can be ignored
            }
        }
     });
}

public static void main(final String args[]) throws Exception {
    final SplashController test = new SplashController();
    for (int i = 0; i < 50; i++) {
       test.drawSplashProgress("Progress step number " + i);
       Thread.sleep(250);
    }
    test.closeSplash();
}
}


问:
Select website and its language in AlertDialog and save it
I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other.  My simple code like this:

```<code>      private SharedPreferences prefs;
      private static final String SELECTED_ITEM = "SelectedItem";
      private SharedPreferences.Editor sharedPrefEditor;

  @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    else if (id == R.id.web)
    final CharSequence[] items={"English","Arabic","Russian"};

        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);

        builder.setTitle("Choose Website");
        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {}
        });

        builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                webView = (WebView) findViewById(R.id.webView);
                int website=current_page;

                if("English".equals(items[which]))
                {
                    webView.loadUrl("https://english.com");
                    website=("https://english.com");
                }
                else if("Arabic".equals(items[which]))
                {
                    webView.loadUrl("https://arabic.com");
                    website=("https://arabic.com");
                }
                else if("Russian".equals(items[which]))
                {
                    webView.loadUrl("https://russian.com");
                    website=("https://russian.com");
                }

                saveSelectedItem(website);
            }
        });
        builder.show();
    }

 private int getSelectedItem() {
      if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    return prefs.getInt(SELECTED_ITEM, -1);
}

  private void saveSelectedItem(int which) {
    if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt(SELECTED_ITEM, which);
    sharedPrefEditor.commit();
}
</code>```

答:
in saveSelectedItem(website);
You are passing a string and the method requires int

```<code>private void saveSelectedItem(int which) {
    if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt(SELECTED_ITEM, which);
    sharedPrefEditor.commit();
</code>```

For saving your data in shared preferences
i recommend to use GSON
i recommend to make a class for example

```<code>public class WebsiteData
{
    @SerializedName("lang")
    @Expose
    private String lang ;
    @SerializedName("website")
    @Expose
    private String website;

    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang= lang;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website= website;
    }
}
</code>```

When user select language create new object and set the language with the chosen language and the set the website with its corresponding value
Then Turn object into String by Gson Like following :

```<code>Gson gson = new Gson();
String dataToSave = gson.toJson(WebsiteData);

String loadedString = getUserData(context);
WebsiteData loadedData = gson.fromJson(loadedString, WebsiteData.class);
</code>```

to save and load data use the following methods :

```<code>public void saveUserData(Context context, String data) {
    SharedPreferences sharedpreferences;
    sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(DATA_KEY, data);
    editor.apply();
}

public String getUserData(Context context) {
    SharedPreferences sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
    return sharedpreferences.getString(DATA_KEY, null);
}
</code>```

Body:
I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other.  My simple code like this:

      private SharedPreferences prefs;
      private static final String SELECTED_ITEM = "SelectedItem";
      private SharedPreferences.Editor sharedPrefEditor;

  @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    else if (id == R.id.web)
    final CharSequence[] items={"English","Arabic","Russian"};

        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);

        builder.setTitle("Choose Website");
        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {}
        });

        builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                webView = (WebView) findViewById(R.id.webView);
                int website=current_page;

                if("English".equals(items[which]))
                {
                    webView.loadUrl("https://english.com");
                    website=("https://english.com");
                }
                else if("Arabic".equals(items[which]))
                {
                    webView.loadUrl("https://arabic.com");
                    website=("https://arabic.com");
                }
                else if("Russian".equals(items[which]))
                {
                    webView.loadUrl("https://russian.com");
                    website=("https://russian.com");
                }

                saveSelectedItem(website);
            }
        });
        builder.show();
    }

 private int getSelectedItem() {
      if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    return prefs.getInt(SELECTED_ITEM, -1);
}

  private void saveSelectedItem(int which) {
    if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt(SELECTED_ITEM, which);
    sharedPrefEditor.commit();
}

Body:
in saveSelectedItem(website);
You are passing a string and the method requires int

private void saveSelectedItem(int which) {
    if (prefs == null) {
        prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    }
    sharedPrefEditor = prefs.edit();
    sharedPrefEditor.putInt(SELECTED_ITEM, which);
    sharedPrefEditor.commit();

For saving your data in shared preferences
i recommend to use GSON
i recommend to make a class for example

public class WebsiteData
{
    @SerializedName("lang")
    @Expose
    private String lang ;
    @SerializedName("website")
    @Expose
    private String website;

    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang= lang;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website= website;
    }
}

When user select language create new object and set the language with the chosen language and the set the website with its corresponding value
Then Turn object into String by Gson Like following :

Gson gson = new Gson();
String dataToSave = gson.toJson(WebsiteData);

String loadedString = getUserData(context);
WebsiteData loadedData = gson.fromJson(loadedString, WebsiteData.class);

to save and load data use the following methods :

public void saveUserData(Context context, String data) {
    SharedPreferences sharedpreferences;
    sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(DATA_KEY, data);
    editor.apply();
}

public String getUserData(Context context) {
    SharedPreferences sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
    return sharedpreferences.getString(DATA_KEY, null);
}


问:
PHP - preload all classes/functions
Is there a way to preload (as opposed to autoload) all classes/functions for a PHP project?

I'm thinking about a web application that runs with PHPFastCGI (so we can bootstrap part of it and reuse this bit between requests), and that uses composer (could its classmap be used for this purpose?).

Here's some context:

"Regular" PHP applications handle a single request and then they get killed. Preloading all classes/functions means having a bigger booting time, autoloading only classes used for the request is a clever optimization but it could be further improved (they require many "read filesystem" operations which are slow), usually by grouping in a single file classes that are likely to be used for all requests (this is what ClassPreloader solves).

However booting an application to handle only one request and then kill it is not the only option: with PHP FastCGI it is possible to keep the application alive between requests. This allows us to shave booting time off the Request/Response time (e.g. instantiate all services from the DIC once).

While profiling my applications, I've noticed that autoloading always appear in the top 10 most expensive exclusive function calls. In a PHP FastCGI application it might make sense to move class loading in the boot phase to remove it entirely from the Request/Response time. I'm trying to find out (I'll do some benchmarking and publish the result).

For more information about this "exotic" way of running PHP applications, see:

Using ReactPHP to keep your application alive: http://marcjschmidt.de/blog/2014/02/08/php-high-performance.html

Fabien Potencier talking about it: https://youtu.be/gpNbmEnRLBU

Using PHPFastCGI to let FastCGI (e.g. php-fpm) manage PHP processes: http://andrewcarteruk.github.io/slides/breaking-boundaries-with-fastcgi/

Using Aerys, a non blocking HTTP application: http://blog.kelunik.com/2015/10/21/getting-started-with-aerys.html

Using AppServer, a native PHP web server: http://www.sitepoint.com/appserver-a-production-ready-php-based-server/

答:
It turns out composer has an option to pre-include files. See the doc.
Copied from the doc:

```<code>{
  "autoload": {
    "files": ["src/preload.php"]
  }
}
</code>```

You can run the necessary code startup/preload, and in your case use:

```<code>class_exists(SomeClass1::class, TRUE);
class_exists(SomeClass2::class, TRUE);
</code>```

Which is a trick to force autoload of a class.

Title: PHP - preload all classes/functions

Body:
It turns out composer has an option to pre-include files. See the doc.
Copied from the doc:

{
  "autoload": {
    "files": ["src/preload.php"]
  }
}

You can run the necessary code startup/preload, and in your case use:

class_exists(SomeClass1::class, TRUE);
class_exists(SomeClass2::class, TRUE);

Which is a trick to force autoload of a class.


问:
php custom exception handling
I am wanting to handle exceptions in my PHP application myself.

When I throw an exception I am wanting to pass along a title to be used in the error page.

Can someone please link me to a good tutorial, or write a clear explanation of how the exception handling actually works (eg how to know what sort of exception you are dealing with, etc.

答:
Official docs is a good place to start - http://php.net/manual/en/language.exceptions.php.

If it is just a message that you want to capture you would do it at follows;

```<code>try{
    throw new Exception("This is your error message");
}catch(Exception $e){
    print $e->getMessage();
}
</code>```

If you want to capture specific errors you would use:

```<code>try{
    throw new SQLException("SQL error message");
}catch(SQLException $e){
    print "SQL Error: ".$e->getMessage();
}catch(Exception $e){
    print "Error: ".$e->getMessage();
}
</code>```

For the record - you'd need to define SQLException. This can be done as simply as:

```<code>class SQLException extends Exception{

}
</code>```

For a title and message you would extend the Exception class:

```<code>class CustomException extends Exception{

    protected $title;

    public function __construct($title, $message, $code = 0, Exception $previous = null) {

        $this->title = $title;

        parent::__construct($message, $code, $previous);

    }

    public function getTitle(){
        return $this->title;
    }

}
</code>```

You could invoke this using :

```<code>try{
    throw new CustomException("My Title", "My error message");
}catch(CustomException $e){
    print $e->getTitle()."<br />".$e->getMessage();
}
</code>```

Title: php custom exception handling

Body:
Official docs is a good place to start - http://php.net/manual/en/language.exceptions.php.

If it is just a message that you want to capture you would do it at follows;

try{
    throw new Exception("This is your error message");
}catch(Exception $e){
    print $e->getMessage();
}

If you want to capture specific errors you would use:

try{
    throw new SQLException("SQL error message");
}catch(SQLException $e){
    print "SQL Error: ".$e->getMessage();
}catch(Exception $e){
    print "Error: ".$e->getMessage();
}

For the record - you'd need to define SQLException. This can be done as simply as:

class SQLException extends Exception{

}

For a title and message you would extend the Exception class:

class CustomException extends Exception{

    protected $title;

    public function __construct($title, $message, $code = 0, Exception $previous = null) {

        $this->title = $title;

        parent::__construct($message, $code, $previous);

    }

    public function getTitle(){
        return $this->title;
    }

}

You could invoke this using :

try{
    throw new CustomException("My Title", "My error message");
}catch(CustomException $e){
    print $e->getTitle()."<br />".$e->getMessage();
}


问:
expression has type 'a list -> 'b list but an expression was expected of type 'b list
This is my function

```<code>let rec helper inputList = function
  | [] -> []
  | a :: b :: hd ->
    if a = b then helper ([b::hd])
    else a :: helper (b::hd)
</code>```

It's not complete, however I can't see why I keep getting the error in the title at helper ([b::hd]). I've tried helper (b::hd) or helper (b::hd::[]) however all come up with errors. How do I make it so that it works?

答:
There are multiple errors here. One is that the keyword function means we have an implicit parameter over which we are working. So the pattern matching happens on that "invisible" parameter. But here you defined probably the explicit one: inputList. So we can remove that one:

```<code>let rec helper = function
  | [] -> []
  | a :: b :: hd -> if a = b then helper ([b::hd]) else a :: helper (b:: hd)</code>```

Next there is a problem with the types: in the recursion, you use:

helper ([b::hd]); and

a :: helper (b:: hd)

But you put these on the same line, and that makes no sense, since the first one passes a list of lists of elements, and the second a list of elements. So the result of the first one would be a list of list of elements, and the second one a list of elements. It does not make sense to merge these.

If I understood correctly that you want to ensure that no two consecutive elements should occur that are equal, then we should rewrite it to:

```<code>let rec helper = function
  | [] -> []
  | a :: b :: hd -> if a = b then helper <b>(b::hd)</b> else a :: helper (b:: hd)</code>```

You have defined two patterns here:

one for the empty list; and

one for a list with at least two elements.

The second one will perform recursion on the tail of the list b :: hd. So that means that eventually when we pass it a list with n elements, it will recursively work on a list with n-1 elements, n-2 elements, etc. But eventually it will have one element. And there is no case for that. So we need to add a case for the one element pattern:

```<code>let rec helper = function
  | [] -> []
  <b>| h :: [] -> h :: []</b>
  | a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)</code>```

Body:
This is my function

let rec helper inputList = function
  | [] -> []
  | a :: b :: hd ->
    if a = b then helper ([b::hd])
    else a :: helper (b::hd)

It's not complete, however I can't see why I keep getting the error in the title at helper ([b::hd]). I've tried helper (b::hd) or helper (b::hd::[]) however all come up with errors. How do I make it so that it works?

Body:
There are multiple errors here. One is that the keyword function means we have an implicit parameter over which we are working. So the pattern matching happens on that "invisible" parameter. But here you defined probably the explicit one: inputList. So we can remove that one:

let rec helper = function
  | [] -> []
  | a :: b :: hd -> if a = b then helper ([b::hd]) else a :: helper (b:: hd)

Next there is a problem with the types: in the recursion, you use:

helper ([b::hd]); and

a :: helper (b:: hd)

But you put these on the same line, and that makes no sense, since the first one passes a list of lists of elements, and the second a list of elements. So the result of the first one would be a list of list of elements, and the second one a list of elements. It does not make sense to merge these.

If I understood correctly that you want to ensure that no two consecutive elements should occur that are equal, then we should rewrite it to:

let rec helper = function
  | [] -> []
  | a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)

You have defined two patterns here:

one for the empty list; and

one for a list with at least two elements.

The second one will perform recursion on the tail of the list b :: hd. So that means that eventually when we pass it a list with n elements, it will recursively work on a list with n-1 elements, n-2 elements, etc. But eventually it will have one element. And there is no case for that. So we need to add a case for the one element pattern:

let rec helper = function
  | [] -> []
  | h :: [] -> h :: []
  | a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)


问:
object does not support item assignment in tensor flow
In the simple program before I am not able to do a simple task and get the following error.

```<code>import tensorflow as tf

x_1= tf.constant([1, 2, 3])
x_1= tf.reshape(x_1, shape= (1, 3))
x_2= tf.constant([2, 3, 4])
x_2= tf.reshape(x_2, shape= (1, 3))
x_3= tf.constant([3, 4, 5])
x_3= tf.reshape(x_3, shape= (1, 3))
x= tf.concat((x_1, x_2, x_3), axis=0)

for i in range(0, 3):
    x[i, :]= x[i, :]+ 1

init= tf.global_variables_initializer()

with tf.Session() as sess:
   y= sess.run(x)
</code>```

And I get the following error:

TypeError: 'Tensor' object does not support item assignment

答:
Tensor objects cannot be accessed/modified by index.

Here's the code fixed:

```<code>import tensorflow as tf

x_1 = tf.constant([1, 2, 3])
x_1 = tf.reshape(x_1, shape=(1, 3))
x_2 = tf.constant([2, 3, 4])
x_2 = tf.reshape(x_2, shape=(1, 3))
x_3 = tf.constant([3, 4, 5])
x_3 = tf.reshape(x_3, shape=(1, 3))
x = tf.concat((x_1, x_2, x_3), axis=0)

x = tf.add(x, tf.constant(1, shape=x.shape))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    y = sess.run(x)
    print(y)
</code>```

Body:
In the simple program before I am not able to do a simple task and get the following error.

import tensorflow as tf

x_1= tf.constant([1, 2, 3])
x_1= tf.reshape(x_1, shape= (1, 3))
x_2= tf.constant([2, 3, 4])
x_2= tf.reshape(x_2, shape= (1, 3))
x_3= tf.constant([3, 4, 5])
x_3= tf.reshape(x_3, shape= (1, 3))
x= tf.concat((x_1, x_2, x_3), axis=0)

for i in range(0, 3):
    x[i, :]= x[i, :]+ 1

init= tf.global_variables_initializer()

with tf.Session() as sess:
   y= sess.run(x)

And I get the following error:

TypeError: 'Tensor' object does not support item assignment

Body:
Tensor objects cannot be accessed/modified by index.

Here's the code fixed:

import tensorflow as tf

x_1 = tf.constant([1, 2, 3])
x_1 = tf.reshape(x_1, shape=(1, 3))
x_2 = tf.constant([2, 3, 4])
x_2 = tf.reshape(x_2, shape=(1, 3))
x_3 = tf.constant([3, 4, 5])
x_3 = tf.reshape(x_3, shape=(1, 3))
x = tf.concat((x_1, x_2, x_3), axis=0)

x = tf.add(x, tf.constant(1, shape=x.shape))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    y = sess.run(x)
    print(y)


问:
why is it not possible to check a type as instance of `Null`
Why I cannot check whether a type is Null?

```<code>scala> val s:String = null
s: String = null

scala> s.isInstanceOf[Null]
<console>:13: error: type Null cannot be used in a type pattern or isInstanceOf test
       s.isInstanceOf[Null]

                 ^
</code>```

答:
A more correct way to check for equality with null, since you want to look for reference equality explicity.

```<code>x eq null
</code>```

Body:
Why I cannot check whether a type is Null?

scala> val s:String = null
s: String = null

scala> s.isInstanceOf[Null]
<console>:13: error: type Null cannot be used in a type pattern or isInstanceOf test
       s.isInstanceOf[Null]

                 ^

Body:
A more correct way to check for equality with null, since you want to look for reference equality explicity.

x eq null


问:
How to cross-reference tibbles in R?
```<code>library(nycflights13)
library(tidyverse)
</code>```

My task is

Look at each destination. Can you find flights that are suspiciously fast? (i.e. flights that represent a potential data entry error).

I have generated a tibble with the average flight times between every two airports:

```<code># A tibble: 224 x 3
# Groups:   origin [?]
   origin  dest mean_time
    <chr> <chr>     <dbl>
 1    EWR   ALB  31.78708
 2    EWR   ANC 413.12500
 3    EWR   ATL 111.99385
 4    EWR   AUS 211.24765
 5    EWR   AVL  89.79681
 6    EWR   BDL  25.46602
 7    EWR   BNA 114.50915
 8    EWR   BOS  40.31275
 9    EWR   BQN 196.17288
10    EWR   BTV  46.25734
# ... with 214 more rows
</code>```

Now I need to sweep through flights and extract all rows, whose air_time is outside say (mean_time/2, mean_time*2). How do I do that?

答:
Assuming you have stored the tibble with the average flight times, join it to the flights table:</p>

```<code>flights_suspicious <- left_join(flights, average_flight_times, by=c("origin","dest")) %>%
filter(air_time < mean_time / 2 | air_time > mean_time * 2)
</code>```

Title: How to cross-reference tibbles in R?

Body:
library(nycflights13)
library(tidyverse)

My task is

Look at each destination. Can you find flights that are suspiciously fast? (i.e. flights that represent a potential data entry error).

I have generated a tibble with the average flight times between every two airports:

# A tibble: 224 x 3
# Groups:   origin [?]
   origin  dest mean_time
    <chr> <chr>     <dbl>
 1    EWR   ALB  31.78708
 2    EWR   ANC 413.12500
 3    EWR   ATL 111.99385
 4    EWR   AUS 211.24765
 5    EWR   AVL  89.79681
 6    EWR   BDL  25.46602
 7    EWR   BNA 114.50915
 8    EWR   BOS  40.31275
 9    EWR   BQN 196.17288
10    EWR   BTV  46.25734
# ... with 214 more rows

Now I need to sweep through flights and extract all rows, whose air_time is outside say (mean_time/2, mean_time*2). How do I do that?

Body:
Assuming you have stored the tibble with the average flight times, join it to the flights table:

flights_suspicious <- left_join(flights, average_flight_times, by=c("origin","dest")) %>%
filter(air_time < mean_time / 2 | air_time > mean_time * 2)


问:
Scale image in React Native
Scale image like we do in HTML. img {height:100%; width:100%} in react native.

I have tried resizeMode?: enum('cover', 'contain', 'stretch', 'repeat', 'center') but none of them work in my case.

```<code><View style={{
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    flexDirection:'row'
  }}>
        <View style={{flex:1, backgroundColor:'yellow'}}>
        <Image
          style={{width: 50, height: 50}}
          resizeMode="stretch"
          source={{uri: 'http://aristotlebuzz.com/wp-content/uploads/2017/01/Facebook.png'}}
        />
        </View>
        <View style={{flex:1, backgroundColor:"red"}}>
           <Text>afdafda</Text>
        </View>

      </View>
</code>```

https://snack.expo.io/ByhjFQo1M

答:
You have to add the {height: 50} to the container for the image...

...and set the image size to {flex: 1}

...and spell stretch correctly.

So replace:

```<code><View style={{flex: 1, backgroundColor: 'yellow'}}>
  <Image
    style={{width: 50, height: 50}}
    resizeMode="strech"
    source={{uri: 'http://aristotlebuzz.com/wp-content/uploads/2017/01/Facebook.png'}}
   />
</code>```

With:

```<code><View style={{flex: 1, height: 50, backgroundColor: 'yellow'}}>
  <Image
    style={{flex: 1}}
    resizeMode="stretch"
    source={{uri: 'http://aristotlebuzz.com/wp-content/uploads/2017/01/Facebook.png'}}
   />
</View>
</code>```

Title: Scale image in React Native

Body:
Scale image like we do in HTML. img {height:100%; width:100%} in react native.

I have tried resizeMode?: enum('cover', 'contain', 'stretch', 'repeat', 'center') but none of them work in my case.

<View style={{
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    flexDirection:'row'
  }}>
        <View style={{flex:1, backgroundColor:'yellow'}}>
        <Image
          style={{width: 50, height: 50}}
          resizeMode="stretch"
          source={{uri: 'http://aristotlebuzz.com/wp-content/uploads/2017/01/Facebook.png'}}
        />
        </View>
        <View style={{flex:1, backgroundColor:"red"}}>
           <Text>afdafda</Text>
        </View>

      </View>

https://snack.expo.io/ByhjFQo1M

Body:
You have to add the {height: 50} to the container for the image...

...and set the image size to {flex: 1}

...and spell stretch correctly.

So replace:

<View style={{flex: 1, backgroundColor: 'yellow'}}>
  <Image
    style={{width: 50, height: 50}}
    resizeMode="strech"
    source={{uri: 'http://aristotlebuzz.com/wp-content/uploads/2017/01/Facebook.png'}}
   />

With:

<View style={{flex: 1, height: 50, backgroundColor: 'yellow'}}>
  <Image
    style={{flex: 1}}
    resizeMode="stretch"
    source={{uri: 'http://aristotlebuzz.com/wp-content/uploads/2017/01/Facebook.png'}}
   />
</View>


问:
Tunning up Activity with dialog theme
I need to launch a Dialog from home screen widget, so I created an Activity with android:theme="@android:style/Theme.Dialog"

The problem is, that I would like make it look like standard dialog window ( buttons on the gray background, font and text size, paddings etc), like here:

(source: android.com)

This is how my "dialog" Activity looks like:

Is there some standard way (theme?) to make it look like standard system dialogs? Or do I have to imitate it in my own layout?

答:
You can get the same look for the buttons below by using the weight attribute and the framework drawable for the background behind them.  Hope this helps!</p>

```<code>             <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:background="@android:drawable/bottom_bar"
               android:orientation="horizontal">
               <Button
                android:text="Cancel"
                android:textSize="12dip"
                android:id="@+id/cancelButton"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_margin="5dip"/>
               <Button
                android:text="Ok"
                android:textSize="12dip"
                android:id="@+id/okButton"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_margin="5dip"/>
           </LinearLayout>
</code>```

Title: Tunning up Activity with dialog theme

Body:
You can get the same look for the buttons below by using the weight attribute and the framework drawable for the background behind them.  Hope this helps!

             <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:background="@android:drawable/bottom_bar"
               android:orientation="horizontal">
               <Button
                android:text="Cancel"
                android:textSize="12dip"
                android:id="@+id/cancelButton"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_margin="5dip"/>
               <Button
                android:text="Ok"
                android:textSize="12dip"
                android:id="@+id/okButton"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_margin="5dip"/>
           </LinearLayout>


问:
Load local data files to Colaboratory
I just wondering that is it possible to load local data files(like .xlsx or .csv files that on my google drive) into Colaboratory?</p>

答:
I was a bit confused by the example for loading local files on first glance as there was no place to specify a file path. All you need to do is copy and paste the recipe to figure this out, but to be clear:

```<code>from google.colab import files
uploaded = files.upload()
</code>```

will open an upload dialogue window where you can browse and select your local files for upload.

Then

```<code>for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
</code>```

will show you the keys to access what you just uploaded.

Edit for additional clarification: The dictionary uploaded will have keys of the selected filenames - so if for example you select a file my_test.txt, then you would access that file using uploaded['my_test.txt'].

Title: Load local data files to Colaboratory

Body:
I was a bit confused by the example for loading local files on first glance as there was no place to specify a file path. All you need to do is copy and paste the recipe to figure this out, but to be clear:

from google.colab import files
uploaded = files.upload()

will open an upload dialogue window where you can browse and select your local files for upload.

Then

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

will show you the keys to access what you just uploaded.

Edit for additional clarification: The dictionary uploaded will have keys of the selected filenames - so if for example you select a file my_test.txt, then you would access that file using uploaded['my_test.txt'].


问:
issue with image_tag when using html in helper
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

```<code>def create_banner_html_helper(banner)

    if banner.logo.present?
      return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

<div class='m3-section m3-img_holder'>"
      image_tag banner.logo(:small)
      "</div>
    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe

    end

    return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe
  end
</code>```

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

答:
You'll have to concat and / or capture the elements, otherwise only the last section will be returned.

There's a good link to it here: https://thepugautomatic.com/2013/06/helpers/
Or the official docs here: https://apidock.com/rails/ActionView/Helpers/TextHelper/concat

There's a capture block used in the linked article that has the following code:

```<code>module MyHelper
  def widget
    capture do
      concat link_to("Hello", hello_path)
      concat " "
      concat link_to("Bye", goodbye_path)
    end
  end
end
</code>```

Stating:

You can get around this with the capture helper. That’s what
  content_tag uses internally: capture, true to its name, captures the
  content so it isn’t appended straight to the page. Instead, it’s built
  up as a separate string, for your custom helper to return (or have its
  way with)

I'd wrap your code like this - concatenating the string elements and the image tag, the return the entirety.

Edit: N.B. I think a quick + either side of the image_tag would solve this, and perhaps be a lot easier :)

Like this perhaps?

```<code>    if banner.logo.present?
      return "<div class='m3-news_wrap m3-mdcast-banner slide'>
                <a href='" + banner.link_url + "' target=_'blank'>
                  <div class='m3-article'>

                    <div class='m3-section m3-img_holder'>" +
                      image_tag(banner.logo(:small)) +
                    "</div>
                    <div class='m3-section m3-desc'>
                      <h3 class='m3-title'>" + banner.title + "</h3>
                      <p>" + banner.subtitle + "</p>
                      <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                    </div>
                 </div>
               </a>
             </div>".html_safe

    end
</code>```

(FYI I think you were missing a final closing div in there.)

Body:
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

def create_banner_html_helper(banner)

    if banner.logo.present?
      return "

"
      image_tag banner.logo(:small)
      "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe

    end

    return "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe
  end

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

Body:
You'll have to concat and / or capture the elements, otherwise only the last section will be returned.

There's a good link to it here: https://thepugautomatic.com/2013/06/helpers/
Or the official docs here: https://apidock.com/rails/ActionView/Helpers/TextHelper/concat

There's a capture block used in the linked article that has the following code:

module MyHelper
  def widget
    capture do
      concat link_to("Hello", hello_path)
      concat " "
      concat link_to("Bye", goodbye_path)
    end
  end
end

Stating:

You can get around this with the capture helper. That’s what
  content_tag uses internally: capture, true to its name, captures the
  content so it isn’t appended straight to the page. Instead, it’s built
  up as a separate string, for your custom helper to return (or have its
  way with)

I'd wrap your code like this - concatenating the string elements and the image tag, the return the entirety.

Edit: N.B. I think a quick + either side of the image_tag would solve this, and perhaps be a lot easier :)

Like this perhaps?

    if banner.logo.present?
      return "<div class='m3-news_wrap m3-mdcast-banner slide'>
                <a href='" + banner.link_url + "' target=_'blank'>
                  <div class='m3-article'>

                    <div class='m3-section m3-img_holder'>" +
                      image_tag(banner.logo(:small)) +
                    "</div>
                    <div class='m3-section m3-desc'>
                      <h3 class='m3-title'>" + banner.title + "</h3>
                      <p>" + banner.subtitle + "</p>
                      <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                    </div>
                 </div>
               </a>
             </div>".html_safe

    end

(FYI I think you were missing a final closing div in there.)


问:
Android Room Database - Unresolved reference @Entity and other annotations
I am using Android Room Persistence library (v.1.0.0-alpha1) in my app.
Although it is working fine, when I open model class (Kotlin Data class) in Android studio, it shows Unresolved reference for all annotations used for Room database like @Entity, @ColumnInfo etc. I tried changing version of arch library to 1.0.0-alpha5 but result was same.

In Lint inspection it is showing Remove deprecated symbol import for all imported annotations.AS was not showing this error previously.

How can I resolve this issue

Edit
Following are imports I have added in my build.gradle

```<code>compile "android.arch.persistence.room:runtime:1.0.0-alpha5"

compile "android.arch.persistence.room:rxjava2:1.0.0-alpha5"

annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha5"

kapt "android.arch.persistence.room:compiler:1.0.0-alpha5"
</code>```

答:
Here you have an example.

https://github.com/jsperk/PocRoom

Remember, you need add:

Gradle (Project)--> maven

Gradle (Module App) dependencies -->

```<code>implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
testImplementation "android.arch.persistence.room:testing:1.0.0"
implementation "android.arch.persistence.room:rxjava2:1.0.0"
</code>```

Body:
I am using Android Room Persistence library (v.1.0.0-alpha1) in my app.
Although it is working fine, when I open model class (Kotlin Data class) in Android studio, it shows Unresolved reference for all annotations used for Room database like @Entity, @ColumnInfo etc. I tried changing version of arch library to 1.0.0-alpha5 but result was same.

In Lint inspection it is showing Remove deprecated symbol import for all imported annotations.AS was not showing this error previously.

How can I resolve this issue

Edit
Following are imports I have added in my build.gradle

compile "android.arch.persistence.room:runtime:1.0.0-alpha5"

compile "android.arch.persistence.room:rxjava2:1.0.0-alpha5"

annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha5"

kapt "android.arch.persistence.room:compiler:1.0.0-alpha5"

Body:
Here you have an example.

https://github.com/jsperk/PocRoom

Remember, you need add:

Gradle (Project)--> maven

Gradle (Module App) dependencies -->

implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
testImplementation "android.arch.persistence.room:testing:1.0.0"
implementation "android.arch.persistence.room:rxjava2:1.0.0"


问:
I used *pointer+1 in my printf function and it didn't turn out what i thought it would be . why?
Here is the C code i recently ran and i got result that i didn't expect

Now the result i expected was "o" but what i got in the result was H and i want to know why?

My thoughts and what i knew :-

What i knew is that in a pointer the data stored is a number which points to the place we tends to point ..

for example:- if we declare a as
char *pointerthen The C will make some memory for pointer
and if we do  pointer = "GOKU"the C will make a separate memory of 5 bits for this string somewhere in the memory cells. Now let the memory cell in which Gis stored to be 50 so in the **pointer ** which let's say is stored in memory cell 100 will have the value 50. So now this pointer which is at poistion of 100th memory cell has a value of 50 which is pointing towards the 'G' character of GOKU..

And i thought if i increase the pointer by 1 then it will jump to memory location 51 where O will be stored but turns out that is not true . It turns out that when i increase the pointer by 1 something happens and it responds to H which falls right next to G in alphabetical order as well as in ASCII table . I ran several test but couldn't get E as output from the program . I knew i can use indexing as to get but i still want to know why this happened.

thanks

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

int main(){
char *pointer = "GOKU";

printf(" %c ", *pointer+1);
return EXIT_SUCCESS;
}
</code>```

答:
The pointer dereference operator * has higher precedence than the addition operator +.  So this:

```<code>*pointer+1
</code>```

Is the same as:

```<code>(*pointer)+1
</code>```

What you're doing is dereferencing pointer first, giving you the character 'G'.  You then add 1 to that value to give you 'H'.

If you want to add to the pointer, you need to add parenetheses:

```<code>*(pointer+1)
</code>```

This will increment the pointer by 1, then dereference the pointer to give you 'O'.

The above, by the way, is the same as:

```<code>pointer[1]
</code>```

Body:
Here is the C code i recently ran and i got result that i didn't expect

Now the result i expected was "o" but what i got in the result was H and i want to know why?

My thoughts and what i knew :-

What i knew is that in a pointer the data stored is a number which points to the place we tends to point ..

for example:- if we declare a as
char *pointerthen The C will make some memory for pointer
and if we do  pointer = "GOKU"the C will make a separate memory of 5 bits for this string somewhere in the memory cells. Now let the memory cell in which Gis stored to be 50 so in the **pointer ** which let's say is stored in memory cell 100 will have the value 50. So now this pointer which is at poistion of 100th memory cell has a value of 50 which is pointing towards the 'G' character of GOKU..

And i thought if i increase the pointer by 1 then it will jump to memory location 51 where O will be stored but turns out that is not true . It turns out that when i increase the pointer by 1 something happens and it responds to H which falls right next to G in alphabetical order as well as in ASCII table . I ran several test but couldn't get E as output from the program . I knew i can use indexing as to get but i still want to know why this happened.

thanks

#include <stdio.h>
#include <string.h>

int main(){
char *pointer = "GOKU";

printf(" %c ", *pointer+1);
return EXIT_SUCCESS;
}

Body:
The pointer dereference operator * has higher precedence than the addition operator +.  So this:

*pointer+1

Is the same as:

(*pointer)+1

What you're doing is dereferencing pointer first, giving you the character 'G'.  You then add 1 to that value to give you 'H'.

If you want to add to the pointer, you need to add parenetheses:

*(pointer+1)

This will increment the pointer by 1, then dereference the pointer to give you 'O'.

The above, by the way, is the same as:

pointer[1]


问:
Security advice: SSL and API access
My API (a desktop application) communicates with my web app using basic HTTP authentication over SSL (Basically I'm just using https instead of http in the requests). My API has implemented logic that makes sure that users don't send incorrect information, but the problem I have is that someone could bypass the API and use curl to potentially post incorrect data (obtaining credentials is trivial since signing up on my web app is free).

I have thought about the following options:

Duplicate the API's logic in the web app so that even if users try to cheat the system using curl or some other tool they are presented with the same conditions.

Implement a further authentication check to make sure only my API can communicate with my web app. (Perhaps SSL client certificates?).

Encrypt the data (Base 64?)

I know I'm being a little paranoid about users spoofing my web app with curl-like tools but I'd rather be safe than sorry. Duplicating the logic is really painful and I would rather not do that. I don't know much about SSL client certificates, can I use them in conjunction with basic HTTP authentication? Will they make my requests take longer to process? What other options do I have?

Thanks in advance.

答:
I would agree in general with sinelaw's comment that such validations are usually better on the server side to avoid exactly the kind of issue you're running into (supporting multiple client types).  That said, you may just not be in a position to move the logic, in which case you need to do something.

To me, your options are:

Client-side certificates, as you suggest -- you're basically authenticating that the client is who (or what, in your case) you expect it to be.  I have worked with these before and mutual authentication configuration can be confusing.  I would not worry about the performance, as I think the first step is getting the behavior your want (correctness first).  Anyway, in general, while this option is feasible, it can be exasperating to set up, depending on your web container.

Custom HTTP header in your desktop app, checking for its existence/value on the server side, or just leveraging of the existing User-Agent header.  Since you're encrypting the traffic, one should not be able to easily see the HTTP header you're sending, so you can set its name and value to whatever you want.  Checking for that on the server side is akin to assuring you that the client sending the request is almost certainly using your desktop app.

I would personally go the custom header route. It may not be 100% perfect, but if you're interested in doing the simplest possible thing to mitigate the most risk, it strikes me as the best route.  It's not a great option if you don't use HTTPS (because then anyone can see the header if they flip on a sniffer), but given that you do use HTTPS, it should work fine.

BTW, I think you may be confusing a few things -- HTTPS is going to give you encryption, but it doesn't necessarily involve (client) authentication.  Those are two different things, although they are often bundled together.  I'm assuming you're using HTTPS with authentication of the actual user (basic auth or whatever).

Title: Security advice: SSL and API access


问:
Is everything provided by TR1 now available in C++14 and easy to make use of?
We expect that converting old sources from using TR1, to not using it, will be straightforward work such as fixing #includes, changing a few names, and patching the build system, but cannot find a definitive statement that this is so for everything in TR1.

I know C++14 through language enhancements and a new standard library now provides many nice things that were in TR1. Even C++11 took over quite a lot from TR1.

But have all things in TR1 been made available as language and library features?   What in TR1 hasn't been eaten by C++14? (Things we don't use, we hope.)

As for TR1 features now in C++14, do any require more effort than simple name changes?

答:
C++ Technical Report 1 (TR1) is the common name for ISO/IEC TR 19768, C++ Library Extensions, which was a document proposing additions to the C++ standard library for the C++03 language standard. The additions include regular expressions, smart pointers, hash tables, and random number generators. TR1 was not a standard itself, but rather a draft document. However, most of its proposals became part of the later official standard, C++11. Before C++11 was standardized, vendors used this document as a guide to create extensions [1].

Generally, most of the features from TR1 passed to C++11, except some minor exceptions and some renamings in <random> header, shown below:

<random>

variate_generator didn't make it.

linear_congruential made it as linear_congruential_engine

mersenne_twister made it as mersenne_twister_engine

subtract_with_carry made it as subtract_with_carry_engine

subtract_with_carry_01 didn't make it.

discard_block made it as discard_block_engine

xor_combine didn't make it.

uniform_int made it as uniform_int_distribution

uniform_real made it as uniform_real_distribution

Also note that from the <type_traits> header in C++17 result_of was replaced with invoke_result.

[1]: C++ Technical Report 1


问:
Design issue while using ACF form in frontend
i have a different admin template where i want to use ACF form for custom post type.i am getting the result correctly but the problem is header and footer appearing twice and design are not appearing correctly like in wp-admin e:g 1 button are looking like label and datepicker not popup correctly.here i am sharing two screenshot to show how the design appearing different from actual design.

This is what i have tried

```<code><?php
acf_form_head();
get_header();
?>
<div id="primary">
    <div id="content" role="main">
        <?php
        acf_form( array(
            'post_id' => 90,
            'field_groups' => array( 43 ),
            'submit_value' => 'Submit',
        ) );
        ?>
    </div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
</code>```

答:
In the Documentation for ACF Form, the acf_form() function is called inside the loop. Maybe that is the issue for some reason? can you try:

```<code><?php
while ( have_posts() ) : the_post();
acf_form( array(
  'post_id' => 90,
  'field_groups' => array( 43 ),
  'submit_value' => 'Submit',
) );
endwhile;
?>
</code>```

See if that works...

Body:
i have a different admin template where i want to use ACF form for custom post type.i am getting the result correctly but the problem is header and footer appearing twice and design are not appearing correctly like in wp-admin e:g 1 button are looking like label and datepicker not popup correctly.here i am sharing two screenshot to show how the design appearing different from actual design.

This is what i have tried

<?php
acf_form_head();
get_header();
?>

        <?php
        acf_form( array(
            'post_id' => 90,
            'field_groups' => array( 43 ),
            'submit_value' => 'Submit',
        ) );
        ?>

<?php get_footer(); ?>

Body:
In the Documentation for ACF Form, the acf_form() function is called inside the loop. Maybe that is the issue for some reason? can you try:

<?php
while ( have_posts() ) : the_post();
acf_form( array(
  'post_id' => 90,
  'field_groups' => array( 43 ),
  'submit_value' => 'Submit',
) );
endwhile;
?>

See if that works...


问:
IndexError: list index out of range when trying to program an argument
I keep getting IndexError: list index out of range when using the below snippets in a python script:

```<code>rhost = sys.argv[1] #target ip
rport = int(sys.argv[2]) #target port
</code>```

I do not really see the issue with the above code.  Any assistance would be most appreciated!

答: It seems like sys.argv does not have 2 or more entries. If you call your script with commandline arguments the list has more than one entry. Do you do that? See this post for a very detailed description on how it works: sys.argv[1] meaning in script</p>

Body:
I keep getting IndexError: list index out of range when using the below snippets in a python script:

rhost = sys.argv[1] #target ip
rport = int(sys.argv[2]) #target port

I do not really see the issue with the above code.  Any assistance would be most appreciated!


问:
Change http port in wildfly maven plugin
I would like to change the default HTTP port using the wildfly-maven-plugin to 8380. Usually, I can do that changing the offset, but this is not working, my changes are ignored and HTTP port continues on 8080.

I'm starting wildfly in the same maven project, because this is way more practical (download and start automatically). Just like that:

```<code>mvn wildfly:run -Dwildfly.version=10.1.0.Final
</code>```

My project contains JAR, WAR and EAR. Classic structure.

As I understood from another SO questions, I need to put the plugin entry in each pom.xml that needs to be ignored, putting <skip>true</skip> in pom.xml of the: root, WAR and JAR. Just like that:

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>
</code>```

If I not skip this guys, the Wildfly try to deploy the JAR/WAR/Root, what is not my objective. I would like to deploy only the EAR.

To do that, I use the <skip>false</skip>  only for pom.xml of the EAR:

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>false</skip>
    </configuration>
</plugin>
</code>```

The localhost:8080/app/ works well after that.

But if I try to change the offset or http port, nothing different happens. This is some of the args that I already try on <configuration/> without success:

```<code><server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>

<jvmArgs>-Djboss.socket.binding.port-offset=300</jvmArgs>

<jvmArgs>-Djboss.http.port=8380</jvmArgs>
</code>```

The change that have some effect was:

```<code><serverConfig>standalone.xml</serverConfig>
<server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>
<filename>${project.build.finalName}.ear</filename>
</code>```

This also have changed the port (jvmArgs is deprecated):

```<code><javaOpts>-Djboss.socket.binding.port-offset=300</javaOpts>
</code>```

But in both cases the EAR application is not deployed...

Any idea? Thanks!

答:
Finally, I found the solution.

The jvmArgs is deprecated. I used javaOpts:

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>false</skip>
        <javaOpts>-Djboss.http.port=8380</javaOpts>
        <filename>${project.build.finalName}.ear</filename>
    </configuration>
</plugin>
</code>```

Works!

You can use too:

```<code><javaOpts>
    <javaOpt>-agentlib:jdwp=transport=dt_socket,address=9087,server=y,suspend=n</javaOpt>
    <javaOpt>-Djboss.http.port=8380</javaOpt>
</javaOpts>
</code>```

To use more than one option for the JVM. In this example above I'm showing how to include a parameter to debug the Wildfly using the maven plugin.

But it's still a mistery why the EAR is not deployed when I use the offset configuration.

Body:
I would like to change the default HTTP port using the wildfly-maven-plugin to 8380. Usually, I can do that changing the offset, but this is not working, my changes are ignored and HTTP port continues on 8080.

I'm starting wildfly in the same maven project, because this is way more practical (download and start automatically). Just like that:

mvn wildfly:run -Dwildfly.version=10.1.0.Final

My project contains JAR, WAR and EAR. Classic structure.

As I understood from another SO questions, I need to put the plugin entry in each pom.xml that needs to be ignored, putting <skip>true</skip> in pom.xml of the: root, WAR and JAR. Just like that:

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>

If I not skip this guys, the Wildfly try to deploy the JAR/WAR/Root, what is not my objective. I would like to deploy only the EAR.

To do that, I use the <skip>false</skip>  only for pom.xml of the EAR:

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>false</skip>
    </configuration>
</plugin>

The localhost:8080/app/ works well after that.

But if I try to change the offset or http port, nothing different happens. This is some of the args that I already try on <configuration/> without success:

<server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>

<jvmArgs>-Djboss.socket.binding.port-offset=300</jvmArgs>

<jvmArgs>-Djboss.http.port=8380</jvmArgs>

The change that have some effect was:

<serverConfig>standalone.xml</serverConfig>
<server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>
<filename>${project.build.finalName}.ear</filename>

This also have changed the port (jvmArgs is deprecated):

<javaOpts>-Djboss.socket.binding.port-offset=300</javaOpts>

But in both cases the EAR application is not deployed...

Any idea? Thanks!

Body:
Finally, I found the solution.

The jvmArgs is deprecated. I used javaOpts:

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>false</skip>
        <javaOpts>-Djboss.http.port=8380</javaOpts>
        <filename>${project.build.finalName}.ear</filename>
    </configuration>
</plugin>

Works!

You can use too:

<javaOpts>
    <javaOpt>-agentlib:jdwp=transport=dt_socket,address=9087,server=y,suspend=n</javaOpt>
    <javaOpt>-Djboss.http.port=8380</javaOpt>
</javaOpts>

To use more than one option for the JVM. In this example above I'm showing how to include a parameter to debug the Wildfly using the maven plugin.

But it's still a mistery why the EAR is not deployed when I use the offset configuration.


问:
Making a string concatenation operator in R
I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

The easiest way would be to create a special operator using %, like

```<code>`%+%` <- function(a, b) paste(a, b, sep="")
</code>```

but this leads to lots of ugly %'s in the code.

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?

答:
If R would thoroghlly comply with S4, the following would have been enough:

```<code>setMethod("+",
          signature(e1 = "character", e2 = "character"),
          function (e1, e2) {
              paste(e1, e2, sep = "")
      })
</code>```

But this gives an error that the method is sealed :((. Hopefully this will change in the feature versions of R.

The best you can do is to define new class "string" which would behave exactly as "character" class:

```<code>setClass("string", contains="character")
string <- function(obj) new("string", as.character(obj))
</code>```

and define the most general method which R allows:

```<code>setMethod("+", signature(e1 = "character", e2 = "ANY"),
          function (e1, e2) string(paste(e1, as.character(e2), sep = "")))
</code>```

now try:

```<code>tt <- string(44444)

tt
#An object of class "string"
#[1] "44444"
tt + 3434
#[1] "444443434"
"sfds" + tt
#[1] "sfds44444"
tt +  tt
#[1] "4444444444"
343 + tt
#Error in 343 + tt : non-numeric argument to binary operator
"sdfs" + tt + "dfsd"
#An object of class "string"
#[1] "sdfs44444dfsd"
</code>```

Body:
I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

The easiest way would be to create a special operator using %, like

`%+%` <- function(a, b) paste(a, b, sep="")

but this leads to lots of ugly %'s in the code.

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?

Body:
If R would thoroghlly comply with S4, the following would have been enough:

setMethod("+",
          signature(e1 = "character", e2 = "character"),
          function (e1, e2) {
              paste(e1, e2, sep = "")
      })

But this gives an error that the method is sealed :((. Hopefully this will change in the feature versions of R.

The best you can do is to define new class "string" which would behave exactly as "character" class:

setClass("string", contains="character")
string <- function(obj) new("string", as.character(obj))

and define the most general method which R allows:

setMethod("+", signature(e1 = "character", e2 = "ANY"),
          function (e1, e2) string(paste(e1, as.character(e2), sep = "")))

now try:

tt <- string(44444)

tt
#An object of class "string"
#[1] "44444"
tt + 3434
#[1] "444443434"
"sfds" + tt
#[1] "sfds44444"
tt +  tt
#[1] "4444444444"
343 + tt
#Error in 343 + tt : non-numeric argument to binary operator
"sdfs" + tt + "dfsd"
#An object of class "string"
#[1] "sdfs44444dfsd"


问:
Pass html defined in parent to child
I am trying to define some html in my parent component that can be passed to the child component. Is this possible? I have tried a couple of things like this: How to pass an expression to a component as an input in Angular2?, but I did not have any luck. Maybe my syntax was wrong. I was a little confused with the let.  Appreciate all the help and any explanations to help me understand this better.

```<code>@Component({
    selector: 'app-my-parent',
    template: `
    <div>other parent html</div>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.first</ng-template>
    </app-my-child>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.second</ng-template>
    </app-my-child>
    `
})
export class MyParent {
}
</code>```

```<code>@Component({
    selector: 'app-my-child',
    template: `
    <div>other child html</div>
    how do I access the template from here? Is there a way to do binding with templates?

})
export class MyChild {
      @Input() property;
}
</code>```

答:
You need to add an ng-content tag to your child component so angular knows it's supposed to transclude content and where to put the content:

```<code>@Component({
    selector: 'app-my-child',
    template: `
    <div>other child html</div>
    <ng-content></ng-content>
    `
})
export class MyChild {
}
</code>```

then you need to remove the ng-template tags, because that tells angular to actually not render these things at all, because they're templates meant to be used elsewhere

Using it in the parent is super simple:

```<code><app-my-child>Anything put between these component tags will be transcluded to the ng-content tag</app-my-child>
</code>```

Title: Pass html defined in parent to child

Body:
I am trying to define some html in my parent component that can be passed to the child component. Is this possible? I have tried a couple of things like this: How to pass an expression to a component as an input in Angular2?, but I did not have any luck. Maybe my syntax was wrong. I was a little confused with the let.  Appreciate all the help and any explanations to help me understand this better.

@Component({
    selector: 'app-my-parent',
    template: `

other parent html

    <app-my-child [property]="value">
        <ng-template #someTemplate">value.first</ng-template>
    </app-my-child>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.second</ng-template>
    </app-my-child>
    `
})
export class MyParent {
}

@Component({
    selector: 'app-my-child',
    template: `

other child html

    how do I access the template from here? Is there a way to do binding with templates?

})
export class MyChild {
      @Input() property;
}

Body:
You need to add an ng-content tag to your child component so angular knows it's supposed to transclude content and where to put the content:

@Component({
    selector: 'app-my-child',
    template: `
    <div>other child html</div>
    <ng-content></ng-content>
    `
})
export class MyChild {
}

then you need to remove the ng-template tags, because that tells angular to actually not render these things at all, because they're templates meant to be used elsewhere

Using it in the parent is super simple:

<app-my-child>Anything put between these component tags will be transcluded to the ng-content tag</app-my-child>


问:
URL Forwarding based on request parameters
I am using UrlRewriteFilter from http://www.tuckey.org/urlrewrite/. Mainly I am trying to get the following URL
http://domain/application/?param=value to redirect to
http://domain/application/?another_param=another_value (simply replacing the request param).

Below are my rule configuration that dosen't seem to work

```<code>    <rule>
    <from>^(.*?param=value)$</from>
    <to type="forward">%{context-path}?another_param=another value</to>
</rule>
</code>```

I have tried several other variations but that didn't seem to work either. any light shed on this issue would be much appreciated

答:
I have been able to resolve the issue using the rule below

```<code> <rule>
    <name>Selective redirect example redirect</name>
    <condition type="parameter" name="param" operator="equal">value</condition>
    <to type="forward">?another_param=another_value</to>
</rule>
</code>```

The key to the answer here is using the conditions rather than depending on the rule to capture the request, in my case I needed only to apply the rule when a certain param value is met. The second part of the answer is removing the <from> tag, and hence all the requests that fulfill the condition will be redirected to the same source page.

Finally, below are the links that were most useful in my search for the answer:

URLRewriteFilter Examples page

The Developer's Tidbits: Tuckey URLRewrite How-To

StackOverflow post: URL Rewrite Filter not working with query parameters containing special characters

Body:
I am using UrlRewriteFilter from http://www.tuckey.org/urlrewrite/. Mainly I am trying to get the following URL
http://domain/application/?param=value to redirect to
http://domain/application/?another_param=another_value (simply replacing the request param).

Below are my rule configuration that dosen't seem to work

    <rule>
    <from>^(.*?param=value)$</from>
    <to type="forward">%{context-path}?another_param=another value</to>
</rule>

I have tried several other variations but that didn't seem to work either. any light shed on this issue would be much appreciated

Body:
I have been able to resolve the issue using the rule below

 <rule>
    <name>Selective redirect example redirect</name>
    <condition type="parameter" name="param" operator="equal">value</condition>
    <to type="forward">?another_param=another_value</to>
</rule>

The key to the answer here is using the conditions rather than depending on the rule to capture the request, in my case I needed only to apply the rule when a certain param value is met. The second part of the answer is removing the <from> tag, and hence all the requests that fulfill the condition will be redirected to the same source page.

Finally, below are the links that were most useful in my search for the answer:

URLRewriteFilter Examples page

The Developer's Tidbits: Tuckey URLRewrite How-To

StackOverflow post: URL Rewrite Filter not working with query parameters containing special characters