问:
python: get the print output in an exec statement
I want to get the output of an exec(...) Here is my code:

```<code>code = """
i = [0,1,2]
for j in i :
    print j
"""
result = exec(code)
</code>```

How could I get the things that print outputed?
How can I get something like:

```<code>0
1
2
</code>```

Regards and thanks.

答:
Here is a small correction of Frédéric's answer. We need to handle a possible exception in exec() to return back normal stdout. Otherwise we could not see farther print outputs:

```<code>code = """
i = [0,1,2]
for j in i :
print j
"""

from cStringIO import StringIO
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
try:
    exec(code)
except:
    raise
finally: # !
    sys.stdout = old_stdout # !

print redirected_output.getvalue()
...
print 'Hello, World!' # now we see it in case of the exception above
</code>```

Body:
I want to get the output of an exec(...) Here is my code:

code = """
i = [0,1,2]
for j in i :
    print j
"""
result = exec(code)

How could I get the things that print outputed?
How can I get something like:

0
1
2

Regards and thanks.

Body:
Here is a small correction of Frédéric's answer. We need to handle a possible exception in exec() to return back normal stdout. Otherwise we could not see farther print outputs:

code = """
i = [0,1,2]
for j in i :
print j
"""

from cStringIO import StringIO
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
try:
    exec(code)
except:
    raise
finally: # !
    sys.stdout = old_stdout # !

print redirected_output.getvalue()
...
print 'Hello, World!' # now we see it in case of the exception above


来源: stackexchange

问:
How to get the number of days in a specific month using Java Calendar?
I am creating a simple program that allows the user to see how many days between the months they set.

For example From January - March

I can get the current day of the month using this:

```<code>Calendar.DAY_OF_MONTH
</code>```

What I want is how can I supply a value in the month?

I have this simple code:

```<code>public static void machineProblemTwo(int startMonth, int endMonth) {

        int[] month = new int[0];
        int date = 2015;

        for(int x = startMonth; x <= endMonth; x++) {
           System.out.println(x + " : " + getMaxDaysInMonth(x,date));
        }

    }

public static int getMaxDaysInMonth(int month, int year){

        Calendar cal = Calendar.getInstance();
        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // how can I supply the month here?

        return days;

    }
</code>```

How can i do that? Can you help me with this?

答:
We can do this as well:</p>

```<code>private DateTime getNewDate(DateTime date, int dayOfMonth) {
    // first we need to make it 1st day of the month
    DateTime newDateTime = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0);
    int maximumValueOfDays = newDateTime.dayOfMonth().getMaximumValue();

    // to handle the month which has less than 31 days
    if (dayOfMonth > maximumValueOfDays) {
      newDateTime = newDateTime.dayOfMonth().withMaximumValue();
    } else {
      newDateTime = newDateTime.withDayOfMonth(dayOfMonth);
    }
    return newDateTime;
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a simple program that allows the user to see how many days between the months they set.

For example From January - March

I can get the current day of the month using this:

Calendar.DAY_OF_MONTH

What I want is how can I supply a value in the month?

I have this simple code:

public static void machineProblemTwo(int startMonth, int endMonth) {

        int[] month = new int[0];
        int date = 2015;

        for(int x = startMonth; x <= endMonth; x++) {
           System.out.println(x + " : " + getMaxDaysInMonth(x,date));
        }

    }

public static int getMaxDaysInMonth(int month, int year){

        Calendar cal = Calendar.getInstance();
        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // how can I supply the month here?

        return days;

    }

How can i do that? Can you help me with this?

Body:
We can do this as well:

private DateTime getNewDate(DateTime date, int dayOfMonth) {
    // first we need to make it 1st day of the month
    DateTime newDateTime = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0);
    int maximumValueOfDays = newDateTime.dayOfMonth().getMaximumValue();

    // to handle the month which has less than 31 days
    if (dayOfMonth > maximumValueOfDays) {
      newDateTime = newDateTime.dayOfMonth().withMaximumValue();
    } else {
      newDateTime = newDateTime.withDayOfMonth(dayOfMonth);
    }
    return newDateTime;
  }


问:
F# List.exists on two lists
I have two lists listA and listB where I want to return true if listB contains any element also in listA.

```<code>let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]
</code>```

Should return true in this case. I feel like this should be easy to solve and I'm missing something fundamental somewhere.

For example, why can't I do like this?

```<code>let testIntersect = for elem in listA do List.exists (fun x -> x = elem) listB
</code>```

答:
```<code>let testIntersect listA listB =
    (Set.ofList listA) - (Set.ofList listB) |> Set.isEmpty |> not
</code>```

Title: F# List.exists on two lists

Body:
I have two lists listA and listB where I want to return true if listB contains any element also in listA.

let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]

Should return true in this case. I feel like this should be easy to solve and I'm missing something fundamental somewhere.

For example, why can't I do like this?

let testIntersect = for elem in listA do List.exists (fun x -> x = elem) listB


问:
I need help making a discord bot direct message someone on typing a command
I am currently trying to create a discord bot and am stumped on a command i am trying to make it do. The command is supposed to be a secret DM message sent by the bot. I was wondering if there was anyway to do this? the command is supposed to look like this:

/dm @PLAYER#000 [message_goes_here]

Pleas help!!

答:
Let's do this step by step:

If the @Player#0000 is a mention, you can get Player#0000's User Object using msg.mentions[0]. Now on to sending that User a message:

Firstly you'll need to separate the message from the command:
Using msg.toString() you'll be able to grab the message with the mention being turned into <@ID>, which will also account for spaces in usernames. Now split the message using msg.toString().split(' '), shift() it twice, join(' ') it and you'll have the message.

Using User.send() you will be able to message that user.

Here's how the final result will look:

```<code>bot.on('message', message => {
    if (message.content.startsWith('/dm ') && message.mentions.users.size) {
        var v=message.toString().split(' ').shift().shift().join(' ') // Takes the DM content from the message
        var member=message.mentions.users[0] // The mentioned user
        member.send(v) // send that user a DM
    }
})
</code>```

Note that this example doesn't really cover errors (in case the message doesn't send, etc.)

Body:
Let's do this step by step:

If the @Player#0000 is a mention, you can get Player#0000's User Object using msg.mentions[0]. Now on to sending that User a message:

Firstly you'll need to separate the message from the command:
Using msg.toString() you'll be able to grab the message with the mention being turned into <@ID>, which will also account for spaces in usernames. Now split the message using msg.toString().split(' '), shift() it twice, join(' ') it and you'll have the message.

Using User.send() you will be able to message that user.

Here's how the final result will look:

bot.on('message', message => {
    if (message.content.startsWith('/dm ') && message.mentions.users.size) {
        var v=message.toString().split(' ').shift().shift().join(' ') // Takes the DM content from the message
        var member=message.mentions.users[0] // The mentioned user
        member.send(v) // send that user a DM
    }
})

Note that this example doesn't really cover errors (in case the message doesn't send, etc.)


问:
Global provider configurable once
I am trying to make a config service that can be given an environment value which it then uses to spit back appropriate config values.

Something like this

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class ConfigService {
private env: string;

SetEnv(value: string) {
    this.env = value;
}

Get() {
    let rtrn;

    if (this.env == "DEV") {
        rtrn = {
            api: "http://localhost:60517/api/"
        }
    }
    else if (this.env == "TEST") {
        rtrn = {
            api: "http://test:60517/api/"
        }
    }
    else { }

    return (rtrn);
}
}
</code>```

Followed by this in app.module.ts

```<code>providers: [
    ConfigService.SetEnv("DEV"),
    ....
]
</code>```

And then used on the following manner after being injected into a component
ConfigService.Get().api

The above example throws an error: app.module.ts:64 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_12__services_config_config_service__.a.SetEnv is not a function

Something along those lines...but I welcome other suggestions to accomplish this.

答:
I didn't know how to do this when I built my app, but if I were starting today, here is how I would solve your problem:

Have a configuration file that exports the configuration you select, along with a common interface. Let's call it config.ts:

```<code>import { InjectionToken } from '@angular/core';
export interface IConfig {
  api:string,
  env?:string
};
const DEV_CONFIG:IConfig = {
  api:'http://dev.endpoint.com',
  env:'DEV'
};
const TEST_CONFIG:IConfig = {
  api:'http://test.endpoint.com',
  env:'TEST'
};
export const CONFIG_TOKEN = new InjectionToken<IConfig>('config.token');
export const CONFIG_PROVIDER = {
  provide:CONFIG_TOKEN,
  useValue:TEST_CONFIG // <- choose the configuration here
}
</code>```

Add the exported provider to your module's providers array:

```<code>providers: [CONFIG_PROVIDER]
</code>```

Finally, in your component, you inject the configuration this way:

```<code>export class AppComponent {
  config:IConfig;

  // Inject is imported from @angular/core
  constructor(@Inject(CONFIG_TOKEN)config:IConfig){
    this.config = config;
    }
}
</code>```

Now you have access to the configuration in your component.

See the docs

Live demo

Title: Global provider configurable once

Body:
I am trying to make a config service that can be given an environment value which it then uses to spit back appropriate config values.

Something like this

import { Injectable } from '@angular/core';

@Injectable()
export class ConfigService {
private env: string;

SetEnv(value: string) {
    this.env = value;
}

Get() {
    let rtrn;

    if (this.env == "DEV") {
        rtrn = {
            api: "http://localhost:60517/api/"
        }
    }
    else if (this.env == "TEST") {
        rtrn = {
            api: "http://test:60517/api/"
        }
    }
    else { }

    return (rtrn);
}
}

Followed by this in app.module.ts

providers: [
    ConfigService.SetEnv("DEV"),
    ....
]

And then used on the following manner after being injected into a component
ConfigService.Get().api

