问:
Slicing columns in Python
I am new in Python. I want to slice columns from index 1 to end of a marix and perform some operations on the those sliced out columns. Following is the code:

```<code>import numpy as np
import pandas as pd

train_df = pd.read_csv('train_475_60_W1.csv',header = None)
train = train_df.as_matrix()
y = train[:,0]
X = train[:,1:-1]
</code>```

The problem is if I execeute "train.shape", it gives me (89512, 61). But when I execute "X.shape", it give me (89512, 59). I was expecting to get 60 as I want to execute operations on all the colunms except the first one. Can anyone please help me in solving this?

答:
The thing you should know with slicing for single dimension even in normal lists is that it looks like this:

```<code>[start : end]
</code>```

with start included and end excluded.

you can also use these:

```<code>[:x] # from the start to x
[x:] # from x to the end
</code>```

you can then generalize than to 2D or more, so in your case it would be:

```<code>X = train[:,1:] # the first : to get all rows, and 1: to get all columns except the first
</code>```

you can learn more about these in here if you want, it's a good way to practice

Title: Slicing columns in Python

Body:
I am new in Python. I want to slice columns from index 1 to end of a marix and perform some operations on the those sliced out columns. Following is the code:

import numpy as np
import pandas as pd

train_df = pd.read_csv('train_475_60_W1.csv',header = None)
train = train_df.as_matrix()
y = train[:,0]
X = train[:,1:-1]

The problem is if I execeute "train.shape", it gives me (89512, 61). But when I execute "X.shape", it give me (89512, 59). I was expecting to get 60 as I want to execute operations on all the colunms except the first one. Can anyone please help me in solving this?

Body:
The thing you should know with slicing for single dimension even in normal lists is that it looks like this:

[start : end]

with start included and end excluded.

you can also use these:

[:x] # from the start to x
[x:] # from x to the end

you can then generalize than to 2D or more, so in your case it would be:

X = train[:,1:] # the first : to get all rows, and 1: to get all columns except the first

you can learn more about these in here if you want, it's a good way to practice


来源: stackexchange

问:
AFNetworking 3.0 Error: “Request failed: internal server error (500)”
I am using Afnetwork 3. I am a new one for IOS development. I want to connect some API using POST method.

```<code>+(void)postExecuteWithParams:(NSString *)first  secondParm:(NSDictionary *)inParams onCompletion:(JSONResponseBlock)completionBlock {

NSString *baseURL = @"xyz";

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:first parameters:inParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSLog(@"JSON: %@", responseObject);
     completionBlock(responseObject);

     //here is place for code executed in success case

 } failure:^(NSURLSessionDataTask *task, NSError *error) {

     NSLog(@"Error: %@", [error localizedDescription]);
 }];

}
</code>```

When I use this code I am getting the error like this

Error: Request failed: internal server error (500)

can i know what is the reason for this error and how can i modify it?

答:
Use

```<code>  manager.securityPolicy.allowInvalidCertificates = YES;
  manager.securityPolicy.validatesDomainName = NO;
</code>```

May be your server has not been published. So, with this you will not able to recieve internal server error.

ContentLicense: CC BY-SA 3.0

Body:
I am using Afnetwork 3. I am a new one for IOS development. I want to connect some API using POST method.

+(void)postExecuteWithParams:(NSString *)first  secondParm:(NSDictionary *)inParams onCompletion:(JSONResponseBlock)completionBlock {

NSString *baseURL = @"xyz";

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:first parameters:inParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSLog(@"JSON: %@", responseObject);
     completionBlock(responseObject);

     //here is place for code executed in success case

 } failure:^(NSURLSessionDataTask *task, NSError *error) {

     NSLog(@"Error: %@", [error localizedDescription]);
 }];

}

When I use this code I am getting the error like this

Error: Request failed: internal server error (500)

can i know what is the reason for this error and how can i modify it?

Body:
Use

  manager.securityPolicy.allowInvalidCertificates = YES;
  manager.securityPolicy.validatesDomainName = NO;

May be your server has not been published. So, with this you will not able to recieve internal server error.


问:
How to detect IE11 close event
I am now trying to detect only the event of the browser close button of IE11 in JavaScript.

I was able to detect the browser close button with the onbeforeunload event, but I also have trouble picking up other page transition events.

This code is I trying on it.

```<code>window.onbeforeunload = function(event) {
    alert('Sure you want to close ?');
}
</code>```

Is there any good way to do it ?

答:
Actually the onbeforeunload Event will be fired when you close the browser/tab , refresh the page(or F5), submit a form, or jump to other pages..etc
AFAIK, there is not a perfect way to detect which operation exactly USER do.But for your question, i guess there are some html tag like

To ABC

that fired the onbeforeunload Event when they are clicked. If it is true, may be you can remove the Event when the HREF was active so that the Event would not be fired.
Try codes blow:

```<code><script type="text/javascript">
  $(function() {
      $("a").click(function() {
        window.onbeforeunload = null;
        location.href = $(this).attr("href");
        return false;
      });
  });
  window.onbeforeunload = function(e) {
     return 'Sure you want to close ?';
  }
</script>
</code>```

Note that this would not prevent the refresh opreation to fired the onbeforeunload Event, but i hope to provide some ideas for resolving your problem.

Title: How to detect IE11 close event

Body:
I am now trying to detect only the event of the browser close button of IE11 in JavaScript.

I was able to detect the browser close button with the onbeforeunload event, but I also have trouble picking up other page transition events.

This code is I trying on it.

window.onbeforeunload = function(event) {
    alert('Sure you want to close ?');
}

Is there any good way to do it ?

Body:
Actually the onbeforeunload Event will be fired when you close the browser/tab , refresh the page(or F5), submit a form, or jump to other pages..etc
AFAIK, there is not a perfect way to detect which operation exactly USER do.But for your question, i guess there are some html tag like

<a href="abc.com">To ABC</a>

that fired the onbeforeunload Event when they are clicked. If it is true, may be you can remove the Event when the HREF was active so that the Event would not be fired.
Try codes blow:

<script type="text/javascript">
  $(function() {
      $("a").click(function() {
        window.onbeforeunload = null;
        location.href = $(this).attr("href");
        return false;
      });
  });
  window.onbeforeunload = function(e) {
     return 'Sure you want to close ?';
  }
</script>

Note that this would not prevent the refresh opreation to fired the onbeforeunload Event, but i hope to provide some ideas for resolving your problem.


问:
Ending a code with a designated value
How would I make it to where I wanted my code to loop if any character besides n or N was entered? So if the user inputs a, t, w, g, etc., it would return back to the beginning of the current loop. I'm usin an if/else if loop. (Just messing around with NetBeans).

```<code>import java.util.Scanner;

public class InvoiceApp
{
    public static void main(String[] args)
    {
        // welcome the user to the program
        System.out.println("Welcome to the Invoice Total Calculator");
        System.out.println();  // print a blank line

        // create a Scanner object named sc
        Scanner sc = new Scanner(System.in);

        // perform invoice calculations until choice isn't equal to "y" or "Y"
        String choice = "y";
        if (choice.equalsIgnoreCase("y"))
        {
            // get the invoice subtotal from the user
            System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // calculate the discount amount and total
            double discountPercent= 0.0;
            if (subtotal >= 200)
            discountPercent = .2;
            else if (subtotal >= 100)
            discountPercent = .1;
            else
            discountPercent = 0.0;

            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // display the discount amount and total
            String message = "Discount percent: " + discountPercent + "\n"
                           + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";
            System.out.println(message);

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
        }
            else if (choice.equalsIgnoreCase("n"));
        }
    }
}
</code>```

答: Use a while(!(choice.equalsIgnoreCase("n"))) instead of your current if statement. You won't need an else section.

Title: Ending a code with a designated value

Body:
How would I make it to where I wanted my code to loop if any character besides n or N was entered? So if the user inputs a, t, w, g, etc., it would return back to the beginning of the current loop. I'm usin an if/else if loop. (Just messing around with NetBeans).

import java.util.Scanner;

public class InvoiceApp
{
    public static void main(String[] args)
    {
        // welcome the user to the program
        System.out.println("Welcome to the Invoice Total Calculator");
        System.out.println();  // print a blank line

        // create a Scanner object named sc
        Scanner sc = new Scanner(System.in);

        // perform invoice calculations until choice isn't equal to "y" or "Y"
        String choice = "y";
        if (choice.equalsIgnoreCase("y"))
        {
            // get the invoice subtotal from the user
            System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // calculate the discount amount and total
            double discountPercent= 0.0;
            if (subtotal >= 200)
            discountPercent = .2;
            else if (subtotal >= 100)
            discountPercent = .1;
            else
            discountPercent = 0.0;

            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // display the discount amount and total
            String message = "Discount percent: " + discountPercent + "\n"
                           + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";
            System.out.println(message);

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
        }
            else if (choice.equalsIgnoreCase("n"));
        }
    }
}


问:
Item position in list
I have this dictionary:

```<code>db= {'www.baurom.ro':
                     {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     },
    'slbz2':
            {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }
</code>```

And a list:

```<code>lista=['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']
</code>```

What am i doing now is this:

```<code>for x in lista:
     if x in db:
        db[x][0][lista.index(x)]+=1
</code>```

In other words i want to count how many times each site appears in the list and on which position. This works but in the given example it will return something like:

```<code>{0: [7, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

while i would want it to be:

```<code>{0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
</code>```

How can i achieve this? I can use a variable, initiate it with var=0 and then +=1 and use it as an artificial index but is there a more "pythonic" way of doing it?

答:
You could do something like this:

```<code>for entry in db:
    db[entry][0] = [int(x == entry) for x in lista]
print(db)  # {'slbz2': {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}, 'www.baurom.ro': {0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}}
</code>```

You essentially replace your dictionary values with a list-comprehension that compares the dictionary entry to the lista entry. If the result of the comparison is True you convert that boolean value to an integer (True -> 1, False -> 0).

If the items in lista are very limited in comparison to the dictionary keys you can do this instead:

```<code>for entry in set(x for x in lista if x in db):
    # rest stays the same
</code>```

This way, you loop and edit only those keys in your dictionary that appear in your lista. Also notice that you loop over a set constructed from the elements of lista to ignore its duplicates ('www.baurom.ro' key is edited once, not as many times as it appears on lista).

Title: Item position in list

Body:
I have this dictionary:

db= {'www.baurom.ro':
                     {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     },
    'slbz2':
            {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }

And a list:

lista=['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']

What am i doing now is this:

for x in lista:
     if x in db:
        db[x][0][lista.index(x)]+=1

In other words i want to count how many times each site appears in the list and on which position. This works but in the given example it will return something like:

{0: [7, 0, 0, 0, 0, 0, 0, 0, 0, 0]

while i would want it to be:

{0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]

How can i achieve this? I can use a variable, initiate it with var=0 and then +=1 and use it as an artificial index but is there a more "pythonic" way of doing it?

Body:
You could do something like this:

for entry in db:
    db[entry][0] = [int(x == entry) for x in lista]
print(db)  # {'slbz2': {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}, 'www.baurom.ro': {0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}}

You essentially replace your dictionary values with a list-comprehension that compares the dictionary entry to the lista entry. If the result of the comparison is True you convert that boolean value to an integer (True -> 1, False -> 0).

If the items in lista are very limited in comparison to the dictionary keys you can do this instead:

for entry in set(x for x in lista if x in db):
    # rest stays the same

This way, you loop and edit only those keys in your dictionary that appear in your lista. Also notice that you loop over a set constructed from the elements of lista to ignore its duplicates ('www.baurom.ro' key is edited once, not as many times as it appears on lista).


问:
TestCafe issue, onChange event not triggred for input box in a modal dialog box
I am trying to update a number on the screen. I click on the update menu that lets me update a number. When I click on the update button it will open a modal dialog box with an empty text box for the new number and a save button. The save button is initially disabled. If the user manually types in a number in the text box, the onChange event will trigger and the save button is enabled. However, if I let the testcafe script to put a number in the number text box, the save button remains disabled. My guess is that when I use the testcafe .typeText(inputbox,'123') it does not fire the onChange event on the text box. Any help on this is greatly appreciated.

答:
TestCafe have fixed the problem with the onChange event for react-dom since the 15.6.0 version. Please try to use TestCafe 0.16.2.
If the problem persists, please provide your page's URL.


问:
Set empty array as default value in array_agg in postgresql
I have a view:

```<code>CREATE OR REPLACE VIEW microservice_view AS
  SELECT
    m.id :: BIGINT,
    m.name,
    m.sending_message_rate :: BIGINT,
    m.max_message_size :: BIGINT,
    m.prefetch_count :: BIGINT,
    (SELECT COALESCE(json_agg(DISTINCT node_id), '[]')
     FROM public.microservice_node
     WHERE microservice_id = m.id) AS nodes,

    (SELECT array_agg(DISTINCT json_build_object('id', transport_id :: INT,
                                                 'is_available', (credentials ->> 'is_available') :: BOOLEAN,
                                                 'username', credentials ->> 'username',
                                                 'password', credentials ->> 'password',
                                                 'default', (default_transport) :: BOOLEAN) :: JSONB
    )
     FROM transport_microservice
     WHERE microservice_id = m.id) AS transports
  FROM public.microservice m
  GROUP BY m.id
  ORDER BY m.id ASC;
</code>```

Sometimes transports is null. How can I set an empty array as a default value for array_agg? This field should be an empty array or array with data. In some cases I use array_length function to filter the data.

答:
First of all, I wouldn't mix array_agg with JSON (notice double quotes escaping; also I use select array( .. subquery ..) trick here to get an array, it's at some extent an equivalent to your array_agg(..)):

```<code>test=# select array(select '{"zz": 1}'::jsonb);
      array
-----------------
 {"{\"zz\": 1}"}
</code>```

-- here you'll get ARRAY of JSONB, while what you really need is single JSONB value with an embedded array inside:

```<code>test=# select pg_typeof(array(select '{"zz": 1}'::jsonb));
 pg_typeof
-----------
 jsonb[]
(1 row)

test=# select pg_typeof('[{"zz": 1}]'::jsonb);
 pg_typeof
-----------
 jsonb
(1 row)
</code>```

To get single jsonb value (with JSON array inside), use jsonb_agg(..) function.

To substitute NULL value by some default, as usual, you can use standard function coalesce(..):

```<code>test=# select coalesce(null::jsonb, '[]'::jsonb);
 coalesce
----------
 []
(1 row)
</code>```

Finally, as I see from additional comments, you need to get array length of your jsonb -- there are functions json_array_length(..) and jsonb_array_length(..) designed for this purpose, see https://www.postgresql.org/docs/current/static/functions-json.html.

Body:
I have a view:

CREATE OR REPLACE VIEW microservice_view AS
  SELECT
    m.id :: BIGINT,
    m.name,
    m.sending_message_rate :: BIGINT,
    m.max_message_size :: BIGINT,
    m.prefetch_count :: BIGINT,
    (SELECT COALESCE(json_agg(DISTINCT node_id), '[]')
     FROM public.microservice_node
     WHERE microservice_id = m.id) AS nodes,

    (SELECT array_agg(DISTINCT json_build_object('id', transport_id :: INT,
                                                 'is_available', (credentials ->> 'is_available') :: BOOLEAN,
                                                 'username', credentials ->> 'username',
                                                 'password', credentials ->> 'password',
                                                 'default', (default_transport) :: BOOLEAN) :: JSONB
    )
     FROM transport_microservice
     WHERE microservice_id = m.id) AS transports
  FROM public.microservice m
  GROUP BY m.id
  ORDER BY m.id ASC;

Sometimes transports is null. How can I set an empty array as a default value for array_agg? This field should be an empty array or array with data. In some cases I use array_length function to filter the data.

Body:
First of all, I wouldn't mix array_agg with JSON (notice double quotes escaping; also I use select array( .. subquery ..) trick here to get an array, it's at some extent an equivalent to your array_agg(..)):

test=# select array(select '{"zz": 1}'::jsonb);
      array
-----------------
 {"{\"zz\": 1}"}

-- here you'll get ARRAY of JSONB, while what you really need is single JSONB value with an embedded array inside:

test=# select pg_typeof(array(select '{"zz": 1}'::jsonb));
 pg_typeof
-----------
 jsonb[]
(1 row)

test=# select pg_typeof('[{"zz": 1}]'::jsonb);
 pg_typeof
-----------
 jsonb
(1 row)

To get single jsonb value (with JSON array inside), use jsonb_agg(..) function.

To substitute NULL value by some default, as usual, you can use standard function coalesce(..):

test=# select coalesce(null::jsonb, '[]'::jsonb);
 coalesce
----------
 []
(1 row)

Finally, as I see from additional comments, you need to get array length of your jsonb -- there are functions json_array_length(..) and jsonb_array_length(..) designed for this purpose, see https://www.postgresql.org/docs/current/static/functions-json.html.


问:
How to correctly swap some characters in string
I have a string that represents a date:

```<code>"12.27.1995"
</code>```

I need to swap the month and the day to get:

```<code>"27.12.1995"
</code>```

I did:

```<code>date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]
</code>```

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

Body:
I have a string that represents a date:

"12.27.1995"

I need to swap the month and the day to get:

"27.12.1995"

I did:

date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

Body:
Not elegant, but a way using regex captures:

/(\d{1,2})\.(\d{1,2})\.(\d{4})/.match "12.27.1995"
[$2, $1, $3].join('.') #=> "27.12.1995"


问:
update values of only certain rows in dataset1, with values from dataset2 in R - but only the ones that don't match, or else keep the original?
So, I have two dataframes, original and the one made from extracted rows of the original and then changed values in one of the columns.

They both have same no. of columns (10), but the original is bigger than the second one. Type of data is the same in both, and I need to replace values in one column which is made of factors. I've tried left_join and merge but I run into errors, which is probably my mistake, but I don't know what I'm doing wrong as I still don't understand R properly.

eg. dataframe 1:

ALB  Med

SKJ  Eq

ALB  Gyre

BUM  Eq

WHM  Trans

YFT  Eq

dataframe 2:

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

hat I want to get:

ALB  Med

SKJ  Eq

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

Excerpt of original data from R (dataset1):

```<code>    > print(catchesbyPPOW[1:10,])
   Species  Long   Lat tCatch_sqrt        ECOREGION                   REALM          PROVINC TYPE
1      ALB  17.5 -57.5   0.5099020             <NA>     Southern Cold Water        Antarctic PPOW
2      YFT  17.5 -57.5   0.2812472             <NA>     Southern Cold Water        Antarctic PPOW
3      BFT -67.5 -52.5   2.9238673 Patagonian Shelf Temperate South America       Magellanic MEOW
4      BFT -62.5 -52.5   3.2256782             <NA>     Atlantic Warm Water Malvinas Current PPOW
5      ALB -52.5 -52.5   0.2323575             <NA>     Southern Cold Water     Subantarctic PPOW
6      SWO -52.5 -52.5   0.9996549             <NA>     Southern Cold Water     Subantarctic PPOW
7      ALB -32.5 -52.5   0.4097926             <NA>     Southern Cold Water        Antarctic PPOW
8      BET -32.5 -52.5   1.4336387             <NA>     Southern Cold Water        Antarctic PPOW
9      SWO -32.5 -52.5   1.2541730             <NA>     Southern Cold Water        Antarctic PPOW
10     YFT -32.5 -52.5   1.2215236             <NA>     Southern Cold Water        Antarctic PPOW
                BIOME optional
1               Polar     TRUE
2               Polar     TRUE
3                <NA>     TRUE
4  Boundary - western     TRUE
5               Polar     TRUE
6               Polar     TRUE
7               Polar     TRUE
8               Polar     TRUE
9               Polar     TRUE
10              Polar     TRUE
</code>```

Dataset 2:

```<code>> print(outliers[1:10,])
    Species  Long   Lat tCatch_sqrt                  ECOREGION                   REALM TYPE BIOME optional