The above example throws an error: app.module.ts:64 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_12__services_config_config_service__.a.SetEnv is not a function

Something along those lines...but I welcome other suggestions to accomplish this.

Body:
I didn't know how to do this when I built my app, but if I were starting today, here is how I would solve your problem:

Have a configuration file that exports the configuration you select, along with a common interface. Let's call it config.ts:

import { InjectionToken } from '@angular/core';
export interface IConfig {
  api:string,
  env?:string
};
const DEV_CONFIG:IConfig = {
  api:'http://dev.endpoint.com',
  env:'DEV'
};
const TEST_CONFIG:IConfig = {
  api:'http://test.endpoint.com',
  env:'TEST'
};
export const CONFIG_TOKEN = new InjectionToken<IConfig>('config.token');
export const CONFIG_PROVIDER = {
  provide:CONFIG_TOKEN,
  useValue:TEST_CONFIG // <- choose the configuration here
}

Add the exported provider to your module's providers array:

providers: [CONFIG_PROVIDER]

Finally, in your component, you inject the configuration this way:

export class AppComponent {
  config:IConfig;

  // Inject is imported from @angular/core
  constructor(@Inject(CONFIG_TOKEN)config:IConfig){
    this.config = config;
    }
}

Now you have access to the configuration in your component.

See the docs

Live demo


问:
Git Reset local repository after hard push to remote
We have a continuous integration build process pointed at a source git repository. When the process runs the CI process pushes its output into a releases repository. My question revolves around the following scenario.

Our CI server builds from source and pushes the results to our releases repository.

A developer checks out the releases repository, adds a schema change script (that isn't added by our CI process), then amends the previous commit and does a force push operation (in order to not add another commit as a result of just adding a script).

The next time the CI process runs and tries to push its output we get the following error "Updates were rejected because the tip of your current branch is behind its remote counterpart."

What I would like to do is tell the CI server to reset the local repository match exactly the remote repo. I've looked at several similar problems and they all say to run the following commands (or very similar).

git fetch --all

git reset --hard [remote repository]

Even after running those commands prior to the build process, I still get the same error. Any ideas on what I should do? Or if what I want to do is even possible.

答:
So it seems that I was potentially resetting the wrong repository. I have changed the commands to do the following (with the last step potentially being unnecessary)

```<code>git fetch --all
git reset --hard @{u}
git pull
</code>```

The @{u} tells git to reset whatever branch is currently checked out, thus eliminating the need to specify the branch manually (which I must have been doing wrong).

One additional item of interest. If you are running the commands in a power shell script (how our CI server runs these actions) you have to write the git reset as follows (as the curly braces cause parse errors).

```<code>git reset --hard "@{u}"
</code>```

Body:
So it seems that I was potentially resetting the wrong repository. I have changed the commands to do the following (with the last step potentially being unnecessary)

git fetch --all
git reset --hard @{u}
git pull

The @{u} tells git to reset whatever branch is currently checked out, thus eliminating the need to specify the branch manually (which I must have been doing wrong).

One additional item of interest. If you are running the commands in a power shell script (how our CI server runs these actions) you have to write the git reset as follows (as the curly braces cause parse errors).

git reset --hard "@{u}"


问:
Retrofit + OkHTTP with EBay's Inventory API
I'm trying to execute the following two requests using EBay's Inventory API:

POST:  bulkUpdatePriceQuantity (create new listing)

PUT:  createOrReplaceInventoryItem (update price/quantity of listing) using

I'm fairly new to Retrofit and OKHTTP and was wondering if someone could post a simple example of how to create a new listing and update price/quantity of an existing listing.

I've spent a couple of days reading about Retrofit and OKHTTP and it seems very confusing. Like I don't understand where/how to add the EBay authorization token and how to pass the data to EBay (such as the new price/quantity or the details of a new listing).

So far this is what I've come up with for Retrofit:

```<code>public interface RetrofitEBaySellAPIService {

@Headers("X-EBAY-C-PACKED-EXAMPLE:   Authorization: Bearer <TOKEN_GOES_HERE>")
@POST("/bulk_update_price_quantity")
// https://api.ebay.com/sell/inventory/v1/bulk_update_price_quantity
Call<List<Task>> getTasks();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.ebay.com/sell/inventory/v1/")
        .addConverterFactory(GsonConverterFactory.create()) // error: GsonConverterFactory cannot be resolved
        .build();

RetrofitEBaySellAPIService service = retrofit.create(RetrofitEBaySellAPIService.class);

Response response = service.getClientList("").execute();

}
</code>```

And this is what I've come up with for OKHTTP:

```<code>public class OKHTTPPostExample  {

public OKHTTPPostExample()
{
}

public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

 public String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    String header = "Authorization: Bearer <TOKEN_GOES_HERE?>";
    Headers headerbuild = Headers.of(header);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .headers(headerbuild)
            .build();

    try (Response response = client.newCall(request).execute()) {

        return response.body().string();

    }
}

 public String revisePriceAndQuantity(String sku) {
    return "{
        'requests' : [
        {
        'sku' : 'SKU_STRING',
        "shipToLocationAvailability" :
        {
        'quantity' : 'integer'
        }";

}

}
</code>```

However, in both cases I'm getting numerous errors. I've read about both technologies for hours (my head is spinning) but I do not understand it clearly.

If someone could post a simple example of how to do both of these operations I would greatly appreciate it.

答:
Unfortunately I don't have developer account to check that it actually works but here is an example of bulkUpdatePriceQuantity

```<code>package example;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.HeaderMap;
import retrofit2.http.POST;

public class Runner {

    //DTOs
    public static class Offer {
        public Integer availableQuantity;
        public String offerId;
        public Price price;
    }

    public static class ShipToLocationAvailability {
        public Integer quantity;
    }

    public static class Price {
        public String currency;
        public String value;
    }

    public static class Request {
        public List<Offer> offers = null;
        public ShipToLocationAvailability shipToLocationAvailability;
        public String sku;
    }

    public static class Response {

        public String offerId;
        public String sku;
        public Integer statusCode;

    }

    public static class RequestBody{
        public List<Request> requests;
    }

    public static class ResponseBody{
        public List<Response> responses;
    }

    //api interface
    public static interface RetrofitEBaySellAPIService {

        @POST("/bulk_update_price_quantity")
        Call<ResponseBody> bulkUpdatePriceQuantity(@HeaderMap Map<String, String> headers, @Body RequestBody object);
    }

    //entry point
    public static void main(String[] args) throws IOException {
        /**
         * request should be initialized.
         * you can do it by creating all necessary objects manually
         * or by deserializing the object from json like this
         * RequestBody request = new Gson().fromJson(jsonString, RequestBody.class);
         *
         * where jsonString is a string that contains json representation of your request body
         *
         */
        RequestBody request = null;

        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.ebay.com/sell/inventory/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitEBaySellAPIService service = retrofit.create(RetrofitEBaySellAPIService.class);
        Map<String, String> headers = new HashMap<>();
        //token should hold a valid active token
        String token = null;
        //put all the headers you need in that map
        headers.put("Authorization", "Bearer " + token);
        ResponseBody response = service.bulkUpdatePriceQuantity(headers, request).execute().body();

    }

}
</code>```

You need to have converter-gson, gson and retrofit in your classpath

Here is a fragment from my pom.xml

```<code>    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>converter-gson</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>retrofit</artifactId>
        <version>2.3.0</version>
    </dependency>
</code>```

Hope it helps

Body:
I'm trying to execute the following two requests using EBay's Inventory API:

POST:  bulkUpdatePriceQuantity (create new listing)

PUT:  createOrReplaceInventoryItem (update price/quantity of listing) using

I'm fairly new to Retrofit and OKHTTP and was wondering if someone could post a simple example of how to create a new listing and update price/quantity of an existing listing.

I've spent a couple of days reading about Retrofit and OKHTTP and it seems very confusing. Like I don't understand where/how to add the EBay authorization token and how to pass the data to EBay (such as the new price/quantity or the details of a new listing).

So far this is what I've come up with for Retrofit:

public interface RetrofitEBaySellAPIService {

@Headers("X-EBAY-C-PACKED-EXAMPLE:   Authorization: Bearer <TOKEN_GOES_HERE>")
@POST("/bulk_update_price_quantity")
// https://api.ebay.com/sell/inventory/v1/bulk_update_price_quantity
Call<List<Task>> getTasks();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.ebay.com/sell/inventory/v1/")
        .addConverterFactory(GsonConverterFactory.create()) // error: GsonConverterFactory cannot be resolved
        .build();

RetrofitEBaySellAPIService service = retrofit.create(RetrofitEBaySellAPIService.class);

Response response = service.getClientList("").execute();

}

And this is what I've come up with for OKHTTP:

public class OKHTTPPostExample  {

public OKHTTPPostExample()
{
}

public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

 public String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    String header = "Authorization: Bearer <TOKEN_GOES_HERE?>";
    Headers headerbuild = Headers.of(header);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .headers(headerbuild)
            .build();

    try (Response response = client.newCall(request).execute()) {

        return response.body().string();

    }
}

 public String revisePriceAndQuantity(String sku) {
    return "{
        'requests' : [
        {
        'sku' : 'SKU_STRING',
        "shipToLocationAvailability" :
        {
        'quantity' : 'integer'
        }";

}

}

However, in both cases I'm getting numerous errors. I've read about both technologies for hours (my head is spinning) but I do not understand it clearly.

If someone could post a simple example of how to do both of these operations I would greatly appreciate it.

Body:
Unfortunately I don't have developer account to check that it actually works but here is an example of bulkUpdatePriceQuantity

package example;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.HeaderMap;
import retrofit2.http.POST;

public class Runner {

    //DTOs
    public static class Offer {
        public Integer availableQuantity;
        public String offerId;
        public Price price;
    }

    public static class ShipToLocationAvailability {
        public Integer quantity;
    }

    public static class Price {
        public String currency;
        public String value;
    }

    public static class Request {
        public List<Offer> offers = null;
        public ShipToLocationAvailability shipToLocationAvailability;
        public String sku;
    }

    public static class Response {

        public String offerId;
        public String sku;
        public Integer statusCode;

    }

    public static class RequestBody{
        public List<Request> requests;
    }

    public static class ResponseBody{
        public List<Response> responses;
    }

    //api interface
    public static interface RetrofitEBaySellAPIService {

        @POST("/bulk_update_price_quantity")
        Call<ResponseBody> bulkUpdatePriceQuantity(@HeaderMap Map<String, String> headers, @Body RequestBody object);
    }

    //entry point
    public static void main(String[] args) throws IOException {
        /**
         * request should be initialized.
         * you can do it by creating all necessary objects manually
         * or by deserializing the object from json like this
         * RequestBody request = new Gson().fromJson(jsonString, RequestBody.class);
         *
         * where jsonString is a string that contains json representation of your request body
         *
         */
        RequestBody request = null;

        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.ebay.com/sell/inventory/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitEBaySellAPIService service = retrofit.create(RetrofitEBaySellAPIService.class);
        Map<String, String> headers = new HashMap<>();
        //token should hold a valid active token
        String token = null;
        //put all the headers you need in that map
        headers.put("Authorization", "Bearer " + token);
        ResponseBody response = service.bulkUpdatePriceQuantity(headers, request).execute().body();

    }

}

You need to have converter-gson, gson and retrofit in your classpath

Here is a fragment from my pom.xml

    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>converter-gson</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.retrofit2</groupId>
        <artifactId>retrofit</artifactId>
        <version>2.3.0</version>
    </dependency>

Hope it helps


问:
Minimax code for tic-tac-toe in python
I've been trying to code a tic-tac-toe game but I'm facing a problem. For example if I put a cross on one of the corners, the bot should mark "O" in the centre but that doesn't happen. Instead, it marks it on adjacent to the cross. The bot is not choosing the right value on the matrix. Any help would be appreciated.
PS: The first player is always human while the second player is the bot.
Here's the code:</p>

```<code>import re
current_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
current_game = list(" | | \n_|_|_\n | | \n_|_|_\n | | \n | | \n")

def draw1():
    for i in range(9):
        if(i<3 and i>=0):
            current_game[2*i]=current_board[i]
        elif(i<6 and i>=3):
            current_game[2*(i-3)+12]=current_board[i]
        elif(i<9 and i>=6):
            current_game[2*(i-6)+24]=current_board[i]
    print "".join(current_game)

def win(board, depth):
    board="".join(board)
    regex1 = [r"XXX......", r"...XXX...", r"......XXX", r"X..X..X..", r".X..X..X.", r"..X..X..X", r"X...X...X", r"..X.X.X.."]
    for i in regex1:
        if bool(re.search(i, board)):
            return -10+depth
    regex2 = [r"OOO......", r"...OOO...", r"......OOO", r"O..O..O..", r".O..O..O.", r"..O..O..O", r"O...O...O", r"..O.O.O.."]
    for i in regex2:
        if bool(re.search(i, board)):
            return 10-depth

def draw(board):
    for i in board:
        if i==" ":
            return False
    return True

def assigning_values_to_a_move(board, isOplaying, depth):
    scorelist=[]
    if win(board, depth)==10-depth:
        return 10-depth
    elif win(board, depth)==-10+depth:
        return -10+depth
    elif draw(board):
        return 0
    else:
        if(isOplaying):
            for i in range(len(board)):
                if board[i]==" ":
                    board[i]="O"
                    scorelist.append(assigning_values_to_a_move(board, not isOplaying, depth+1))
                    board[i]=" "
            return max(scorelist)
        else:
            for i in range(len(board)):
                if board[i]==" ":
                    board[i]="X"
                    scorelist.append(assigning_values_to_a_move(board, isOplaying, depth+1))
                    board[i]=" "
            return min(scorelist)

def choosing_the_move(board, depth):
    current_value=-1000
    best_value=-1000
    best_index=-1
    for i in range(9):
        if board[i]==" ":
            board[i]="O"
            current_value=assigning_values_to_a_move(board, False, depth)
            if(current_value>best_value):
                best_value=current_value
                best_index=i
            board[i]=" "
    return best_index

for i in range(9):
    if i%2==0:
        y=int(raw_input())
        current_board[y]="X"
        draw1()
    else:
        current_board[choosing_the_move(current_board,i+1)]="O"
        draw1()
</code>```

答:
Tobias, It's a good start, but your algorithm is searching for the fewest moves for a win, correct?  The fewest moves will occur when the player (X) makes poor choices.

For example, if the board looks like this.

```<code>O|X|X
O| |X
 | |
</code>```

I'd suggest you weight the positions based on the number of ways to win.

```<code>weights = [3,2,3,
           2,4,2,
           3,2,3]
</code>```

Then calculate a move resulting in a win based on greatest weight.

Title: Minimax code for tic-tac-toe in python

Body:
I've been trying to code a tic-tac-toe game but I'm facing a problem. For example if I put a cross on one of the corners, the bot should mark "O" in the centre but that doesn't happen. Instead, it marks it on adjacent to the cross. The bot is not choosing the right value on the matrix. Any help would be appreciated.
PS: The first player is always human while the second player is the bot.
Here's the code:

import re
current_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
current_game = list(" | | \n_|_|_\n | | \n_|_|_\n | | \n | | \n")

def draw1():
    for i in range(9):
        if(i<3 and i>=0):
            current_game[2*i]=current_board[i]
        elif(i<6 and i>=3):
            current_game[2*(i-3)+12]=current_board[i]
        elif(i<9 and i>=6):
            current_game[2*(i-6)+24]=current_board[i]
    print "".join(current_game)

def win(board, depth):
    board="".join(board)
    regex1 = [r"XXX......", r"...XXX...", r"......XXX", r"X..X..X..", r".X..X..X.", r"..X..X..X", r"X...X...X", r"..X.X.X.."]
    for i in regex1:
        if bool(re.search(i, board)):
            return -10+depth
    regex2 = [r"OOO......", r"...OOO...", r"......OOO", r"O..O..O..", r".O..O..O.", r"..O..O..O", r"O...O...O", r"..O.O.O.."]
    for i in regex2:
        if bool(re.search(i, board)):
            return 10-depth

def draw(board):
    for i in board:
        if i==" ":
            return False
    return True

def assigning_values_to_a_move(board, isOplaying, depth):
    scorelist=[]
    if win(board, depth)==10-depth:
        return 10-depth
    elif win(board, depth)==-10+depth:
        return -10+depth
    elif draw(board):
        return 0
    else:
        if(isOplaying):
            for i in range(len(board)):
                if board[i]==" ":
                    board[i]="O"
                    scorelist.append(assigning_values_to_a_move(board, not isOplaying, depth+1))
                    board[i]=" "
            return max(scorelist)
        else:
            for i in range(len(board)):
                if board[i]==" ":
                    board[i]="X"
                    scorelist.append(assigning_values_to_a_move(board, isOplaying, depth+1))
                    board[i]=" "
            return min(scorelist)

def choosing_the_move(board, depth):
    current_value=-1000
    best_value=-1000
    best_index=-1
    for i in range(9):
        if board[i]==" ":
            board[i]="O"
            current_value=assigning_values_to_a_move(board, False, depth)
            if(current_value>best_value):
                best_value=current_value
                best_index=i
            board[i]=" "
    return best_index

for i in range(9):
    if i%2==0:
        y=int(raw_input())
        current_board[y]="X"
        draw1()
    else:
        current_board[choosing_the_move(current_board,i+1)]="O"
        draw1()

Body:
Tobias, It's a good start, but your algorithm is searching for the fewest moves for a win, correct?  The fewest moves will occur when the player (X) makes poor choices.

For example, if the board looks like this.

O|X|X
O| |X
 | |

I'd suggest you weight the positions based on the number of ways to win.

weights = [3,2,3,
           2,4,2,
           3,2,3]

Then calculate a move resulting in a win based on greatest weight.


问:
jQuery to add Browser-Name into css-class
I'm using jQuery to detect the Users Browser-Agent and than add the browser-name as a css-class to the body. This works like magic with webkit and mozilla … but with msie it fails — but don't know why. For msie i also have to add not only the «msie», but also one class with the version-number of the used msie (like «msie7» or «msie8»).

Everything works, only the msie-section does not!

my (full) jQuery-Code:

```<code>    <script type="text/javascript">
<!--
(function($){
    $(function(){

        var $copy = $('div.SPA_printcontact').clone();
        var $body = $('body');

        $copy.insertAfter('#printdate');

        if($.browser.msie) {
            $body.addClass('msie')
            var userAgent = userAgent.substring(0,userAgent.indexOf('.'));
            var version = userAgent;
            $body.addClass('msie' + version)
        }
        if($.browser.webkit) {
            $body.addClass('webkit')
        }
        if($.browser.mozilla) {
            $body.addClass('mozilla')
        }

    });
}(jQuery));
-->
</script>
</code>```

答: Please try using $('body').addClass() if that does not work, then try $('body').attr("class",msie+version).</p>

ContentLicense: CC BY-SA 2.5


答:
You can not call methods from providers into the app.module: This is wrong.

```<code>providers: [
ConfigService.SetEnv("DEV"),
....
 ]
</code>```

If you want to set env,then set it from your component where you are injecting this service. And look at the above answer, it must give you the solution which you are looking for.

Let me know, if this solves your problem.

Title: Global provider configurable once

Body:
You can not call methods from providers into the app.module: This is wrong.

providers: [
ConfigService.SetEnv("DEV"),
....
 ]

If you want to set env,then set it from your component where you are injecting this service. And look at the above answer, it must give you the solution which you are looking for.

Let me know, if this solves your problem.


问:
How to hide foreign key elements from tables in SQL Developer Data Modeler?
For example, I have two tables UNIT_OF_MEASUREMENT and PHYSICAL_QUANTITY. PHYSICAL_QUANTITY has a field what represents foreign key of UNIT_OF_MEASUREMENT table. When i add this relationship, PHYSICAL_QUANTITY_UNIT_OF_MEASUREMENT_FK at PHYSICAL_QUANTITY table is shown. How can i hide this element (not relationship) from table?

There is way to hide primary key elements from table. Just Right-click at table -> select "Show / Hide elements" -> select elements that must be hidden and click "OK".

But PHYSICAL_QUANTITY_UNIT_OF_MEASUREMENT_FK element is not shown there.
Why? And is there a way to hide PHYSICAL_QUANTITY_UNIT_OF_MEASUREMENT_FK element from table? Thanks.

答: You can select the elements that you need to be shown by right clicking on the diagram (not in the tables), and selecting the ones you need in View Details


问:
Grails 3 change default service scope
In grails 3, the default service scope is Singleton, the documents show it's easy to override this by defining

```<code>static scope='request'
</code>```

in the service class.  Is it possible to change the default service scope for an application similar to the way it is done for controllers in application.groovy?

The specific issue is a Service class in a plugin is calling application services (which are designed around request scope).  This was working in grails 2, but with the upgrade to grails 3 it no longer does.

答:
Is it possible to change the default scope for an application similar
  to the way it is done for controllers in application.groovy?

There is no direct support for that, no.  You could write a bean definition post processor that could impose that change.

Title: Grails 3 change default service scope

Body:
In grails 3, the default service scope is Singleton, the documents show it's easy to override this by defining

static scope='request'

in the service class.  Is it possible to change the default service scope for an application similar to the way it is done for controllers in application.groovy?

The specific issue is a Service class in a plugin is calling application services (which are designed around request scope).  This was working in grails 2, but with the upgrade to grails 3 it no longer does.


问:
Is there any object-oriented approach or pattern to work with tabular data?
Required operations with tabular data:

Switch columns with rows

Adding columns/rows at specific places

Mark columns/rows/cells as belonging to the same group and fetch specific group

Change column/rows order

Calculate totals to rows/columns

Transform to pivot table

Output result as HTML/JSON

What would be a good object-oriented approach to work with tabular data?

答:
I think the first thing that is needed here is a good / appropriate data structure to keep / manipulate the table data.
That depends on specific requirements you can have, such as size of the table, performance requirements, etc.

Let's assume you will use some Matrix class which provides low-level operations over table (set cell value, add/remove row, transpose, etc).

This class will operate with basic data structures, for example, it may have get_row method which will return a list of numbers.
Now we can, for example, get the summary of values in this list, but we can't just change some list item and have this change reflected in the parent Matrix (the row data is disconnected from the parent matrix structure).

Now we can build our structure upon this Matrix class, our two targets are:

1) make it more convenient for the user, some of the "conveniences" can be:

row, column and cell objects all connected to the parent Table object (if we modify the row item, it will be reflected in the parent table and other row / column / cell obejcts).

we can generate different views of the same data (such as pivot tables)

we can use special column/row addressing system (such as using 1, 2, 3, ... for rows and A, B, C, ... for columns)

2) hide the actual data structure we use to store the table data