3       BFT -67.5 -52.5   2.9238673           Patagonian Shelf Temperate South America MEOW  <NA>     TRUE
39      SWO -62.5 -42.5   0.6316645     North Patagonian Gulfs Temperate South America MEOW  <NA>     TRUE
130     ALB -57.5 -37.5   7.6342489 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
131     BET -57.5 -37.5   0.8367258 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
132     BUM -57.5 -37.5   0.5127475 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
133     SAI -57.5 -37.5   1.3915028 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
134     SKJ -57.5 -37.5   1.2453915 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
135     SWO -57.5 -37.5   2.4453357 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
136     WHM -57.5 -37.5   0.2320991 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
137     YFT -57.5 -37.5   2.2360680 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
             PROVINC
3   Malvinas Current
39  Malvinas Current
130 Malvinas Current
131 Malvinas Current
132 Malvinas Current
133 Malvinas Current
134 Malvinas Current
135 Malvinas Current
136 Malvinas Current
137 Malvinas Current
</code>```

I deleted my failed attempts, I just have the latest one I tried with left_join:

```<code>PPOWoutliers<-left_join(catchesbyPPOW, outliers, by = NULL)
</code>```

Which gave me this warning:

```<code>Joining, by = c("Species", "Long", "Lat", "tCatch_sqrt", "ECOREGION", "REALM", "PROVINC", "TYPE", "BIOME", "optional")
Warning message:
In left_join_impl(x, y, by$x, by$y, suffix$x, suffix$y) :
  joining factors with different levels, coercing to character vector
</code>```

答:
Thank you very much for help!
I found a way, in the end.
I did a left_join of the datasets with the variable I wanted to change with a different name in dataset2. Then I did a for loop to replace all the resulting NA's with values from the original column, and it worked.</p>

```<code>library(dplyr)

PPOWoutliers <-left_join(catchesbyPPOW, outliers, by = NULL)
summary(PPOWoutliers)

for (i in 1:2448){
   if (is.na(PPOWoutliers[i,11])==TRUE){
     PPOWoutliers[i,12] <- as.character(PPOWoutliers[i,7])}
  else{
    PPOWoutliers[i,12] <- as.character(PPOWoutliers[i,11])}
  }
</code>```

Body:
So, I have two dataframes, original and the one made from extracted rows of the original and then changed values in one of the columns.

They both have same no. of columns (10), but the original is bigger than the second one. Type of data is the same in both, and I need to replace values in one column which is made of factors. I've tried left_join and merge but I run into errors, which is probably my mistake, but I don't know what I'm doing wrong as I still don't understand R properly.

eg. dataframe 1:

ALB  Med

SKJ  Eq

ALB  Gyre

BUM  Eq

WHM  Trans

YFT  Eq

dataframe 2:

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

hat I want to get:

ALB  Med

SKJ  Eq

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

Excerpt of original data from R (dataset1):

    > print(catchesbyPPOW[1:10,])
   Species  Long   Lat tCatch_sqrt        ECOREGION                   REALM          PROVINC TYPE
1      ALB  17.5 -57.5   0.5099020             <NA>     Southern Cold Water        Antarctic PPOW
2      YFT  17.5 -57.5   0.2812472             <NA>     Southern Cold Water        Antarctic PPOW
3      BFT -67.5 -52.5   2.9238673 Patagonian Shelf Temperate South America       Magellanic MEOW
4      BFT -62.5 -52.5   3.2256782             <NA>     Atlantic Warm Water Malvinas Current PPOW
5      ALB -52.5 -52.5   0.2323575             <NA>     Southern Cold Water     Subantarctic PPOW
6      SWO -52.5 -52.5   0.9996549             <NA>     Southern Cold Water     Subantarctic PPOW
7      ALB -32.5 -52.5   0.4097926             <NA>     Southern Cold Water        Antarctic PPOW
8      BET -32.5 -52.5   1.4336387             <NA>     Southern Cold Water        Antarctic PPOW
9      SWO -32.5 -52.5   1.2541730             <NA>     Southern Cold Water        Antarctic PPOW
10     YFT -32.5 -52.5   1.2215236             <NA>     Southern Cold Water        Antarctic PPOW
                BIOME optional
1               Polar     TRUE
2               Polar     TRUE
3                <NA>     TRUE
4  Boundary - western     TRUE
5               Polar     TRUE
6               Polar     TRUE
7               Polar     TRUE
8               Polar     TRUE
9               Polar     TRUE
10              Polar     TRUE

Dataset 2:

> print(outliers[1:10,])
    Species  Long   Lat tCatch_sqrt                  ECOREGION                   REALM TYPE BIOME optional
3       BFT -67.5 -52.5   2.9238673           Patagonian Shelf Temperate South America MEOW  <NA>     TRUE
39      SWO -62.5 -42.5   0.6316645     North Patagonian Gulfs Temperate South America MEOW  <NA>     TRUE
130     ALB -57.5 -37.5   7.6342489 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
131     BET -57.5 -37.5   0.8367258 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
132     BUM -57.5 -37.5   0.5127475 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
133     SAI -57.5 -37.5   1.3915028 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
134     SKJ -57.5 -37.5   1.2453915 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
135     SWO -57.5 -37.5   2.4453357 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
136     WHM -57.5 -37.5   0.2320991 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
137     YFT -57.5 -37.5   2.2360680 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
             PROVINC
3   Malvinas Current
39  Malvinas Current
130 Malvinas Current
131 Malvinas Current
132 Malvinas Current
133 Malvinas Current
134 Malvinas Current
135 Malvinas Current
136 Malvinas Current
137 Malvinas Current

I deleted my failed attempts, I just have the latest one I tried with left_join:

PPOWoutliers<-left_join(catchesbyPPOW, outliers, by = NULL)

Which gave me this warning:

Joining, by = c("Species", "Long", "Lat", "tCatch_sqrt", "ECOREGION", "REALM", "PROVINC", "TYPE", "BIOME", "optional")
Warning message:
In left_join_impl(x, y, by$x, by$y, suffix$x, suffix$y) :
  joining factors with different levels, coercing to character vector

Body:
Thank you very much for help!
I found a way, in the end.
I did a left_join of the datasets with the variable I wanted to change with a different name in dataset2. Then I did a for loop to replace all the resulting NA's with values from the original column, and it worked.

library(dplyr)

PPOWoutliers <-left_join(catchesbyPPOW, outliers, by = NULL)
summary(PPOWoutliers)

for (i in 1:2448){
   if (is.na(PPOWoutliers[i,11])==TRUE){
     PPOWoutliers[i,12] <- as.character(PPOWoutliers[i,7])}
  else{
    PPOWoutliers[i,12] <- as.character(PPOWoutliers[i,11])}
  }


问:
Illegal string offset error in PHP
I am sending these objects to server to fetch the record and save it. but it is giving me the below given error  </p>

```<code>array(3) {
[0]=>
array(1) {
    ["answer"]=>
    string(218) "{"id":"19","question_id":"10","answer_text":"Please note that we also maintain you:",
"iscorrect":"1",
"created_at":"2014-06-07 07:52:12",
"updated_at":"2014-06-07 07:52:12"}"
  }
  [1]=>
 array(1) {
   ["answer"]=>
    string(218) "{"id":"20","question_id":"10","answer_text":"Please note that we also maintain the following pages and support forums to help you:",
"iscorrect":"1",
"created_at":"2014-06-07 07:52:13",
"updated_at":"2014-06-07 07:52:13"}"
 }
[2]=>
array(1) {
  ["answer"]=>
  string(218) "{"id":"21","question_id":"10",
  "answer_text":"Please note that we also maintain the following pages and support forums to help you:","iscorrect":"0","created_at":"2014-06-07 07:52:13","updated_at":"2014-06-07 07:52:13"}"
}
}

{"error":{"type":"ErrorException","message":"Illegal string offset     'id'","file":"\/home\/learnomatics\/laravel\/mobillz_mlmalp\/app\/controllers\/QuizController.php","line":379}}
</code>```

<p>I am trying to get the values like   </p>

```<code>$answers=Input::get('answers');
var_dump($answers);
foreach ($answers as $answer) {
    if(isset($answer['answer'])){
        quiz_que_ans_id=$answer['answer']['id'];
}
}
</code>```

答:
Try the following, which passes the photo into the Form::file facade.

```<code>{!! Form::file('photo', $user_master->photo, ['class' => 'control-label input-sm', 'type'=>'file', 'accept'=>'image/*']) !!}
</code>```

Instead of

```<code>{!! Form::file('photo', null, ['class' => 'control-label input-sm', 'type'=>'file', 'accept'=>'image/*']) !!}`
</code>```

Title: Illegal string offset error in PHP

Body:
I am sending these objects to server to fetch the record and save it. but it is giving me the below given error

array(3) {
[0]=>
array(1) {
    ["answer"]=>
    string(218) "{"id":"19","question_id":"10","answer_text":"Please note that we also maintain you:",
"iscorrect":"1",
"created_at":"2014-06-07 07:52:12",
"updated_at":"2014-06-07 07:52:12"}"
  }
  [1]=>
 array(1) {
   ["answer"]=>
    string(218) "{"id":"20","question_id":"10","answer_text":"Please note that we also maintain the following pages and support forums to help you:",
"iscorrect":"1",
"created_at":"2014-06-07 07:52:13",
"updated_at":"2014-06-07 07:52:13"}"
 }
[2]=>
array(1) {
  ["answer"]=>
  string(218) "{"id":"21","question_id":"10",
  "answer_text":"Please note that we also maintain the following pages and support forums to help you:","iscorrect":"0","created_at":"2014-06-07 07:52:13","updated_at":"2014-06-07 07:52:13"}"
}
}

{"error":{"type":"ErrorException","message":"Illegal string offset     'id'","file":"\/home\/learnomatics\/laravel\/mobillz_mlmalp\/app\/controllers\/QuizController.php","line":379}}

I am trying to get the values like

$answers=Input::get('answers');
var_dump($answers);
foreach ($answers as $answer) {
    if(isset($answer['answer'])){
        quiz_que_ans_id=$answer['answer']['id'];
}
}