this way we can work on Matrix implementation independently without breaking user code

we can even replace it with different structure (maybe we find something that is faster or something that takes less memory), or we can have different implementations for different situations (for example for desktop and mobile apps)

This is the approximate classes structure I would start with (python-like pseudo code):

```<code>class Matrix:
    """The base data structure, implementation detail."""

    get_cell(int x, int y):
        """Returns cell value by x/y column and row indexes."""

    set_cell(int x, int y, value):
        """Sets cell value by x/y column and row indexes."""

    get_row(int index) -> list:
        """Returns `list` of values in the `index` row."""

    get_column(int index) -> list;
     """Returns `list` of values in the `index` column."""
</code>```

The Matrix class is a low level data structure and it should not be a part of a public interface.

The public interface is represented by Table class and other related classes below:

```<code>class Table:
    """The user-level interface to work with table data."""

    constructor():
        """Initializes Matrix object."""
        # The "_data" object is private, only to be used internally.
        self._data = Matrix()

    row(int number) -> Row:
        """Returns `Row` object by row number (1, 2, 3, ...)."""
        row = Row(self, number)
        self.attach(row)
        return row

    column(string name) -> Column:
        """Returns `Column` object by string name (A, B, C, ...)."""
        column = Column(self, name)
        self.attach(column)
        return column

    cell(int row_number, string col_name) -> Cell:
        """Returns `Cell` object by string name (A, B, C, ...)."""
        cell = Cell(self, row_number, col_name)
        self.attach(cell)
        return column

    attach(Observer observer):
        """Register an observer to be notified when Table state was changed."""
        self.observers.append(observer)

    _notify():
        """Notify all dependent objects about the state change."""
        for observer in self.observers:
            observer.update()

    ...
</code>```

To keep Table and Row / Column / Cell objects in-sync we can use the Observer pattern.

Here the Table is a Subject and Row / Column / Cell are Observers.
Once the state of the Table (and underlying data) is changed, we can update all dependent objects.

```<code>class Row(Observable):
    """Table row object."""

    constructor(Table parent, int index):
        self.parent = parent
        self.index = index
        self._data = None
        self.update()

    update()
        """Update row data.

        Fetches the `list` or row values from the `Matrix` object.
        """
        # Note: we have two choices here - the `Row`, `Column` and `Cell` objects
        # can either access `Table._data` property directly, or `Table` can provide
        # proxy methods to modify the data (like `_get_value(x, y)`); in both cases
        # there is a private interface to work with data used by `Table`, `Row`,
        # `Column` and `Cell` classes and the implementation depends on the language,
        # in C++ these classes can be friends, in python this can be just a documented
        # agreement on how these classes should work.
        # See also the comment in the `remove` method below.
        self._data = parent._data.get_row(index)

    sum():
        """Returns sum of row items."""
        sum = 0
        for value in self._data:
            sum += value
        return sum

    cell(string col_name):
        """Returns cell object."""
        return parent.cell(self.index, col_name)

    remove():
        """Removes current row."""
        # Here we access `parent._data` directly, so we also have to
        # call `parent._notify` here to update other objects.
        # An alternative would be a set of proxy methods in the `Table` class
        # which would modify the data and then call the `_notify` method, in such case
        # we would have something like `self.parent._remove_row(self.index)` here.
        self.parent._data.remove_row(self.index)
        self.parent._notify()
        self.parent.detach(self)
</code>```

The Column and Cell classes are similar, the Column will hold the column data and the Cell will wrap the cell value.
The user-level usage can look like be this:

```<code>table = Table()
# Update table data
table.cell(1, "A").set(10)
table.cell(1, "B").set(20)
table.row(1).cell("C").set(30)
# Get row sum
sum = table.row(1).sum()

# Get the table row
row = table.row(1)
# The `remove` operation removes the row from the table and `detaches` it,
# so it will no longer observe the `table` changes.
row.remove()
# Now we have the detached row and we can put it into another table,
# so basically we cut-and-pasted the row from one table to another
another_table.add_row(row)
</code>```

Using this approach you can quite easily implement such operations as copy, cut, paste. Also you can apply Command pattern here and extract these operations into small classes. This way it will also be quite easy to implement undo and redo.

The PivotTable table can also be a special kind of Observable.
Depending on the requirements to the features for the pivot table, you may find Builder pattern useful to configure the pivot table.
Something like this:

```<code>pivotBuilder = PivotBuilder(table)
# Group by column "A" and use `SumAggregator` to aggregate grouped values.
pivotBuilder.group_by_column("A", SumArggregator())  # or maybe pivotBuilder.groupBy(table.column("A"))
pivotTable := pivotBuilder.get_result()
</code>```

The classes to export table to different formats probably don't have to be observable, so they'll just wrap the Table object and transform it to the appropriate format:

```<code>json_table = JsonTable(table)
data = json_table.export()
</code>```

Of course, the above is just one of many possible implementation options, treat them as some ideas that can be useful (or not useful) depending on specific requirements you have.

You may find more ideas in the GoF patterns book.

Body:
I think the first thing that is needed here is a good / appropriate data structure to keep / manipulate the table data.
That depends on specific requirements you can have, such as size of the table, performance requirements, etc.

Let's assume you will use some Matrix class which provides low-level operations over table (set cell value, add/remove row, transpose, etc).

This class will operate with basic data structures, for example, it may have get_row method which will return a list of numbers.
Now we can, for example, get the summary of values in this list, but we can't just change some list item and have this change reflected in the parent Matrix (the row data is disconnected from the parent matrix structure).

Now we can build our structure upon this Matrix class, our two targets are:

1) make it more convenient for the user, some of the "conveniences" can be:

row, column and cell objects all connected to the parent Table object (if we modify the row item, it will be reflected in the parent table and other row / column / cell obejcts).

we can generate different views of the same data (such as pivot tables)

we can use special column/row addressing system (such as using 1, 2, 3, ... for rows and A, B, C, ... for columns)

2) hide the actual data structure we use to store the table data

this way we can work on Matrix implementation independently without breaking user code

we can even replace it with different structure (maybe we find something that is faster or something that takes less memory), or we can have different implementations for different situations (for example for desktop and mobile apps)

This is the approximate classes structure I would start with (python-like pseudo code):

class Matrix:
    """The base data structure, implementation detail."""

    get_cell(int x, int y):
        """Returns cell value by x/y column and row indexes."""

    set_cell(int x, int y, value):
        """Sets cell value by x/y column and row indexes."""

    get_row(int index) -> list:
        """Returns `list` of values in the `index` row."""

    get_column(int index) -> list;
     """Returns `list` of values in the `index` column."""

The Matrix class is a low level data structure and it should not be a part of a public interface.

The public interface is represented by Table class and other related classes below:

class Table:
    """The user-level interface to work with table data."""

    constructor():
        """Initializes Matrix object."""
        # The "_data" object is private, only to be used internally.
        self._data = Matrix()

    row(int number) -> Row:
        """Returns `Row` object by row number (1, 2, 3, ...)."""
        row = Row(self, number)
        self.attach(row)
        return row

    column(string name) -> Column:
        """Returns `Column` object by string name (A, B, C, ...)."""
        column = Column(self, name)
        self.attach(column)
        return column

    cell(int row_number, string col_name) -> Cell:
        """Returns `Cell` object by string name (A, B, C, ...)."""
        cell = Cell(self, row_number, col_name)
        self.attach(cell)
        return column

    attach(Observer observer):
        """Register an observer to be notified when Table state was changed."""
        self.observers.append(observer)

    _notify():
        """Notify all dependent objects about the state change."""
        for observer in self.observers:
            observer.update()

    ...

To keep Table and Row / Column / Cell objects in-sync we can use the Observer pattern.

Here the Table is a Subject and Row / Column / Cell are Observers.
Once the state of the Table (and underlying data) is changed, we can update all dependent objects.

class Row(Observable):
    """Table row object."""

    constructor(Table parent, int index):
        self.parent = parent
        self.index = index
        self._data = None
        self.update()

    update()
        """Update row data.

        Fetches the `list` or row values from the `Matrix` object.
        """
        # Note: we have two choices here - the `Row`, `Column` and `Cell` objects
        # can either access `Table._data` property directly, or `Table` can provide
        # proxy methods to modify the data (like `_get_value(x, y)`); in both cases
        # there is a private interface to work with data used by `Table`, `Row`,
        # `Column` and `Cell` classes and the implementation depends on the language,
        # in C++ these classes can be friends, in python this can be just a documented
        # agreement on how these classes should work.
        # See also the comment in the `remove` method below.
        self._data = parent._data.get_row(index)

    sum():
        """Returns sum of row items."""
        sum = 0
        for value in self._data:
            sum += value
        return sum

    cell(string col_name):
        """Returns cell object."""
        return parent.cell(self.index, col_name)

    remove():
        """Removes current row."""
        # Here we access `parent._data` directly, so we also have to
        # call `parent._notify` here to update other objects.
        # An alternative would be a set of proxy methods in the `Table` class
        # which would modify the data and then call the `_notify` method, in such case
        # we would have something like `self.parent._remove_row(self.index)` here.
        self.parent._data.remove_row(self.index)
        self.parent._notify()
        self.parent.detach(self)

The Column and Cell classes are similar, the Column will hold the column data and the Cell will wrap the cell value.
The user-level usage can look like be this:

table = Table()
# Update table data
table.cell(1, "A").set(10)
table.cell(1, "B").set(20)
table.row(1).cell("C").set(30)
# Get row sum
sum = table.row(1).sum()

# Get the table row
row = table.row(1)
# The `remove` operation removes the row from the table and `detaches` it,
# so it will no longer observe the `table` changes.
row.remove()
# Now we have the detached row and we can put it into another table,
# so basically we cut-and-pasted the row from one table to another
another_table.add_row(row)

Using this approach you can quite easily implement such operations as copy, cut, paste. Also you can apply Command pattern here and extract these operations into small classes. This way it will also be quite easy to implement undo and redo.

The PivotTable table can also be a special kind of Observable.
Depending on the requirements to the features for the pivot table, you may find Builder pattern useful to configure the pivot table.
Something like this:

pivotBuilder = PivotBuilder(table)
# Group by column "A" and use `SumAggregator` to aggregate grouped values.
pivotBuilder.group_by_column("A", SumArggregator())  # or maybe pivotBuilder.groupBy(table.column("A"))
pivotTable := pivotBuilder.get_result()

The classes to export table to different formats probably don't have to be observable, so they'll just wrap the Table object and transform it to the appropriate format:

json_table = JsonTable(table)
data = json_table.export()

Of course, the above is just one of many possible implementation options, treat them as some ideas that can be useful (or not useful) depending on specific requirements you have.

You may find more ideas in the GoF patterns book.


问:
How can I get VSTS working with private nuget repos which require credentials?
I am trying to set up a CI/CD system and the company has chosen Visual Studio Team Services.

Everything was going well until I noticed my build failing here:

Error:
d:\a_tasks\NuGetInstaller_333b11bd-d341-40d9-afcf-b32d5ce6f23b\0.2.31\node_modules\nuget-task-common\NuGet\3.3.0\NuGet.exe
failed with return code: 1

Packages failed to install

The software project uses Telerik DLL's that are retrieved from a private Telerik nuget repo - which requires credentials to access.

Now obviously there must be a way to tell VSTS in the 'Nuget Restore' build step but I can't find anything online other than create our own hosted company Repo and tell VSTS about it - which isn't helpful because I don't want to host Telerik's own DLL's.

Is there any way to do this or should I move to TeamCity?

答:
The latest version (2.*) of the NuGet task supports both privately NuGet feeds and specifying the credentials for it (see screenshot). You simply need to leverage a NuGet configuration file to achieve this. Read Configure NuGet behavior for more details.

Also note that if you are using a hosted agent, your private NuGet repository must be publicly accessible. Otherwise you will need to run your build agent on the same network as your NuGet server.