Body:
Try the following, which passes the photo into the Form::file facade.

{!! Form::file('photo', $user_master->photo, ['class' => 'control-label input-sm', 'type'=>'file', 'accept'=>'image/*']) !!}

Instead of

{!! Form::file('photo', null, ['class' => 'control-label input-sm', 'type'=>'file', 'accept'=>'image/*']) !!}`


问:
`scope` around `mount` ineffective?
(While this discusses Blacklight engine, I believe the question is actually purely about Rails.)

I am trying to add internationalisation to my Blacklight app. To that end, I

wrapped everything in config/routes.rb into scope "(:locale)", locale: /en|ja/, and

in app/controllers/application_controller.rb I added before_action :set_locale and overrode default_url_options

as suggested by Rails i18n guide. Most things work, but there's one thing I haven't been able to figure out.

All of my application routes are correctly mapped, e.g. http://www.example.com/en/catalog/12345 correctly matches with (/:locale)/catalog/:id(.:format), and gets routed to catalog#show with {:id=>/[^\/]+(?=\.json|\.html|$|\/)/, :locale=>/en|ja/}). All of Devise's URLs are fine. Everything works... except the mount-ed Blacklight engine.

Apparently, the Blacklight engine doesn't listen to scope. rake routes shows:

```<code>Routes for Blacklight::Engine:
      search_history GET    /search_history(.:format)            search_history#index
      ....
</code>```

and not (:locale)/search_history(.:format) as I would hope.

I have modified the Blacklight template so that I get a language chooser pointing to the current page in both Japanese and English, but when I navigate to search_history, url_for suddenly throws up when confronted with the :locale parameter.

Why does mount ignore scope? How do I solve my problem (engine routes also responding to :locale)?

Here's my default Blacklight-generated config/routes.rb, modified with scope:

```<code>Rails.application.routes.draw do

  scope "(:locale)", locale: /en|ja/ do
    mount Blacklight::Engine => '/'
    root to: "catalog#index"
      concern :searchable, Blacklight::Routes::Searchable.new

    resource :catalog, only: [:index], as: 'catalog', path: '/catalog', controller: 'catalog', id: /[^\/]+(?=\.json|\.html|$|\/)/ do
      concerns :searchable
    end

    devise_for :users
    concern :exportable, Blacklight::Routes::Exportable.new

    resources :solr_documents, only: [:show], path: '/catalog', controller: 'catalog', id: /[^\/]+(?=\.json|\.html|$|\/)/ do
      concerns :exportable
    end

    resources :bookmarks, id: /[^\/]+(?=\.json|\.html|$|\/)/ do
      concerns :exportable

      collection do
        delete 'clear'
      end
    end
  end
end
</code>```

tl;dr: scope prefixes all of my routes, except the routes by mount. Why, and how to fix?

答:
It seems that Rails is indeed ignoring scope in the engine routes, but I can add a scope for the engine explicitly:

```<code>Blacklight::Engine.routes.default_scope = { path: "(:locale)", locale: /en|ja/ }
mount Blacklight::Engine => '/'
</code>```

However, that still does not solve my issues (continued in link_to with parameters for an Engine route).

Title: `scope` around `mount` ineffective?

Body:
(While this discusses Blacklight engine, I believe the question is actually purely about Rails.)

I am trying to add internationalisation to my Blacklight app. To that end, I

wrapped everything in config/routes.rb into scope "(:locale)", locale: /en|ja/, and

in app/controllers/application_controller.rb I added before_action :set_locale and overrode default_url_options

as suggested by Rails i18n guide. Most things work, but there's one thing I haven't been able to figure out.

All of my application routes are correctly mapped, e.g. http://www.example.com/en/catalog/12345 correctly matches with (/:locale)/catalog/:id(.:format), and gets routed to catalog#show with {:id=>/[^\/]+(?=\.json|\.html|$|\/)/, :locale=>/en|ja/}). All of Devise's URLs are fine. Everything works... except the mount-ed Blacklight engine.

Apparently, the Blacklight engine doesn't listen to scope. rake routes shows:

Routes for Blacklight::Engine:
      search_history GET    /search_history(.:format)            search_history#index
      ....

and not (:locale)/search_history(.:format) as I would hope.

I have modified the Blacklight template so that I get a language chooser pointing to the current page in both Japanese and English, but when I navigate to search_history, url_for suddenly throws up when confronted with the :locale parameter.

Why does mount ignore scope? How do I solve my problem (engine routes also responding to :locale)?

Here's my default Blacklight-generated config/routes.rb, modified with scope:

Rails.application.routes.draw do

  scope "(:locale)", locale: /en|ja/ do
    mount Blacklight::Engine => '/'
    root to: "catalog#index"
      concern :searchable, Blacklight::Routes::Searchable.new

    resource :catalog, only: [:index], as: 'catalog', path: '/catalog', controller: 'catalog', id: /[^\/]+(?=\.json|\.html|$|\/)/ do
      concerns :searchable
    end

    devise_for :users
    concern :exportable, Blacklight::Routes::Exportable.new

    resources :solr_documents, only: [:show], path: '/catalog', controller: 'catalog', id: /[^\/]+(?=\.json|\.html|$|\/)/ do
      concerns :exportable
    end

    resources :bookmarks, id: /[^\/]+(?=\.json|\.html|$|\/)/ do
      concerns :exportable

      collection do
        delete 'clear'
      end
    end
  end
end

tl;dr: scope prefixes all of my routes, except the routes by mount. Why, and how to fix?

Body:
It seems that Rails is indeed ignoring scope in the engine routes, but I can add a scope for the engine explicitly:

Blacklight::Engine.routes.default_scope = { path: "(:locale)", locale: /en|ja/ }
mount Blacklight::Engine => '/'

However, that still does not solve my issues (continued in link_to with parameters for an Engine route).


问:
Is there any framework for Windows Forms, DB driven application development/prototyping?
I'm writing simple database driven application, 80% of functionality is CRUD operations on about 15 tables.
Coming from web development background I figured I can cover almost all of these CRUD cases with Rails scaffolding or say Django admins.
So I started to look around for Rails/Django-like framework but for Windows Forms applications (ofcourse I understand that "rich client" application
development significantly differs from a web development and I'm not expecting anything really similar).

I was surprised that except for a variety of ORMs (let's call it Model-layer) it seems like I'm left with little choice
when it comes to View-Controller layer. Maybe I'm missing something?

PS. I evaluated Visual Studio DataSet Designer, but it seems to work only for the most simple cases, and requires additional code for any slightly nontrivial task.

(added) so far I've found:

TrueView for .NET (thanks to Vijay Patel)

NConstruct

答:
Did you check Rocket Framework for Windows Form

Everything is perfectly in order to support your requirement.

This use Entity Framework as the back-end

Use Object Data Source to Auto-Bind Object to UI

Use Generic to minimize the amount of code you need to write

Additionally, the documentation also is very well done and architecture is pretty good and stable too..

I am using it right now and it is serving me pretty well

OwnerDisplayName: dolzenko

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dolzenko


问:
observable to return many json objects from server will contain all at once or iterate through?
I'm using angular 4 and typescript

I have created an api endpoint that will return a array of json objects. My question refers to capturing the json inside a variable designed to hold an array of javascript objects. Will the observable return a list of json objects to where I can just set the variable in my typescript code to that array? And if so how.

Or do I have to iterate through the list of json objects and append them to the array variable?

Notice no code, as I am confused as to when I use interaces, when I use constructors and the alike. I would like to see how this is done. I am still learning

答:
Service : </p>

```<code>getData(): Observable<any> {
return this.http.get(`yourUrl`)
  .map(r => r.json());
}
</code>```

<p>Component : </p>

```<code>yourFunction() {
    this.service.getData().subscribe(
        data => {
            // If your API returns an Array, then data is an array.
            // If it returns one line, then it's an object.
        }
    );
}
</code>```

Body:
Service :

getData(): Observable<any> {
return this.http.get(`yourUrl`)
  .map(r => r.json());
}

Component :

yourFunction() {
    this.service.getData().subscribe(
        data => {
            // If your API returns an Array, then data is an array.
            // If it returns one line, then it's an object.
        }
    );
}


问:
How to display data in smarty when using PDO with prepared statement and executing inside foreach?
```<code>$dbh = new PDO($dsn, $user, $password, array(
 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));

$selectNumberTitle = $dbh->prepare("SELECT AdvertNumber, AdvertTitle FROM `adverts` WHERE AdvertNumber = ? ");