问:
20s of PAGEIOLATCH_SH on Azure SQL Database with execution plan of 0.06 subtree cost
(Azure support is giving vague answers, so I'm turning to Stack Overflow with hope! :))

Situation

User complains of timeout errors on a query. I run the same query twice (same parameters) from MSMS. First run takes looong (23s or sometimes 50s), second, third, etc. runs take <1s. Execution Plans are identical and have a subtree cost of 0.0671..

The difference I do notice is a WaitStats section in the first Execution Plan with the following values:

```<code>WaitCount: 2751
WaitTimeMS: 6
WaitType: MEMORY_ALLOCATION_EXT

WaitCount: 2751
WaitTimeMS: 6
WaitType: IO_QUEUE_LIMIT

WaitCount: 669
WaitTimeMS: 20360
WaitType: PAGEIOLATCH_SH
</code>```

Azure SQL DTU is averaging around 5% max.

Azure Support says it's probably the Execution Plan compilation time. I doubt that since clearing the Proc Cache does not reintroduce the long waits after the first run.

The execution plan "leafs" are Index Seek (NonClustedred), Key Lookup (Clustered) and RID Lookup (Heap). The RID Lookup being 39% (of the 0.0671). A single row is returned (i.e. TOP 1).

3 tables are in the query with CROSS APPLY. The biggest one has 8 million rows and contains a ~40KB VARBINARY column (not referenced nor returned anywhere in the query).

Query

```<code>DECLARE @p0 VARCHAR(50); SET @p0 = '<GUID1>'

SELECT TOP 1 p.Id, p.DateCreatedUtc, p.PreviousOwnerId
FROM (
    -- last project save
    SELECT ps.Id AS psId, p.*
    FROM Projects p
    CROSS APPLY (
      SELECT TOP 1 *
      FROM ProjectSaves
      WHERE ProjectId = p.Id
      ORDER BY LastModifiedUtc DESC
    ) AS ps
    WHERE p.OwnerId = @p0
) p
CROSS APPLY (
    SELECT TOP 1 *
    FROM ProjectSavePhotos
    WHERE ProjectSaveId = p.psId AND (name LIKE 'uploads%')
) ps
WHERE P.IsDeleted = 0 AND p.Id NOT IN ('<GUID2>')
ORDER BY p.DateCreatedUtc DESC
</code>```

p.OwnerId is indexed and Azure automatically created two more indexes:

on OwnerId and Id and

on IsDeleted, OwnerId and Id

ps.ProjectId is indexed and includes LastModifiedUtc

psp.ProjectSaveId is indexed and includes name

Question

How can I diagnose the root cause of the 20s PAGEIOLATCH_SH? Could it be the mere presence of the VARBINARY column? If so, how can I confirm that?

References read

https://www.sqlshack.com/handling-excessive-sql-server-pageiolatch_sh-wait-types/

https://sqlperformance.com/2014/06/io-subsystem/knee-jerk-waits-pageiolatch-sh

答:
Any type of data is stored as a page in SQL Server. There are different types of page depending on what the page contains (data, index, etc). See documentation page.

The fundamental unit of data storage in SQL Server is the page. The disk space allocated to a data file (.mdf or .ndf) in a database is logically divided into pages numbered contiguously from 0 to n. Disk I/O operations are performed at the page level. That is, SQL Server reads or writes whole data pages.

When you run a query against your database, the SQL Engine will look in the system memory (buffer) to see if it has all the pages required to execute your query. If some pages are missing, the SQL Engine will load them in memory from the disk.

The PAGEIOLATCH_SH wait corresponds to pages being pulled from disk to memory (buffer). Once pages have been loaded in system memory, they remain there until evicted. This is the reason why the first run of your query takes more time than the subsequent runs. During the first run, the SQL Engine needs to retrieve data from disk. For subsequent run, this is no longer the case.

To reduce the first query wait, there are different strategies. As mentioned by Alberto, if you run this query often, then the pages are less likely to be evicted from the buffer. As mentioned by influent, you can rewrite your query or create new indexes so that the SQL Engine does not have to load so many pages. Please post the query plan for further investigation.

Body:
(Azure support is giving vague answers, so I'm turning to Stack Overflow with hope! :))

Situation

User complains of timeout errors on a query. I run the same query twice (same parameters) from MSMS. First run takes looong (23s or sometimes 50s), second, third, etc. runs take <1s. Execution Plans are identical and have a subtree cost of 0.0671..

The difference I do notice is a WaitStats section in the first Execution Plan with the following values:

WaitCount: 2751
WaitTimeMS: 6
WaitType: MEMORY_ALLOCATION_EXT

WaitCount: 2751
WaitTimeMS: 6
WaitType: IO_QUEUE_LIMIT

WaitCount: 669
WaitTimeMS: 20360
WaitType: PAGEIOLATCH_SH

Azure SQL DTU is averaging around 5% max.

Azure Support says it's probably the Execution Plan compilation time. I doubt that since clearing the Proc Cache does not reintroduce the long waits after the first run.

The execution plan "leafs" are Index Seek (NonClustedred), Key Lookup (Clustered) and RID Lookup (Heap). The RID Lookup being 39% (of the 0.0671). A single row is returned (i.e. TOP 1).

3 tables are in the query with CROSS APPLY. The biggest one has 8 million rows and contains a ~40KB VARBINARY column (not referenced nor returned anywhere in the query).

Query

DECLARE @p0 VARCHAR(50); SET @p0 = '<GUID1>'

SELECT TOP 1 p.Id, p.DateCreatedUtc, p.PreviousOwnerId
FROM (
    -- last project save
    SELECT ps.Id AS psId, p.*
    FROM Projects p
    CROSS APPLY (
      SELECT TOP 1 *
      FROM ProjectSaves
      WHERE ProjectId = p.Id
      ORDER BY LastModifiedUtc DESC
    ) AS ps
    WHERE p.OwnerId = @p0
) p
CROSS APPLY (
    SELECT TOP 1 *
    FROM ProjectSavePhotos
    WHERE ProjectSaveId = p.psId AND (name LIKE 'uploads%')
) ps
WHERE P.IsDeleted = 0 AND p.Id NOT IN ('<GUID2>')
ORDER BY p.DateCreatedUtc DESC

p.OwnerId is indexed and Azure automatically created two more indexes:

on OwnerId and Id and

on IsDeleted, OwnerId and Id

ps.ProjectId is indexed and includes LastModifiedUtc

psp.ProjectSaveId is indexed and includes name

Question

How can I diagnose the root cause of the 20s PAGEIOLATCH_SH? Could it be the mere presence of the VARBINARY column? If so, how can I confirm that?

References read

https://www.sqlshack.com/handling-excessive-sql-server-pageiolatch_sh-wait-types/

https://sqlperformance.com/2014/06/io-subsystem/knee-jerk-waits-pageiolatch-sh


问:
safeUnbox() cannot be inverted
I'm trying to eliminate all the warnings of my Android application and one of them is this:

viewModel.value is a boxed field but needs to be un-boxed to execute android:checked. This may cause NPE so Data Binding will safely unbox it. You can change the expression and explicitly wrap viewModel.value with safeUnbox() to prevent the warning

Where value is a generic ObservableField that comes from a super class:

```<code>public abstract class BaseDataTypeViewModel<T> extends BaseObservable  {
    public final ObservableField<T> value = new ObservableField<>();
    ...
}
</code>```

And is extented somewhere as a Boolean:

```<code>public class CheckBooleanDataTypeViewModel extends BaseDataTypeViewModel<Boolean> {
    ...
}
</code>```

I saw on data binding - safeUnbox warning that the warnings happen because this is a Boolean and not a boolean, so I tried to add this: android:checked="@={safeUnbox(viewModel.value)}" instead of android:checked="@={viewModel.value}" but then I got an error saying I can't invert the safeUnbox() method.

****/ data binding error ****msg:The expression android.databinding.DynamicUtil.safeUnbox(viewModelValue) cannot be inverted: There is no inverse for method safeUnbox, you must add an @InverseMethod annotation to the method to indicate which method should be used when using it in two-way binding expressions

I understand correctly the 2 separated issues, but do I have to live with the warning to avoid the error or is their a solution to avoid both the warning and the error? What about the @InverseMethod it is talking about? I didn't manage to add this annotation because the method comes from the android package.

答:
I haven't worked with Android Architecture Components or with the Data Binding libraries in this particular way, but I think I can still help.

Within your XML, you've got this:

```<code>android:checked="@={viewModel.value}"
</code>```

The system is giving you a warning because it wants you to know that in the case where viewModel.value is null, it's going to do something special (behave as though it were false instead, presumably). It does this via the safeUnbox() method.

To solve the warning, it's suggesting making the safeUnbox() call explicit. You can't do that because there's no "inverse" of safeUnbox() to go back from boolean to Boolean.

But it doesn't sound like you have to use safeUnbox(); you could create your own method that converts Boolean to boolean, and then you could use the suggested annotation to declare which method will convert back from boolean to Boolean.

```<code>public class MyConversions {

    @InverseMethod("myBox")
    public static boolean myUnbox(Boolean b) {
        return (b != null) && b.booleanValue();
    }

    public static Boolean myBox(boolean b) {
        return b ? Boolean.TRUE : Boolean.FALSE;
    }
}
</code>```

Now you can change your XML to:

```<code>android:checked="@={com.example.stackoverflow.MyConversions.myUnbox(viewModel.value)}"
</code>```

I hope this helps. If it turns out that I'm way off-base, let me know; I'd love to learn more about this topic.

Most of what I have in this answer I learned from https://medium.com/google-developers/android-data-binding-inverse-functions-95aab4b11873

Title: safeUnbox() cannot be inverted

Body:
I'm trying to eliminate all the warnings of my Android application and one of them is this:

viewModel.value is a boxed field but needs to be un-boxed to execute android:checked. This may cause NPE so Data Binding will safely unbox it. You can change the expression and explicitly wrap viewModel.value with safeUnbox() to prevent the warning

Where value is a generic ObservableField that comes from a super class:

public abstract class BaseDataTypeViewModel<T> extends BaseObservable  {
    public final ObservableField<T> value = new ObservableField<>();
    ...
}

And is extented somewhere as a Boolean:

public class CheckBooleanDataTypeViewModel extends BaseDataTypeViewModel<Boolean> {
    ...
}

I saw on data binding - safeUnbox warning that the warnings happen because this is a Boolean and not a boolean, so I tried to add this: android:checked="@={safeUnbox(viewModel.value)}" instead of android:checked="@={viewModel.value}" but then I got an error saying I can't invert the safeUnbox() method.

****/ data binding error ****msg:The expression android.databinding.DynamicUtil.safeUnbox(viewModelValue) cannot be inverted: There is no inverse for method safeUnbox, you must add an @InverseMethod annotation to the method to indicate which method should be used when using it in two-way binding expressions

I understand correctly the 2 separated issues, but do I have to live with the warning to avoid the error or is their a solution to avoid both the warning and the error? What about the @InverseMethod it is talking about? I didn't manage to add this annotation because the method comes from the android package.

Body:
I haven't worked with Android Architecture Components or with the Data Binding libraries in this particular way, but I think I can still help.

Within your XML, you've got this:

android:checked="@={viewModel.value}"

The system is giving you a warning because it wants you to know that in the case where viewModel.value is null, it's going to do something special (behave as though it were false instead, presumably). It does this via the safeUnbox() method.

To solve the warning, it's suggesting making the safeUnbox() call explicit. You can't do that because there's no "inverse" of safeUnbox() to go back from boolean to Boolean.

But it doesn't sound like you have to use safeUnbox(); you could create your own method that converts Boolean to boolean, and then you could use the suggested annotation to declare which method will convert back from boolean to Boolean.

public class MyConversions {

    @InverseMethod("myBox")
    public static boolean myUnbox(Boolean b) {
        return (b != null) && b.booleanValue();
    }

    public static Boolean myBox(boolean b) {
        return b ? Boolean.TRUE : Boolean.FALSE;
    }
}

Now you can change your XML to:

android:checked="@={com.example.stackoverflow.MyConversions.myUnbox(viewModel.value)}"

I hope this helps. If it turns out that I'm way off-base, let me know; I'd love to learn more about this topic.

Most of what I have in this answer I learned from https://medium.com/google-developers/android-data-binding-inverse-functions-95aab4b11873


问:
Javascript onmousehover event to connect information
So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first  and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information. </p>

```<code>window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
    xhr = new XMLHttpRequest();
        if(xhr) {
            xhr.addEventListener("readystatechange", ShowFile);
            xhr.open("GET", "plants.xml", true);
            xhr.send();
        } else {
            alert("XHR not supported.");
        }
}
function ShowFile() {
    var i;
    var title;
    var cover;
    var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
        //here we have gotten the file correctly
        //loop through it and print out cover and title
        var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
        //booklist is an array and each element is an object sub i
        //so you have to use getElementBy something in order to pull the information
        for (i = 0; i < plantlist.length; i++) {
            var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
             var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
            plant_table += "<tr>" +
                            "<td class =\"plant\">" + Common + "</td>" +
                            "<td>" + Botanical + "</td>" +
                         "</tr>";
    }
        plant_table += "</table>";
        document.getElementById("outarea").innerHTML = plant_table;
    }
    var plants = document.getElementsByClassName("plant");
    for (i=0; i < plants.length; i++) {
      plants[i].onmouseover = HoverChoice;
    }
    }
function HoverChoice() {
    var input = xhr.responseXML.getElementsByTagName("PLANT");
    for (i = 0; i < input.length; i++) {
            Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
            var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
            var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
           var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
    if (plants == this.innerHTML) {
    document.getElementById("inarea").innerHTML =
    "<h1>" + Common + "</h1>" + "<br />" + "<br />" +
    "Zone: " + Zone + "<br />" +
    "Light: " + Light + "<br />" +
    "Price: " + Price;
}
}
}
}
</code>```

答:
you could try using addEventListener method instead and see whether it works?

```<code>    plants.forEach(function(plant){
    plant.addEventListener("onmouseover", HoverChoice);
    });
</code>```

or going with the original loop you made it would be

```<code>for (i=0; i < plants.length; i++)
{
  plants[i].addEventListener("onmouseover", HoverChoice);
}
</code>```

I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });

Body:
So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first  and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.

window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
    xhr = new XMLHttpRequest();
        if(xhr) {
            xhr.addEventListener("readystatechange", ShowFile);
            xhr.open("GET", "plants.xml", true);
            xhr.send();
        } else {
            alert("XHR not supported.");
        }
}
function ShowFile() {
    var i;
    var title;
    var cover;
    var plant_table = "

Common Name 	Botanical Name
";
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
        //here we have gotten the file correctly
        //loop through it and print out cover and title
        var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
        //booklist is an array and each element is an object sub i
        //so you have to use getElementBy something in order to pull the information
        for (i = 0; i < plantlist.length; i++) {
            var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
             var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
            plant_table += "
" +
                            "" + Common + "	" +
                            "" + Botanical + "	" +
                         "
";
    }
        plant_table += "
";
        document.getElementById("outarea").innerHTML = plant_table;
    }
    var plants = document.getElementsByClassName("plant");
    for (i=0; i < plants.length; i++) {
      plants[i].onmouseover = HoverChoice;
    }
    }
function HoverChoice() {
    var input = xhr.responseXML.getElementsByTagName("PLANT");
    for (i = 0; i < input.length; i++) {
            Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
            var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
            var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
           var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
    if (plants == this.innerHTML) {
    document.getElementById("inarea").innerHTML =
    "
" + Common + "
" + "
" + "
" +
    "Zone: " + Zone + "
" +
    "Light: " + Light + "
" +
    "Price: " + Price;
}
}
}
}

Body:
you could try using addEventListener method instead and see whether it works?

    plants.forEach(function(plant){
    plant.addEventListener("onmouseover", HoverChoice);
    });

or going with the original loop you made it would be

for (i=0; i < plants.length; i++)
{
  plants[i].addEventListener("onmouseover", HoverChoice);
}

I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });


问:
Shortening repeating functions
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

```

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

答:
Basically, just pass this to the function and since the value indicated on the button is what is different for each button, we just concatenate that to 'test' and pass that to the string.

    <!DOCTYPE html>

      <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

    <input type="button" onclick="setSliderValue(this)" value="1">
    <input type="button" onclick="setSliderValue(this)" value="2">
    <input type="button" onclick="setSliderValue(this)" value="3">

    ```

Title: Shortening repeating functions

Body:
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

Body:
Basically, just pass this to the function and since the value indicated on the button is what is different for each button, we just concatenate that to 'test' and pass that to the string.

    <!DOCTYPE html>
    <html>

    <body>
    <div id="slidecontainer">
      <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
      <p>Value: <span id="demo"></span></p>
    </div>
    <input type="button" onclick="setSliderValue(this)" value="1">
    <input type="button" onclick="setSliderValue(this)" value="2">
    <input type="button" onclick="setSliderValue(this)" value="3">

    <script>
    var slider = document.getElementById("myRange");
    var output = document.getElementById("demo");
    output.innerHTML = slider.value;

    slider.oninput = function() {
      output.innerHTML = this.value;
    }

    function setSliderValue(button) {
        var value = button.value
     var testType = 'test' + value;
        console.log('test: ' + testType +' '+ slider.value);
    }

    </script>

    </body>
    </html>


问:
How do I do this in Javascript and Django?
I'm used to putting my javascripts in the top of my page in the head section.  In my javascript, I use a lot of template stuff from Django like:  {{ user.id }} {{ post.body }}

I decided to move my javascript into another file, and then import it using: script src=

But since my javascript is in another file now it can't read my Django template stuff.

What do I do? I have Django template stuff all over the javascript, and I must move my javascript to another file.

答:
Dump some JSON object at top of page in a script tag:

```<code><script type='text/javascript'>
var a = {{ someJsonObject }}
</script>
</code>```

Then include your separate javascript file and use a.variable1, a.variable2 etc. in your javascript codes.

Body:
Dump some JSON object at top of page in a script tag:

<script type='text/javascript'>
var a = {{ someJsonObject }}
</script>

Then include your separate javascript file and use a.variable1, a.variable2 etc. in your javascript codes.


问:
java.util.InputMismatchException when reading simple value
I had read similar answers here, but still I can't think what's going on here. I've got the following snippet:

```<code> public static void main(String [] args) {
    Scanner scanner = new Scanner(System.in);

    String text = null;
    int option, value = 0;

    System.out.println("1. Cipher - 2. Decypher");
    option = scanner.nextInt();

    switch (option) {
        case 1:
            text = scanner.nextLine();
            value = scanner.nextInt();
            break;

        case 2:
            text = scanner.nextLine();
            value = scanner.nextInt();
            break;
    }
    System.out.println("you have entered " + text);
    System.out.println("you have entered " + value);
}
</code>```

So if you enter 1, you can write a String, then an int. Simple, right?

Then, why am I getting this output after typing "1", enter and then "hello"?

```<code>1. Cipher - 2. Decypher
1
hello
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at phd.cml.PruBorrar.main(PruBorrar.java:19)

Process finished with exit code 1
</code>```

答:
The scanner.nextInt() method only returns the next int, it doesn't consume the newline you are entering after the int.

The nextLine() call will then consume the newline after the int:

```<code>text = scanner.nextLine();
</code>```

And then this will attempt to consume "hello" and throw an InputMismatchException:

```<code>value = scanner.nextInt();
</code>```

So basically you just have to add an extra scanner.nextLine() after the call to scanner.nextInt()

This explains it more thoroughly: https://www.reddit.com/r/javahelp/wiki/scanner

Body:
I had read similar answers here, but still I can't think what's going on here. I've got the following snippet:

 public static void main(String [] args) {
    Scanner scanner = new Scanner(System.in);

    String text = null;
    int option, value = 0;

    System.out.println("1. Cipher - 2. Decypher");
    option = scanner.nextInt();

    switch (option) {
        case 1:
            text = scanner.nextLine();
            value = scanner.nextInt();
            break;

        case 2:
            text = scanner.nextLine();
            value = scanner.nextInt();
            break;
    }
    System.out.println("you have entered " + text);
    System.out.println("you have entered " + value);
}

So if you enter 1, you can write a String, then an int. Simple, right?

Then, why am I getting this output after typing "1", enter and then "hello"?

1. Cipher - 2. Decypher
1
hello
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at phd.cml.PruBorrar.main(PruBorrar.java:19)

Process finished with exit code 1

Body:
The scanner.nextInt() method only returns the next int, it doesn't consume the newline you are entering after the int.

The nextLine() call will then consume the newline after the int:

text = scanner.nextLine();

And then this will attempt to consume "hello" and throw an InputMismatchException:

value = scanner.nextInt();

So basically you just have to add an extra scanner.nextLine() after the call to scanner.nextInt()

This explains it more thoroughly: https://www.reddit.com/r/javahelp/wiki/scanner


问:
How can I ignore DTD validation but keep the Doctype when writing an XML file?
I am working on a system that should be able to read any (or at least, any well-formed) XML file, manipulate a few nodes and write them back into that same file. I want my code to be as generic as possible and I don't want

hardcoded references to Schema/Doctype information anywhere in my code. The doctype information is in the source document, I want to keep exactly that doctype information and not provide it again from within my code. If a document has no DocType, I won't add one. I do not care about the form or content of these files at all, except for my few nodes.

custom EntityResolvers or StreamFilters to omit or otherwise manipulate the source information (It is already a pity that namespace information seems somehow inaccessible from the document file where it is declared, but I can manage by using uglier XPaths)

DTD validation. I don't have the referenced DTDs, I don't want to include them and Node manipulation is perfectly possible without knowing about them.

The aim is to have the source file entirely unchanged except for the changed Nodes, which are retrieved via XPath. I would like to get away with the standard javax.xml stuff.

My progress so far:

```<code>    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setAttribute("http://xml.org/sax/features/namespaces", true);
    factory.setAttribute("http://xml.org/sax/features/validation", false);
    factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    factory.setNamespaceAware(true);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setIgnoringComments(false);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(inStream));
</code>```

This loads the XML source into a org.w3c.dom.Document successfully, ignoring DTD validation. I can do my replacements and then I use

```<code>    Source source = new DOMSource(document);
    Result result = new StreamResult(getOutputStream(getPath()));

    // Write the DOM document to the file
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
</code>```

to write it back. Which is nearly perfect. But the Doctype tag is gone, no matter what I do. While debugging, I saw that there is a DeferredDoctypeImpl [log4j:configuration: null] object in the Document object after parsing, but it is somehow wrong, empty or ignored. The file I tested on starts like this (but it is the same for other file types):

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

[...]

I think there are a lot of (easy?) ways involving hacks or pulling additional JARs into the project. But I would rather like to have it with the tools I already use.

答:
I tried using the LSSerializer library and was unable to get anywhere with it in terms of retaining the Doctype. This is the solution that Stephan probably used
Note: This is in scala but uses a java library so just convert your code

```<code>import com.sun.org.apache.xml.internal.serialize.{OutputFormat, XMLSerializer}
 def transformXML(root: Element, file: String): Unit = {
    val doc = root.getOwnerDocument
    val format = new OutputFormat(doc)
    format.setIndenting(true)
    val writer = new OutputStreamWriter(new FileOutputStream(new File(file)))
    val serializer = new XMLSerializer(writer, format)
    serializer.serialize(doc)

  }
</code>```

OwnerDisplayName: Stephan

Body:
I am working on a system that should be able to read any (or at least, any well-formed) XML file, manipulate a few nodes and write them back into that same file. I want my code to be as generic as possible and I don't want