foreach ($advertnumber as $i => $number) {
    $selectNumberTitle->execute(array($number));
    foreach ($selectNumberTitle as $row) {
        echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
    }
}
</code>```

Above code works nicely. I need the same output in smarty.

答:
```<code>$selectNumberTitleMerge = array();
foreach ($advertnumber as $i => $number) {
    $selectNumberTitle->execute(array($number));
    foreach ($selectNumberTitle as $row) {
        $selectNumberTitleMerge[] = $row;
        echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
    }
}
$smarty->assign('selectNumberTitleMerge', $selectNumberTitleMerge);
</code>```

and code inside my template:

```<code>{foreach $selectNumberTitleMerge as $r}
    {$r.AdvertNumber})
    {$r.AdvertTitle}
    <br>
{foreachelse}
    .. no results ..
{/foreach}
</code>```

Body:
$dbh = new PDO($dsn, $user, $password, array(
 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));

$selectNumberTitle = $dbh->prepare("SELECT AdvertNumber, AdvertTitle FROM `adverts` WHERE AdvertNumber = ? ");

foreach ($advertnumber as $i => $number) {
    $selectNumberTitle->execute(array($number));
    foreach ($selectNumberTitle as $row) {
        echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "
";
    }
}

Above code works nicely. I need the same output in smarty.

Body:
$selectNumberTitleMerge = array();
foreach ($advertnumber as $i => $number) {
    $selectNumberTitle->execute(array($number));
    foreach ($selectNumberTitle as $row) {
        $selectNumberTitleMerge[] = $row;
        echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
    }
}
$smarty->assign('selectNumberTitleMerge', $selectNumberTitleMerge);

and code inside my template:

{foreach $selectNumberTitleMerge as $r}
    {$r.AdvertNumber})
    {$r.AdvertTitle}
    <br>
{foreachelse}
    .. no results ..
{/foreach}


问:
Scala 2.8.1 implicitly convert to java.util.List<java.util.Map<String, Object>>
I have a Scala data structure created with the following:

```<code>List(Map[String, Anyref]("a" -> someFoo, "b" -> someBar))
</code>```

I would like to implicitly convert it (using scala.collection.JavaConversions or scala.collection.JavaConverters) to a java.util.List<java.util.Map<String, Object>> to be passed the a Java method that expects the latter.

Is this possible?

I have already created the following method that does it, but was wondering if it can be done automatically by the compiler?

```<code>import scala.collection.JavaConversions._
def convertToJava(listOfMaps: List[Map[String, AnyRef]]):
  java.util.List[java.util.Map[String, Object]] = {
  asJavaList(listOfMaps.map(asJavaMap(_)))
}
</code>```

答:
You don't want this kind of multilevel conversion happening by magic.  You can improve a little on your own conversion though, at least aesthetically.</p>

```<code>import java.{ util => ju }
implicit def convert[K, V](xs: List[Map[K, V]]): ju.List[ju.Map[K, V]] = xs map (x => x: ju.Map[K, V])
</code>```

Body:
I have a Scala data structure created with the following:

List(Map[String, Anyref]("a" -> someFoo, "b" -> someBar))

I would like to implicitly convert it (using scala.collection.JavaConversions or scala.collection.JavaConverters) to a java.util.List<java.util.Map<String, Object>> to be passed the a Java method that expects the latter.

Is this possible?

I have already created the following method that does it, but was wondering if it can be done automatically by the compiler?

import scala.collection.JavaConversions._
def convertToJava(listOfMaps: List[Map[String, AnyRef]]):
  java.util.List[java.util.Map[String, Object]] = {
  asJavaList(listOfMaps.map(asJavaMap(_)))
}

Body:
You don't want this kind of multilevel conversion happening by magic.  You can improve a little on your own conversion though, at least aesthetically.

import java.{ util => ju }
implicit def convert[K, V](xs: List[Map[K, V]]): ju.List[ju.Map[K, V]] = xs map (x => x: ju.Map[K, V])


问:
My call back url is coming as post request, but angular ui-route is not handling , how can i make my state should accept post request?
Here is my route:

```<code>.state('payment-paytm', {
        parent: 'app',
        url: '/pricing/paytm_update',
        component: 'pricing',
        resolve: {
          data: function (PricingService,$stateParams) {
            return PricingService.paytm_update_status($stateParams);
          }
        }
      });
</code>```

this route is not accepting post request coming from paytm call back.

paramList["CALLBACK_URL"] = "http://localhost:9000/pricing/paytm_update"

this is the url we configured in paytm, this is responding correctly but this post request am not able to handle in my angular.

答:
I think angular will not be able to capture the post request coming from paytm.

you have to catch it from the server side language and post it to angular route.

for post parameters you could include it in the url ($stateParams) and then you could get the parameters in your angular controller.

Body:
Here is my route:

.state('payment-paytm', {
        parent: 'app',
        url: '/pricing/paytm_update',
        component: 'pricing',
        resolve: {
          data: function (PricingService,$stateParams) {
            return PricingService.paytm_update_status($stateParams);
          }
        }
      });

this route is not accepting post request coming from paytm call back.

paramList["CALLBACK_URL"] = "http://localhost:9000/pricing/paytm_update"

this is the url we configured in paytm, this is responding correctly but this post request am not able to handle in my angular.


问:
SSL proxy for two applications on same domain (one application without context path)
I have 2 applications running on separate tomcat on the same server machine

application 1 : www.example.com

application 2 : www.example.com/app

I have made the configuration and SSL works for application 1 but not for application 2.

When I try to go to https:www.example.com/app , i get a page not found exception

httpd.conf

```<code>ServerName example.com

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

SSLEngine               On

SSLCertificateFile      /etc/ssl/certs/mydomain_com_with_chain.crt
SSLCertificateKeyFile   /etc/ssl/private/mydomain_com.key

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app
</code>```

The server.xml configuration is correct with the connector having proxy parameters

```<code> <Connector port="8081"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               acceptCount="100"
               disableUploadTimeout="true"
               scheme="https"
               proxyName="example.com"
               proxyPort="443"
               secure="true"/>
</code>```

Can someone please point out the problem here . I suspect it is because application 1 does not have a context path. However, I cannot have a context path for my application 1.
Any suggestions highly appreciated.

答:
If you're really running both tomcats on 8081 and 8082 (because you're only giving one Connector configuration), here's an excerpt from the mod_proxy documentation (emphasis mine):

Ordering ProxyPass Directives

The configured ProxyPass and ProxyPassMatch rules are checked in the
  order of configuration. The first rule that matches wins. So usually
  you should sort conflicting ProxyPass rules starting with the longest
  URLs first. Otherwise, later rules for longer URLS will be hidden by
  any earlier rule which uses a leading substring of the URL. Note that
  there is some relation with worker sharing. In contrast, only one
  ProxyPass directive can be placed in a Location block, and the most
  specific location will take precedence.

This means that it should be enough to reorder

```<code>ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/
</code>```

In addition, you might want to look at Joao Vitorino's answer for changing the second argument to ProxyPassReverse - I'm typically not using ProxyPass and its related options, so I can't tell from the top of my head.

The culprit for the missing match seems to be that the first ProxyPass, covering /, wins over the second for /app

Body:
I have 2 applications running on separate tomcat on the same server machine

application 1 : www.example.com

application 2 : www.example.com/app

I have made the configuration and SSL works for application 1 but not for application 2.

When I try to go to https:www.example.com/app , i get a page not found exception

httpd.conf

ServerName example.com

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

SSLEngine               On

SSLCertificateFile      /etc/ssl/certs/mydomain_com_with_chain.crt
SSLCertificateKeyFile   /etc/ssl/private/mydomain_com.key

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app

The server.xml configuration is correct with the connector having proxy parameters

 <Connector port="8081"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               acceptCount="100"
               disableUploadTimeout="true"
               scheme="https"
               proxyName="example.com"
               proxyPort="443"
               secure="true"/>

Can someone please point out the problem here . I suspect it is because application 1 does not have a context path. However, I cannot have a context path for my application 1.
Any suggestions highly appreciated.

Body:
If you're really running both tomcats on 8081 and 8082 (because you're only giving one Connector configuration), here's an excerpt from the mod_proxy documentation (emphasis mine):

Ordering ProxyPass Directives

The configured ProxyPass and ProxyPassMatch rules are checked in the
  order of configuration. The first rule that matches wins. So usually
  you should sort conflicting ProxyPass rules starting with the longest
  URLs first. Otherwise, later rules for longer URLS will be hidden by
  any earlier rule which uses a leading substring of the URL. Note that
  there is some relation with worker sharing. In contrast, only one
  ProxyPass directive can be placed in a Location block, and the most
  specific location will take precedence.

This means that it should be enough to reorder

ProxyPass               /app       http://myserver:8082/app
ProxyPassReverse        /app       http://myserver:8082/app

ProxyPass               /       http://myserver:8081/
ProxyPassReverse        /       http://myserver:8081/

In addition, you might want to look at Joao Vitorino's answer for changing the second argument to ProxyPassReverse - I'm typically not using ProxyPass and its related options, so I can't tell from the top of my head.

The culprit for the missing match seems to be that the first ProxyPass, covering /, wins over the second for /app


问:
How to get rid of < > { } highlight in VSCode
I switched from Notepad++ to VSCode. Every thing is nice except for this highlighter. I found no use for it right now and would like to remove it.

答:
Try setting:

```<code>"editor.matchBrackets": false
</code>```

More info about VSCode settings

Body:
Try setting:

"editor.matchBrackets": false

More info about VSCode settings


问:
How can I iteratively apply the function on a data in c++?
I'm just looking for a general pseudo-code type in which if I have a data type of vector<vector<double>> Xand it needs to iteratively go through a function myFunction(vector<vector<double>> &X) that returns the same data type until a certain condition on X is met or until n'th iterations.

So, suppose let X(1) = myFunction(X), then feed it again to get

X(2) = myFunction(X(1)), then feed it again to get

X(3) = myFunction(X(2)), and repreat until certain conditions say

myCondition(X(k)) = true or until n'th iteration has been done and stops at X(n)

How could I implement it?

答:
You may do something like this:

```<code>typedef vector<vector<double>> datatype;
datatype myFunction( datatype X ,int iteration ,int n ){
    if( iteration== n ) return X;
    /// do some operations with X
    myFunction( X , iteration+1 ,n );
}
</code>```

From main function, you may call like this:

```<code>  // define vector X and no of iterations- n.
  datatype ans=myFunction(X,0,n);
</code>```

Body:
You may do something like this:

typedef vector<vector<double>> datatype;
datatype myFunction( datatype X ,int iteration ,int n ){
    if( iteration== n ) return X;
    /// do some operations with X
    myFunction( X , iteration+1 ,n );
}

From main function, you may call like this:

  // define vector X and no of iterations- n.
  datatype ans=myFunction(X,0,n);


问:
Counting the number of people working at a given time
I have data the shows when employees log in and when they log out. I call the duration they are logged in "Ready" time and the time they are logged off as "Not Ready" time. What I want to do is have a continuous, gradient timeline that shows how many people are in the ready state.

Some notes about the data:

The data has a start time and an end time. Each record is unique for the employee and the start time?

I unfortunately cannot post this data as it does not belong to me.

答:
Let's say that your data is something like this

```<code>employee    start_time  end_time
E1  7/7/2017  10:03:10 AM   7/7/2017  18:03:10 AM
E2  7/7/2017  10:10:10 AM   7/7/2017  18:03:10 AM
E3  7/7/2017  10:13:10 AM   7/7/2017  18:03:10 AM
E1  7/7/2017  11:03:10 AM   7/7/2017  19:03:10 AM
E2  7/7/2017  10:30:10 AM   7/7/2017  18:03:10 AM
</code>```

In that case I would follow these steps:

Check if start_time & end_time columns are not in 'timestamp' format then right click it and go to 'Change data type' to select 'Date & Time'

Create a parameter Select_Report_DateTime. In parameter window select Data  type = 'Date & Time'; Display format = 'Automatic'; Allowable values = 'All'

Right click this parameter and select 'Show parameter control'

Create calculated field default_date_time as #1/1/1900 12:00:00 AM#. If it's not in 'timestamp' format then right click it and go to 'Change data type' to select 'Date & Time'

Create calculated field Report_DateTime_formatted as

```<code>IF [Select_Report_DateTime] == [default_date_time] then now()
ELSE [Select_Report_DateTime]
END
</code>```

Create a calculated field Users(inReadyState) as

```<code>IF (([Report_DateTime_formatted] >= [start_time]) &
    ([Report_DateTime_formatted] < [end_time])) THEN "Yes"