hardcoded references to Schema/Doctype information anywhere in my code. The doctype information is in the source document, I want to keep exactly that doctype information and not provide it again from within my code. If a document has no DocType, I won't add one. I do not care about the form or content of these files at all, except for my few nodes.

custom EntityResolvers or StreamFilters to omit or otherwise manipulate the source information (It is already a pity that namespace information seems somehow inaccessible from the document file where it is declared, but I can manage by using uglier XPaths)

DTD validation. I don't have the referenced DTDs, I don't want to include them and Node manipulation is perfectly possible without knowing about them.

The aim is to have the source file entirely unchanged except for the changed Nodes, which are retrieved via XPath. I would like to get away with the standard javax.xml stuff.

My progress so far:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setAttribute("http://xml.org/sax/features/namespaces", true);
    factory.setAttribute("http://xml.org/sax/features/validation", false);
    factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    factory.setNamespaceAware(true);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setIgnoringComments(false);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(inStream));

This loads the XML source into a org.w3c.dom.Document successfully, ignoring DTD validation. I can do my replacements and then I use

    Source source = new DOMSource(document);
    Result result = new StreamResult(getOutputStream(getPath()));

    // Write the DOM document to the file
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);

to write it back. Which is nearly perfect. But the Doctype tag is gone, no matter what I do. While debugging, I saw that there is a DeferredDoctypeImpl [log4j:configuration: null] object in the Document object after parsing, but it is somehow wrong, empty or ignored. The file I tested on starts like this (but it is the same for other file types):

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

[...]

I think there are a lot of (easy?) ways involving hacks or pulling additional JARs into the project. But I would rather like to have it with the tools I already use.

Body:
I tried using the LSSerializer library and was unable to get anywhere with it in terms of retaining the Doctype. This is the solution that Stephan probably used
Note: This is in scala but uses a java library so just convert your code

import com.sun.org.apache.xml.internal.serialize.{OutputFormat, XMLSerializer}
 def transformXML(root: Element, file: String): Unit = {
    val doc = root.getOwnerDocument
    val format = new OutputFormat(doc)
    format.setIndenting(true)
    val writer = new OutputStreamWriter(new FileOutputStream(new File(file)))
    val serializer = new XMLSerializer(writer, format)
    serializer.serialize(doc)

  }


问:
output raw javascript using handlebars
I created a mini CMS to store code snippets.
It pulls articles form a mongodb database.
I use highlgiht.js to display the code and allow users to copy the snippets.

With HTML, everything works as expected:

```<code>{{#article}}
    <h1>Demo</h1>
    {{{markup}}} <!-- prints raw HTML in the screen, yay! -->

    <h1>HTML</h1>
    <pre class="pre-scrollable"><code class="html">{{markup}}</code>```

{{/article}}
```

<p>Now, with Javascript:</p>

```{{#article}}

Demo

    {{{js}}}

JS

{{js}}```
    <!-- prints <script></script> -->

{{/article}}
</code>```

The content of the field "js" in the database is "console.log("test");"

Why is it not outputting what's saved in the db, but instead it is making up a new script tag on its own??

Thank you!

答:
After pulling most of my hair, I figured it out:

I had a name collision where my document property/field was named "js" and that conflicted with the name of a helper from a library I am using:
https://github.com/helpers/handlebars-helpers/blob/master/lib/html.js#L85

Title: output raw javascript using handlebars

Body:
I created a mini CMS to store code snippets.
It pulls articles form a mongodb database.
I use highlgiht.js to display the code and allow users to copy the snippets.

With HTML, everything works as expected:

{{#article}}

Demo

    {{{markup}}}

HTML

{{markup}}

{{/article}}

Now, with Javascript:

{{#article}}

Demo

    {{{js}}}

JS

{{js}}

{{/article}}

The content of the field "js" in the database is "console.log("test");"

Why is it not outputting what's saved in the db, but instead it is making up a new script tag on its own??

Thank you!


问:
JSF update view don't change the bean
I got a basic edit form for a "document" entity (I use JSF2 and Hibernate),  the "create" form works fine, but the "edit" doesn't. So the edit form show the current document values, but when it send new values, the backbean doesn't get them and works like with old entity.

parts of my edit.xhtml :

```<code><ui:param name="doc" value="#{document.getDocument()}" />

<h:form id="editForm">
    <h:inputHidden name="ID" id="ID" value="#{doc.ID}" />

    <div class="input-group">
        <span class="input-group-label">Title *</span>
        <h:inputText type="text" class="input-group-field" size="30" name="title" id="title" a:required="required" a:placeholder="title" value="#{doc.title}"/>
    </div>
    <h:message for="title"></h:message>

    <div class="input-group">
        <span class="input-group-label">Subtitle</span>
        <h:inputText type="text" class="input-group-field" size="30" name="subtitle" id="subtitle" a:placeholder="subtitle" value="#{doc.subtitle}" />
    </div>
    <h:message for="subtitle"></h:message>

    <div class="button-group">
        <h:button outcome="/main?faces-redirect=true" type="button" value="Cancel"></h:button>
       <h:commandButton action="${doc.save}" value="Save">
           <f:ajax render="@form" execute=":editForm" event="keyup"/>
       </h:commandButton>
    </div>

</h:form>
</code>```

parts of my document bean :

```<code>@ManagedBean
@Entity
@ViewScoped
public class document implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "ID")
    private int ID;
    @NotNull
    private String title;
    private String subtitle;

    //Getters Setters....

    @Transient
    public document getDocument() {
        documentDAO = new DocumentDAO();
        Optional<document> doc =  documentDAO.read(this.ID);
        if(doc.isPresent()) {
            return doc.get();
        }else {
            return null;
        }
    }

    public String save() {
         documentDAO = new DocumentDAO();
         System.out.println("Saving Document (" + this.getTitle() + ")...");
         documentDAO.update(this);
         if(this.error == null || this.error.isEmpty())
              return "/list?faces-redirect=true";
         else
             return "edit";
     }
</code>```

If I edit the document title, was for example "test", by "testok", and send the form, the system print "Saving Document (test)...", and not "Saving Document (testok)...", despite of I can see that "testok" has been send in the post html request (using web dev panel of the navigator).
I don't have form inside a form.

答:
I found a solution, by using a copy of the bean for the edit, and load it in the view params, retrieving the id from previous list page.
In the header of my edit.xhtml:

```<code><f:metadata>
    <f:viewParam name="id" value="#{document.ID}"/>
    <f:viewAction action="#{document.getDocument()}" />
</f:metadata>
</code>```

In my document bean:

```<code>@Transient
public void getDocument() {
    documentDAO = new DocumentDAO();
    Optional<document> doc =  documentDAO.read(this.ID);
    if(doc.isPresent()) {
        document d = doc.get();
        this.title = d.title;
        this.subtitle = d.subtitle;
    }
}
</code>```

And now it works fine, it update the bean. Just copying all the members variables is a bit crappy, maybe there's a nicer way.

Title: JSF update view don't change the bean

Body:
I got a basic edit form for a "document" entity (I use JSF2 and Hibernate),  the "create" form works fine, but the "edit" doesn't. So the edit form show the current document values, but when it send new values, the backbean doesn't get them and works like with old entity.

parts of my edit.xhtml :

<ui:param name="doc" value="#{document.getDocument()}" />

<h:form id="editForm">
    <h:inputHidden name="ID" id="ID" value="#{doc.ID}" />

        Title *
        <h:inputText type="text" class="input-group-field" size="30" name="title" id="title" a:required="required" a:placeholder="title" value="#{doc.title}"/>

    <h:message for="title"></h:message>

        Subtitle
        <h:inputText type="text" class="input-group-field" size="30" name="subtitle" id="subtitle" a:placeholder="subtitle" value="#{doc.subtitle}" />

    <h:message for="subtitle"></h:message>

        <h:button outcome="/main?faces-redirect=true" type="button" value="Cancel"></h:button>
       <h:commandButton action="${doc.save}" value="Save">
           <f:ajax render="@form" execute=":editForm" event="keyup"/>
       </h:commandButton>

</h:form>

parts of my document bean :

@ManagedBean
@Entity
@ViewScoped
public class document implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "ID")
    private int ID;
    @NotNull
    private String title;
    private String subtitle;

    //Getters Setters....

    @Transient
    public document getDocument() {
        documentDAO = new DocumentDAO();
        Optional<document> doc =  documentDAO.read(this.ID);
        if(doc.isPresent()) {
            return doc.get();
        }else {
            return null;
        }
    }

    public String save() {
         documentDAO = new DocumentDAO();
         System.out.println("Saving Document (" + this.getTitle() + ")...");
         documentDAO.update(this);
         if(this.error == null || this.error.isEmpty())
              return "/list?faces-redirect=true";
         else
             return "edit";
     }

If I edit the document title, was for example "test", by "testok", and send the form, the system print "Saving Document (test)...", and not "Saving Document (testok)...", despite of I can see that "testok" has been send in the post html request (using web dev panel of the navigator).
I don't have form inside a form.

Body:
I found a solution, by using a copy of the bean for the edit, and load it in the view params, retrieving the id from previous list page.
In the header of my edit.xhtml:

<f:metadata>
    <f:viewParam name="id" value="#{document.ID}"/>
    <f:viewAction action="#{document.getDocument()}" />
</f:metadata>

In my document bean:

@Transient
public void getDocument() {
    documentDAO = new DocumentDAO();
    Optional<document> doc =  documentDAO.read(this.ID);
    if(doc.isPresent()) {
        document d = doc.get();
        this.title = d.title;
        this.subtitle = d.subtitle;
    }
}

And now it works fine, it update the bean. Just copying all the members variables is a bit crappy, maybe there's a nicer way.