ELSE "No"
END
</code>```

Now drag Users(inReadyState) in 'Columns', CNT[employee] in 'Rows' and 'Marks' as Bar.

You can very well play around with this model to get the o/p as per your specific requirement.

Don't forget to let us know if it helped :)

Body:
Let's say that your data is something like this

employee    start_time  end_time
E1  7/7/2017  10:03:10 AM   7/7/2017  18:03:10 AM
E2  7/7/2017  10:10:10 AM   7/7/2017  18:03:10 AM
E3  7/7/2017  10:13:10 AM   7/7/2017  18:03:10 AM
E1  7/7/2017  11:03:10 AM   7/7/2017  19:03:10 AM
E2  7/7/2017  10:30:10 AM   7/7/2017  18:03:10 AM

In that case I would follow these steps:

Check if start_time & end_time columns are not in 'timestamp' format then right click it and go to 'Change data type' to select 'Date & Time'

Create a parameter Select_Report_DateTime. In parameter window select Data  type = 'Date & Time'; Display format = 'Automatic'; Allowable values = 'All'

Right click this parameter and select 'Show parameter control'

Create calculated field default_date_time as #1/1/1900 12:00:00 AM#. If it's not in 'timestamp' format then right click it and go to 'Change data type' to select 'Date & Time'

Create calculated field Report_DateTime_formatted as

IF [Select_Report_DateTime] == [default_date_time] then now()
ELSE [Select_Report_DateTime]
END

Create a calculated field Users(inReadyState) as

IF (([Report_DateTime_formatted] >= [start_time]) &
    ([Report_DateTime_formatted] < [end_time])) THEN "Yes"
ELSE "No"
END

Now drag Users(inReadyState) in 'Columns', CNT[employee] in 'Rows' and 'Marks' as Bar.

You can very well play around with this model to get the o/p as per your specific requirement.

Don't forget to let us know if it helped :)


问:
DataMapperException: Unable to open connection to "MySQL, MySQL provider 5.0.8.1"
I use ibatis with net and my DB is mysql.

This following error occurs now and then and I was unable to find the cause. Any insights what could be the cause for the errors?

iBatis should handle the opening and closing of DB connections? Then I am not sure how this error could occur.

Is it possible to programmatically close the connections?

Error

MySql.Data.MySqlClient.MySqlException: Too many connections
Stack trace
[MySqlException: Too many connections]
at MySql.Data.MySqlClient.MySqlStream.OpenPacket()
at MySql.Data.MySqlClient.NativeDriver.Authenticate411()
at MySql.Data.MySqlClient.NativeDriver.Authenticate()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at IBatisNet.DataMapper.SqlMapSession.OpenConnection(String connectionString)

[DataMapperException: Unable to open connection to "MySQL, MySQL provider 5.0.8.1".]
at IBatisNet.DataMapper.SqlMapSession.OpenConnection(String connectionString)
at IBatisNet.DataMapper.SqlMapSession.OpenConnection()
at IBatisNet.DataMapper.Commands.DbCommandDecorator.System.Data.IDbCommand.ExecuteReader()
at IBatisNet.DataMapper.MappedStatements.MappedStatement.RunQueryForObject(RequestScope\ request, ISqlMapSession session, Object parameterObject, Object resultObject)
at IBatisNet.DataMapper.MappedStatements.MappedStatement.ExecuteQueryForObject(ISqlMapSession\ session, Object parameterObject, Object resultObject)
at IBatisNet.DataMapper.MappedStatements.MappedStatement.ExecuteQueryForObject(ISqlMapSession\ session, Object parameterObject)
at IBatisNet.DataMapper.SqlMapper.QueryForObject(String statementName, Object\ parameterObject)
at Sun.Stream.Persistence.SchoolRepository.GetSchoolDetailsByUrl(String\ SchoolUrl) in F:\SVN\Edu\Persistence\SchoolRepository.cs:line 213
at CustomExtensions.FindSchoolUrl(School& school)
at EduPage.Page_PreInit(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o,\ Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,\ EventArgs e)
at System.Web.UI.Page.OnPreInit(EventArgs e)
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,\ Boolean includeStagesAfterAsyncPoint)

[HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.]
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,\ Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint,\ Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.embedplayer_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

答:
just execute this command</p>

```<code>SET GLOBAL max_connections = 1024;
</code>```

Body:
just execute this command

SET GLOBAL max_connections = 1024;


问:
How to make thymeleaf to ignore the null object?
I have a spring mvc project project with jsp as view. I need to use thymeleaf now. The old jsp project will auto ignore the manager object, if I don't put the manager object to the ModelMap.

```<code>  <form class="form-horizontal" method="post" action="<c:url value=" /${action} " />">
<input type="hidden" name="id" value="${manager.id}">
....
<div class="form-group">
    <label class="col-sm-2 control-label">email</label>
    <div class="col-sm-8">
        <input type="text" name="email" value="${manager.email}" class="form-control1" placeholder="Email">
    </div>
</div>
<div class="form-group">
    <label class="col-sm-2 control-label">phone</label>
    <div class="col-sm-8">
        <input type="text" name="mobile" value="${manager.mobile}" class="form-control1" placeholder="phone number">
    </div>
</div>
...
<div class="form-group">
    <div class="col-sm-8 col-sm-offset-2 ">
        <button class="btn btn-success1 btn-block">sumbit</button>
    </div>
</div>

</form>
</code>```

However Thymeleaf will give a error if I write as

```<code>     <input type="text" name="email" th:value="${manager.email}" class="form-control1" placeholder="Email">
</code>```

I knew we can check the object as

```<code><input type="text" name="mobile" th:value="${manager? manager.mobile : ''}" class="form-control1" placeholder="phone number">
</code>```

Do I have to writte check each of them ?

答:
There is a safe navigation & an  elvis operator in Spring EL which you can use in Thymeleaf. Here is the docs
which describes it. Use it like below in your case which will return null instead of throwing an exception.</p>

```<code>${manager?.email}
</code>```

Body:
I have a spring mvc project project with jsp as view. I need to use thymeleaf now. The old jsp project will auto ignore the manager object, if I don't put the manager object to the ModelMap.

  <form class="form-horizontal" method="post" action="<c:url value=" /${action} " />">
<input type="hidden" name="id" value="${manager.id}">
....

    email

        <input type="text" name="email" value="${manager.email}" class="form-control1" placeholder="Email">

    phone

        <input type="text" name="mobile" value="${manager.mobile}" class="form-control1" placeholder="phone number">

...

        <button class="btn btn-success1 btn-block">sumbit</button>

</form>

However Thymeleaf will give a error if I write as

     <input type="text" name="email" th:value="${manager.email}" class="form-control1" placeholder="Email">

I knew we can check the object as

<input type="text" name="mobile" th:value="${manager? manager.mobile : ''}" class="form-control1" placeholder="phone number">

Do I have to writte check each of them ?

Body:
There is a safe navigation & an  elvis operator in Spring EL which you can use in Thymeleaf. Here is the docs
which describes it. Use it like below in your case which will return null instead of throwing an exception.

${manager?.email}


问:
eBay Finding API filter by shipToLocations
I'm using eBay Finding API and I want to get results by filtering shipping to my country. I found this shipToLocations, but I can't find the filter.

```<code>    $apicall .= "&itemFilter(0).name=Condition";
    $apicall .= "&itemFilter(0).value=New";
    $apicall .= "&itemFilter(1).name=ListingType";
    $apicall .= "&itemFilter(1).value=FixedPrice";
    $apicall .= "&itemFilter(2).name=HideDuplicateItems";
    $apicall .= "&itemFilter(2).value=true";
</code>```

答:
You can set a new itemFilter with name=AvailableTo and value=<2 Characters code of your country>
For example:</p>

```<code>$apicall .= "&itemFilter(1).name=AvailableTo";
$apicall .= "&itemFilter(1).value=DE";                  // DE = country code for Germany
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using eBay Finding API and I want to get results by filtering shipping to my country. I found this shipToLocations, but I can't find the filter.

    $apicall .= "&itemFilter(0).name=Condition";
    $apicall .= "&itemFilter(0).value=New";
    $apicall .= "&itemFilter(1).name=ListingType";
    $apicall .= "&itemFilter(1).value=FixedPrice";
    $apicall .= "&itemFilter(2).name=HideDuplicateItems";
    $apicall .= "&itemFilter(2).value=true";

Body:
You can set a new itemFilter with name=AvailableTo and value=<2 Characters code of your country>
For example:

$apicall .= "&itemFilter(1).name=AvailableTo";
$apicall .= "&itemFilter(1).value=DE";                  // DE = country code for Germany


问:
adding and deleting form rows with javascript
I created a form where add button adds another row with name, email and age in the form and delete deletes it.  However, jquery code does not work as intended. I am a beginner in jquery to figure out what mistake I have made. I looked through similar questions in Stackoverflow but could'nt figure it out.

$(document).ready(function(){
     var max_fields= 10;
     var wrapper  = $("#commentForm");
     var add_button = $("#addButton");
     var delete_button = $('#deleteButton')

     var x=1;
     add_button.click(function(e){
      e.preventDefault();

      if (x < max_fields){
       x++;
       $(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
      }

     });
      $(wrapper).on("click","#deleteButton", function(e){

       e.preventDefault();$(this).parent('p').remove();
       x--;

      })

     });
      ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
    <section class="container">
     <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
     <fieldset>
      <input type="checkbox"/>

      <p>
       <span> Name </span> <br>
       <label for="aname" ></label>
       <input id="bname" name="name" minlength="2" type="text" required/>
      </p>
      <p>
       <span> Email </span> <br>
       <label for="aemail" ></label>
       <input id="bemail" name="email" type="email" required/>
      </p>
      <p>
       <span> Age </span> <br>
       <label for="aage" ></label>
       <input id="bage" name="age" type="number" required/>
      </p>

      <div class="input_fields_wrap">

       <div class="addButton">
        <button  type="button" value="add">Add</button>
       </div>

       <div class="deleteButton">
        <button type="button" value="delete">Delete</button>
       </div>
      </div>

     </fieldset>
     </form>

     </section>

    </body></code>```

Thank you.

答:
So, there are some things not good as you have them.

IDs should be unique

why use  if you have

you can use name="value[]" put your eyes on the [] so if you submit your form you will get an array of values on the server which is just awesome

you need clean HTML! Cause yes upper- / lowercase does matter

if you have an ID the jQuery selector is # so $('#my-id') if you have a class it's a . so  $('.my-class')

Now I've changed it and tried to keep it simple so it should be easy to see whats going on.

Make a wrapper around those fields you want to copy / duplicate what ever. If they are the same as they are pretty much just copy that
 and insert it

Removed all IDs (hope you don't need them) else you need to clean them up anyway.

use little CSS to hide the delete button at first field

insert delete button for every field, cause most users will click add multiple times, then insert data and then see they don't need all the fields so they want to delete the empty ones. Which is more simple if they can delete the single ones by one

Play with this code:

$(document).ready(function(){
  var max_fields= 10;
  var counter = 0;

  $('.addButton').on('click', function(){
      counter++;
      if(counter >= max_fields) {
          return;
      }

      var copy = $('.form-copy-wrap').first().clone();
      copy.find('.delete').removeAttr('disabled');
      $("#commentForm fieldset").append(copy);
  });

  $(document).on('click', '.delete', function(){
      $(this).closest('.form-copy-wrap').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.delete[disabled] {
    display: none;
}

.form-copy-wrap {
    border: dashed 1px #afafaf;
}</code>```

    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>
        <input type="checkbox"/>

            Name
            <input name="name[]" minlength="2" type="text" required/>

            Email
            <input name="email[]" type="email" required/>

            Age
            <input name="age[]" type="number" required/>

        <button class="delete" type="button" value="delete" disabled="disabled">Delete</button>

                <button  type="button" value="add">Add</button>

    </fieldset>
    </form>```
</div>
</div>
</p>

<p>Delete with checkbox:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
  var max_fields= 10;
  var counter = 0;

  $('.addButton').on('click', function(){
      counter++;
      if(counter >= max_fields) {
          return;
      }

      var copy = $('.form-copy-wrap').first().clone();
      copy.find('input[name^="delete"]').prop( "checked", false );
      $("#commentForm fieldset").append(copy);
  });

  $(document).on('click', '.delete', function(){
      $('input[name^="delete"]:checked').closest('.form-copy-wrap').remove();
  });

  $(document).on('change', 'input[name^="delete"]', function(){
      if($('input[name^="delete"]:checked').length >= 1) {
          $('.delete').removeAttr('disabled');
      } else {
          $('.delete').attr('disabled', 'disabled');
      }
  });
});</code>```

.delete[disabled] {
    opacity: 0.5;
}

.form-copy-wrap {
    border: dashed 1px #afafaf;
}

#commentForm .form-copy-wrap:first-child p:first-child {
    display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>

<div class="form-copy-wrap">
        <p>
            <label>
              <input type="checkbox" name="delete[]" value="delete" />
              Delete this row
            </label>
        </p>

        <p>
            <label for="aname" >Name</label>
            <input name="name[]" minlength="2" type="text" required/>
        </p>
        <p>
            <label for="aemail" >Email</label>
            <input name="email[]" type="email" required/>
        </p>
        <p>
            <label for="aage" >Age</label>
            <input name="age[]" type="number" required/>
        </p>

</div>

        <div class="input_fields_wrap">
            <div class="addButton">
                <button  type="button" value="add">Add</button>
            </div>
            <button class="delete" type="button" value="delete" disabled="disabled">Delete</button>
        </div>

    </fieldset>
    </form></code>```

Body:
I created a form where add button adds another row with name, email and age in the form and delete deletes it.  However, jquery code does not work as intended. I am a beginner in jquery to figure out what mistake I have made. I looked through similar questions in Stackoverflow but could'nt figure it out.

$(document).ready(function(){
     var max_fields= 10;
     var wrapper  = $("#commentForm");
     var add_button = $("#addButton");
     var delete_button = $('#deleteButton')

     var x=1;
     add_button.click(function(e){
      e.preventDefault();

      if (x < max_fields){
       x++;
       $(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
      }

     });
      $(wrapper).on("click","#deleteButton", function(e){

       e.preventDefault();$(this).parent('p').remove();
       x--;

      })

     });

     <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
     <fieldset>
      <input type="checkbox"/>

        Name

       <input id="bname" name="name" minlength="2" type="text" required/>

        Email

       <input id="bemail" name="email" type="email" required/>

        Age

       <input id="bage" name="age" type="number" required/>

        <button  type="button" value="add">Add</button>

        <button type="button" value="delete">Delete</button>

     </fieldset>
     </form>

Thank you.

Body:
So, there are some things not good as you have them.

IDs should be unique

why use <span> if you have <label>

you can use name="value[]" put your eyes on the [] so if you submit your form you will get an array of values on the server which is just awesome

you need clean HTML! Cause yes upper- / lowercase does matter

if you have an ID the jQuery selector is # so $('#my-id') if you have a class it's a . so  $('.my-class')

Now I've changed it and tried to keep it simple so it should be easy to see whats going on.

Make a wrapper around those fields you want to copy / duplicate what ever. If they are the same as they are pretty much just copy that <div> and insert it

Removed all IDs (hope you don't need them) else you need to clean them up anyway.

use little CSS to hide the delete button at first field

insert delete button for every field, cause most users will click add multiple times, then insert data and then see they don't need all the fields so they want to delete the empty ones. Which is more simple if they can delete the single ones by one

Play with this code:

$(document).ready(function(){
  var max_fields= 10;
  var counter = 0;

  $('.addButton').on('click', function(){
      counter++;
      if(counter >= max_fields) {
          return;
      }

      var copy = $('.form-copy-wrap').first().clone();
      copy.find('.delete').removeAttr('disabled');
      $("#commentForm fieldset").append(copy);
  });

  $(document).on('click', '.delete', function(){
      $(this).closest('.form-copy-wrap').remove();
  });
});

.delete[disabled] {
    display: none;
}

.form-copy-wrap {
    border: dashed 1px #afafaf;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>
        <input type="checkbox"/>

<div class="form-copy-wrap">
        <p>
            <label for="aname" >Name</label>
            <input name="name[]" minlength="2" type="text" required/>
        </p>
        <p>
            <label for="aemail" >Email</label>
            <input name="email[]" type="email" required/>
        </p>
        <p>
            <label for="aage" >Age</label>
            <input name="age[]" type="number" required/>
        </p>
        <button class="delete" type="button" value="delete" disabled="disabled">Delete</button>
</div>

        <div class="input_fields_wrap">
            <div class="addButton">
                <button  type="button" value="add">Add</button>
            </div>
        </div>

    </fieldset>
    </form>

Delete with checkbox:

$(document).ready(function(){
  var max_fields= 10;
  var counter = 0;

  $('.addButton').on('click', function(){
      counter++;
      if(counter >= max_fields) {
          return;
      }

      var copy = $('.form-copy-wrap').first().clone();
      copy.find('input[name^="delete"]').prop( "checked", false );
      $("#commentForm fieldset").append(copy);
  });

  $(document).on('click', '.delete', function(){
      $('input[name^="delete"]:checked').closest('.form-copy-wrap').remove();
  });

  $(document).on('change', 'input[name^="delete"]', function(){
      if($('input[name^="delete"]:checked').length >= 1) {
          $('.delete').removeAttr('disabled');
      } else {
          $('.delete').attr('disabled', 'disabled');
      }
  });
});

.delete[disabled] {
    opacity: 0.5;
}

.form-copy-wrap {
    border: dashed 1px #afafaf;
}

#commentForm .form-copy-wrap:first-child p:first-child {
    display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>

<div class="form-copy-wrap">
        <p>
            <label>
              <input type="checkbox" name="delete[]" value="delete" />
              Delete this row
            </label>
        </p>

        <p>
            <label for="aname" >Name</label>
            <input name="name[]" minlength="2" type="text" required/>
        </p>
        <p>
            <label for="aemail" >Email</label>
            <input name="email[]" type="email" required/>
        </p>
        <p>
            <label for="aage" >Age</label>
            <input name="age[]" type="number" required/>
        </p>

</div>

        <div class="input_fields_wrap">
            <div class="addButton">
                <button  type="button" value="add">Add</button>
            </div>
            <button class="delete" type="button" value="delete" disabled="disabled">Delete</button>
        </div>

    </fieldset>
    </form>


问:
GridLayoutManager scrollToPosition doesn't scroll
I am passing the position of the RecyclerView from first FirstFragment to SecondFragment and it works. After scrolling in that one, I get the position again and I am passing it to the FirstFragment. But, when FirstFragment gets the position, the list is not scrolled to that particular index.

FirstFragment

```<code>public class FirstFragment extends BaseFragment implements FirstAdapter.OnItemInteractionListener {

FragmentFirstBinding mBinder;
List<MyItem> mMyItemList;
GridLayoutManager mManager;
MyItem mMyItem;
FirstAdapter mAdapter;
int mPosition;

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static final String GET_SECOND_FRAGMENT = "get_second_fragment";

public static FirstFragment newInstance() {
    FirstFragment fragment = new FirstFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMyItemList = new ArrayList<>();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mBinder = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false);
    populate();
    mManager = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
    mAdapter = new FirstAdapter(getContext(), mMyItemList);
    mBinder.rvFirst.setLayoutManager(mManager);
    mBinder.rvFirst.setAdapter(mAdapter);
    mAdapter.addOnItemInteractionListener(this);
    EventBus.getDefault().register(this);
    return mBinder.getRoot();
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    EventBus.getDefault().unregister(this);
}

private void populate() {
    for (int i = 0; i < 30; i++) {
        mMyItemList.add(i, mMyItem);
    }
}

private void sendAction(String action, List<MyItem> myItemList, int position) {
    if (mListener == null) {
        return;
    }
    Bundle bundle = new Bundle();
    bundle.putString(Constants.ACTION, action);
    bundle.putParcelable(Constants.DATA1, Parcels.wrap(myItemList));
    bundle.putInt(Constants.POSITION, position);
    mListener.onFragmentInteraction(bundle);
}

@Override
public void onItemClick(int position) {
    sendAction(GET_SECOND_FRAGMENT, mMyItemList, position);
}

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onMessage(SendPos event) {
    mPosition = event.getPos();
    mBinder.rvFirst.scrollToPosition(mPosition);
    mBinder.rvFirst.getLayoutManager().scrollToPosition(mPosition);
    EventBus.getDefault().removeStickyEvent(event);
}
</code>```

}

Second Fragment

```<code>public class SecondFragment extends BaseFragment {

FragmentSecondBinding mBinder;
List<MyItem> mMyItemList;
LinearLayoutManager mManager;
Parcelable mParcelable;
SecondAdapter mAdapter;
int mPosition;

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static final String ACTION_BACK = "back";

public static SecondFragment newInstance(List<MyItem> myItemList, int position) {
    SecondFragment fragment = new SecondFragment();
    Bundle args = new Bundle();
    args.putParcelable(ARG_PARAM1, Parcels.wrap(myItemList));
    args.putInt(ARG_PARAM2, position);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParcelable = getArguments().getParcelable(ARG_PARAM1);
        mMyItemList = Parcels.unwrap(mParcelable);
        mPosition = getArguments().getInt(ARG_PARAM2);
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mBinder = DataBindingUtil.inflate(inflater, R.layout.fragment_second, container, false);
    mManager = new LinearLayoutManager(getContext());
    mAdapter = new SecondAdapter(getContext(), mMyItemList);
    mBinder.rvSecond.setLayoutManager(mManager);
    mBinder.rvSecond.setAdapter(mAdapter);
    mManager.scrollToPosition(mPosition);
    setUIListeners();
    return mBinder.getRoot();
}

private void setUIListeners() {
    mBinder.back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPosition = mManager.findFirstVisibleItemPosition();
            sendPos(mPosition);
            sendActionToActivity(ACTION_BACK);
        }
    });
}

private void sendActionToActivity(String action) {
    Bundle bundle = new Bundle();
    bundle.putString(Constants.ACTION, action);
    mListener.onFragmentInteraction(bundle);
}

private void sendPos(int pos) {
    SendPos sendPos = new SendPos();
    sendPos.setPos(pos);
    EventBus.getDefault().postSticky(sendPos);
}
</code>```

}

答:
Have you try to use the RecyclerView as well ? for example :

```<code>mRecyclerView.scrollToPosition(mPosition);
mRecyclerView.getLayoutManager().scrollToPosition(mPosition);
</code>```

Don't forget to register the EventBus : EventBus.getDefault().register(this);

EDIT:

You can use RecyclerView.smoothScrollToPosition(int position) instead

Hope this helps.
Sorry for my english.

Body:
I am passing the position of the RecyclerView from first FirstFragment to SecondFragment and it works. After scrolling in that one, I get the position again and I am passing it to the FirstFragment. But, when FirstFragment gets the position, the list is not scrolled to that particular index.

FirstFragment

public class FirstFragment extends BaseFragment implements FirstAdapter.OnItemInteractionListener {

FragmentFirstBinding mBinder;
List<MyItem> mMyItemList;
GridLayoutManager mManager;
MyItem mMyItem;
FirstAdapter mAdapter;
int mPosition;

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static final String GET_SECOND_FRAGMENT = "get_second_fragment";

public static FirstFragment newInstance() {
    FirstFragment fragment = new FirstFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMyItemList = new ArrayList<>();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mBinder = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false);
    populate();
    mManager = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
    mAdapter = new FirstAdapter(getContext(), mMyItemList);
    mBinder.rvFirst.setLayoutManager(mManager);
    mBinder.rvFirst.setAdapter(mAdapter);
    mAdapter.addOnItemInteractionListener(this);
    EventBus.getDefault().register(this);
    return mBinder.getRoot();
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    EventBus.getDefault().unregister(this);
}

private void populate() {
    for (int i = 0; i < 30; i++) {
        mMyItemList.add(i, mMyItem);
    }
}

private void sendAction(String action, List<MyItem> myItemList, int position) {
    if (mListener == null) {
        return;
    }
    Bundle bundle = new Bundle();
    bundle.putString(Constants.ACTION, action);
    bundle.putParcelable(Constants.DATA1, Parcels.wrap(myItemList));
    bundle.putInt(Constants.POSITION, position);
    mListener.onFragmentInteraction(bundle);
}

@Override
public void onItemClick(int position) {
    sendAction(GET_SECOND_FRAGMENT, mMyItemList, position);
}

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onMessage(SendPos event) {
    mPosition = event.getPos();
    mBinder.rvFirst.scrollToPosition(mPosition);
    mBinder.rvFirst.getLayoutManager().scrollToPosition(mPosition);
    EventBus.getDefault().removeStickyEvent(event);
}

}

Second Fragment

public class SecondFragment extends BaseFragment {

FragmentSecondBinding mBinder;
List<MyItem> mMyItemList;
LinearLayoutManager mManager;
Parcelable mParcelable;
SecondAdapter mAdapter;
int mPosition;

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static final String ACTION_BACK = "back";

public static SecondFragment newInstance(List<MyItem> myItemList, int position) {
    SecondFragment fragment = new SecondFragment();
    Bundle args = new Bundle();
    args.putParcelable(ARG_PARAM1, Parcels.wrap(myItemList));
    args.putInt(ARG_PARAM2, position);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParcelable = getArguments().getParcelable(ARG_PARAM1);
        mMyItemList = Parcels.unwrap(mParcelable);
        mPosition = getArguments().getInt(ARG_PARAM2);
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mBinder = DataBindingUtil.inflate(inflater, R.layout.fragment_second, container, false);
    mManager = new LinearLayoutManager(getContext());
    mAdapter = new SecondAdapter(getContext(), mMyItemList);
    mBinder.rvSecond.setLayoutManager(mManager);
    mBinder.rvSecond.setAdapter(mAdapter);
    mManager.scrollToPosition(mPosition);
    setUIListeners();
    return mBinder.getRoot();
}

private void setUIListeners() {
    mBinder.back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPosition = mManager.findFirstVisibleItemPosition();
            sendPos(mPosition);
            sendActionToActivity(ACTION_BACK);
        }
    });
}

private void sendActionToActivity(String action) {
    Bundle bundle = new Bundle();
    bundle.putString(Constants.ACTION, action);
    mListener.onFragmentInteraction(bundle);
}

private void sendPos(int pos) {
    SendPos sendPos = new SendPos();
    sendPos.setPos(pos);
    EventBus.getDefault().postSticky(sendPos);
}

}

Body:
Have you try to use the RecyclerView as well ? for example :

mRecyclerView.scrollToPosition(mPosition);
mRecyclerView.getLayoutManager().scrollToPosition(mPosition);

Don't forget to register the EventBus : EventBus.getDefault().register(this);

EDIT:

You can use RecyclerView.smoothScrollToPosition(int position) instead

Hope this helps.
Sorry for my english.


问:
How to read an environment variable in Kotlin?
I'd like to get a certain value from an environment variable in my Kotlin app, but I can't find anything about reading environment variables in the core libraries documentation.

I'd expect it to be under kotlin.system but there's really not that much there.

答:
And if you want to handle env var which do exists but is empty:

```<code>val myEnv = (System.getenv("MY_ENV") ?: "").ifEmpty { "default_value" }
</code>```

(see edit history for previos versions)

Body:
And if you want to handle env var which do exists but is empty:

val myEnv = (System.getenv("MY_ENV") ?: "").ifEmpty { "default_value" }

(see edit history for previos versions)


问:
Angular js .push method for Json file not working
When i try to enter random data into an Array or Json file through .push method its not working
here is my code
Array Code is

```<code> $scope.stock =[{
"name":"Pepsi",
"price":65,
"color":"black",
"avaliable":true}]
</code>```

trying to bind through ng-model

```<code><form ng-submit="addItem()">
    <input type="text" placeholder="Name" ng-model="newName" />
    <input type="text" placeholder="Price" ng-model="newPrice" />
    <input type="text" placeholder="color" ng-model="newcolor" />
    <input class="submit" type="submit" value="Add New Item" />
</form>
</code>```

the JS code is

```<code>$scope.addItem = function(){
    $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
    });
</code>```

答:
```<code>//try this
$scope.stock = [];

$scope.addItem = function(){
$scope.stock.push({
    name: $scope.newName,
    price: parseInt($scope.newPrice),
    color: $scope.newcolor,
    avaliable: true
});
</code>```

Body:
When i try to enter random data into an Array or Json file through .push method its not working
here is my code
Array Code is

 $scope.stock =[{
"name":"Pepsi",
"price":65,
"color":"black",
"avaliable":true}]

trying to bind through ng-model

<form ng-submit="addItem()">
    <input type="text" placeholder="Name" ng-model="newName" />
    <input type="text" placeholder="Price" ng-model="newPrice" />
    <input type="text" placeholder="color" ng-model="newcolor" />
    <input class="submit" type="submit" value="Add New Item" />
</form>

the JS code is

$scope.addItem = function(){
    $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
    });