问:
iphone : strange behaviour of labels
on viewWillAppear  i am trying to hide labels but is not getting hide here.what could be wrong?

```<code>In case when alertview is not being shown it is working fine with hide/unhide.but when alert is shown it is not working

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {

        for (SKPaymentTransaction *transaction in transactions) {

                switch (transaction.transactionState) {
                case SKPaymentTransactionStatePurchasing:

                    break;

                case SKPaymentTransactionStatePurchased:

                    flgCheck = 1;
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                    [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"IN_APP_PURCHASE"];
                    [[NSUserDefaults standardUserDefaults] setValue:@"ON" forKey:@"REMOVEADS"];

                    [appdelegate removeAdmob];

                    [self viewWillAppear:YES];

                    if([[[NSUserDefaults standardUserDefaults] valueForKey:@"FROMPOPUP"] isEqualToString:@"Done"])
                    {
                        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [purchasedone show];
                        [purchasedone release];
                    }
  }
    -(void)viewWillAppear:(BOOL)animated
    {

        purchaseDone = [[NSUserDefaults standardUserDefaults] valueForKey:@"IN_APP_PURCHASE"];
        if([purchaseDone isEqualToString:@"YES"])
        {
            lblinst.hidden=YES;
            lblremovead.enabled = YES;
            adSwitch.enabled = YES;
            btnUpgrade.enabled = NO;
            if([[[NSUserDefaults standardUserDefaults] valueForKey:@"REMOVEADS"] isEqualToString:@"ON"])
            {
                [adSwitch setOn:YES];
                [appdelegate removeAdmob];
            }
            else
            {
                [adSwitch setOn:NO];
                [appdelegate addAdmob];

            }
        }
    }
</code>```

答:
Ensure that the condition [purchaseDone isEqualToString:@"YES"]  evaluate to YES,
It seem me the result is NO.

And you could check  with putting the NSLog's ,

```<code>if([purchaseDone isEqualToString:@"YES"])
{
   lblinst.hidden=YES;
   NSLog(@"true :: hide the label");
   ............
   ......
}
else
{
   NSLog(@"False :: Not hide the label");
}
</code>```

Title: iphone : strange behaviour of labels

Body:
on viewWillAppear  i am trying to hide labels but is not getting hide here.what could be wrong?

In case when alertview is not being shown it is working fine with hide/unhide.but when alert is shown it is not working

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {

        for (SKPaymentTransaction *transaction in transactions) {

                switch (transaction.transactionState) {
                case SKPaymentTransactionStatePurchasing:

                    break;

                case SKPaymentTransactionStatePurchased:

                    flgCheck = 1;
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                    [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"IN_APP_PURCHASE"];
                    [[NSUserDefaults standardUserDefaults] setValue:@"ON" forKey:@"REMOVEADS"];

                    [appdelegate removeAdmob];

                    [self viewWillAppear:YES];

                    if([[[NSUserDefaults standardUserDefaults] valueForKey:@"FROMPOPUP"] isEqualToString:@"Done"])
                    {
                        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [purchasedone show];
                        [purchasedone release];
                    }
  }
    -(void)viewWillAppear:(BOOL)animated
    {

        purchaseDone = [[NSUserDefaults standardUserDefaults] valueForKey:@"IN_APP_PURCHASE"];
        if([purchaseDone isEqualToString:@"YES"])
        {
            lblinst.hidden=YES;
            lblremovead.enabled = YES;
            adSwitch.enabled = YES;
            btnUpgrade.enabled = NO;
            if([[[NSUserDefaults standardUserDefaults] valueForKey:@"REMOVEADS"] isEqualToString:@"ON"])
            {
                [adSwitch setOn:YES];
                [appdelegate removeAdmob];
            }
            else
            {
                [adSwitch setOn:NO];
                [appdelegate addAdmob];

            }
        }
    }

Body:
Ensure that the condition [purchaseDone isEqualToString:@"YES"]  evaluate to YES,
It seem me the result is NO.

And you could check  with putting the NSLog's ,

if([purchaseDone isEqualToString:@"YES"])
{
   lblinst.hidden=YES;
   NSLog(@"true :: hide the label");
   ............
   ......
}
else
{
   NSLog(@"False :: Not hide the label");
}


来源: stackexchange

问:
Synchronizing between a local and remote GUI
Consider the following GUI:

when the user press the + button the value is incremented to 6.

However on another computer another user is running the same GUI.

The two GUIs have to stay in sync.
If one of the users press the + button the value should be updated for both GUIs.

The remote GUI, the client, communicate with the local server via a simple protocol.
The communication takes the form of a cmd sent from the client and a response sent from the server. There are two commands:

```<code>1. cmd:"GET_VALUE", response: "5"
2. cmd: "INCREMENT", response: "OK"
</code>```

Unfortunately the client has to poll GET_VALUE to be notified,
but the protocol albeit flawed can not be changed.

How can I implement this in Qt, C++?

So far I have come up with the following classes (rough outline):

```<code>class Model {
public:
    std::atomic<int> m_value;
};

class Widget : public QWidget {
public slots:
    void incrementClickedLocally(); // must update Model::m_value somehow
    void valueChangedFromModel(int value); // will update the QLineEdit
};

// Reads synchronously from TCP/IP using WinSocket and works on the Model
class RemoteHandler : public QThread {
private:
    void run override();
};
</code>```

I would like to use signals/slots to communicate across the threads.
However it seems that the RemoteHandler can not use signal/slots to get the Model::m_value since slots can not have return types?

Further it would be convenient to emit a valueChanged signal from Model to notify Widget. However in order to do that Model must be a QObject.
It seems that when Model becomes a QObject there are many potential thread problems I have to look out for?
As it is Model is threadsafe. I can therefore request Model::m_value directly from the non main thread in RemoteHandler while the Widget may be accessing the same variable simultaneously from the main thread.

答:
It cannot work with those commands.

The logic is well-known from the design of multi-core CPU's. You need Compare-and-Swap (CAS), Load-Link/Store Conditional (LL/SC) or something equally powerful. With the weak protocol you have, it can be proven that the race conditions are unsolvable.

ContentLicense: CC BY-SA 4.0

Body:
Consider the following GUI:

when the user press the + button the value is incremented to 6.

However on another computer another user is running the same GUI.

The two GUIs have to stay in sync.
If one of the users press the + button the value should be updated for both GUIs.

The remote GUI, the client, communicate with the local server via a simple protocol.
The communication takes the form of a cmd sent from the client and a response sent from the server. There are two commands:

1. cmd:"GET_VALUE", response: "5"
2. cmd: "INCREMENT", response: "OK"

Unfortunately the client has to poll GET_VALUE to be notified,
but the protocol albeit flawed can not be changed.

How can I implement this in Qt, C++?

So far I have come up with the following classes (rough outline):

class Model {
public:
    std::atomic<int> m_value;
};

class Widget : public QWidget {
public slots:
    void incrementClickedLocally(); // must update Model::m_value somehow
    void valueChangedFromModel(int value); // will update the QLineEdit
};

// Reads synchronously from TCP/IP using WinSocket and works on the Model
class RemoteHandler : public QThread {
private:
    void run override();
};

I would like to use signals/slots to communicate across the threads.
However it seems that the RemoteHandler can not use signal/slots to get the Model::m_value since slots can not have return types?

Further it would be convenient to emit a valueChanged signal from Model to notify Widget. However in order to do that Model must be a QObject.
It seems that when Model becomes a QObject there are many potential thread problems I have to look out for?
As it is Model is threadsafe. I can therefore request Model::m_value directly from the non main thread in RemoteHandler while the Widget may be accessing the same variable simultaneously from the main thread.


问:
restTemplate to attach a file to an event
I am generating a file, and then an event. I want to attach the file to the event generated. Thus, making use of a POST method here.

However, I get 401: Unauthorized: [no body] error

```<code> private void attachBinaryToEvent(Event event, File file) throws IOException, AuthenticationException {
    String pathEvent = platform.getUrl().get()+"/event/events/{{eventId}}/binaries";
    String pathEventAttachment = pathEvent.replace("{{eventId}}", event.getId().getValue());

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", "binaryFile");
    jsonObject.addProperty("data", new String(Base64.getEncoder().encode(FileUtils.readFileToByteArray(file))));

    HttpHeaders headers = RequestAuthenticationEncoder.encode(getCredentials());
    headers.setContentType(MediaType.APPLICATION_JSON);
    log.info("HEader {}", headers.get("Authorization")); //this works as i get the credentials
    HttpEntity<JsonObject> request = new HttpEntity<>(jsonObject,headers);

    restTemplate.postForObject(pathEventAttachment, request.toString(), Event.class); //Fails here

    log.info("Binary file added to the event {}", event.getId().getValue());

  }
</code>```

Error:

```<code>org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:785)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421)
    at com.nordex.microservice.controller.Controller.attachBinaryToEvent(Controller.java:173)
    at com.nordex.microservice.controller.Controller.fileUpload(Controller.java:149)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
...
</code>```

Update:

```<code>HttpEntity<JsonObject> request = new HttpEntity<>(jsonObject,headers);
restTemplate.postForObject(pathEventAttachment, request, Event.class);
</code>```

gives error:

```<code>org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: JsonObject; nested exception is com.fasterxml.jackson.databind.JsonMappingException: JsonObject (through reference chain: com.google.gson.JsonObject["asInt"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:296)
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:946)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421)

</code>```

Any suggestions ?

答:
I think the issue is with you converting your HttpEntity request object to string in your postforObject request. Is there any explicit reason why you are doing that. If not try once by replacing request.toString() to just request and let us know if it works. If your jsonObject needs to be a string you can do that in your request object (if you request payload needs to be a string)</p>
```<code>HttpEntity<JsonObject> request = new HttpEntity<>(jsonObject.toString(),headers);

restTemplate.postForObject(pathEventAttachment, request, Event.class); //Fails here
</code>```

Body:
I am generating a file, and then an event. I want to attach the file to the event generated. Thus, making use of a POST method here.

However, I get 401: Unauthorized: [no body] error

 private void attachBinaryToEvent(Event event, File file) throws IOException, AuthenticationException {
    String pathEvent = platform.getUrl().get()+"/event/events/{{eventId}}/binaries";
    String pathEventAttachment = pathEvent.replace("{{eventId}}", event.getId().getValue());

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", "binaryFile");
    jsonObject.addProperty("data", new String(Base64.getEncoder().encode(FileUtils.readFileToByteArray(file))));

    HttpHeaders headers = RequestAuthenticationEncoder.encode(getCredentials());
    headers.setContentType(MediaType.APPLICATION_JSON);
    log.info("HEader {}", headers.get("Authorization")); //this works as i get the credentials
    HttpEntity<JsonObject> request = new HttpEntity<>(jsonObject,headers);

    restTemplate.postForObject(pathEventAttachment, request.toString(), Event.class); //Fails here

    log.info("Binary file added to the event {}", event.getId().getValue());

  }

Error:

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:785)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421)
    at com.nordex.microservice.controller.Controller.attachBinaryToEvent(Controller.java:173)
    at com.nordex.microservice.controller.Controller.fileUpload(Controller.java:149)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
...

Update:

HttpEntity<JsonObject> request = new HttpEntity<>(jsonObject,headers);
restTemplate.postForObject(pathEventAttachment, request, Event.class);

gives error:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: JsonObject; nested exception is com.fasterxml.jackson.databind.JsonMappingException: JsonObject (through reference chain: com.google.gson.JsonObject["asInt"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:296)
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:946)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421)

Any suggestions ?

Body:
I think the issue is with you converting your HttpEntity request object to string in your postforObject request. Is there any explicit reason why you are doing that. If not try once by replacing request.toString() to just request and let us know if it works. If your jsonObject needs to be a string you can do that in your request object (if you request payload needs to be a string)

HttpEntity<JsonObject> request = new HttpEntity<>(jsonObject.toString(),headers);

restTemplate.postForObject(pathEventAttachment, request, Event.class); //Fails here


问:
scraping name of dataset in kaggle using python
Hi,
Please how can i get the name of dataset in kaggle, usign beatiful soup or selenium or scrapy.
I test this code but no return :

```<code>from bs4 import BeautifulSoup
import requests

url = 'https://www.kaggle.com/heptapod/titanic'
res = requests.get(url)
html_page = res.content

soup = BeautifulSoup(html_page, 'html.parser')
datasetName = soup.find('h5',{'class':'sc-dIvrsQ sc-hHEiqL sc-kaPsuu kSVYRu ccTnQh ffXPrd'})

print(datasetName)
</code>```

see the picture :
inspect element from kaggle

答:
Using Selenium

```<code>from selenium.webdriver.chrome.options import Options
opt = Options()
opt.add_argument('--headless')
driver = webdriver.Chrome(executable_path = 'yourdriverpath', options=opt)

driver.get("https://www.kaggle.com/heptapod/titanic")
time.sleep(5)
datasetname = driver.find_element(By.XPATH, "//div[@role='button']//div//div").text
print(datasetname)
</code>```

Output:

```<code>train_and_test2.csv

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

dataset snapshot

Body:
Hi,
Please how can i get the name of dataset in kaggle, usign beatiful soup or selenium or scrapy.
I test this code but no return :

from bs4 import BeautifulSoup
import requests

url = 'https://www.kaggle.com/heptapod/titanic'
res = requests.get(url)
html_page = res.content

soup = BeautifulSoup(html_page, 'html.parser')
datasetName = soup.find('h5',{'class':'sc-dIvrsQ sc-hHEiqL sc-kaPsuu kSVYRu ccTnQh ffXPrd'})

print(datasetName)

see the picture :
inspect element from kaggle

Body:
Using Selenium

from selenium.webdriver.chrome.options import Options
opt = Options()
opt.add_argument('--headless')
driver = webdriver.Chrome(executable_path = 'yourdriverpath', options=opt)

driver.get("https://www.kaggle.com/heptapod/titanic")
time.sleep(5)
datasetname = driver.find_element(By.XPATH, "//div[@role='button']//div//div").text
print(datasetname)

Output:

train_and_test2.csv

Process finished with exit code 0

dataset snapshot


问:
how can i have a struct have an unknown size array member?
im trying to make a sort of minesweeper clone in c, but i cant figure out how to create a variable length array member of a struct and initialize it.

my struct definitions

typedef struct Cell
{
    Rectangle area;         // The area the cell covers
    bool hasMine;           // If the cell covers a mine
    bool covered;           // If the cell is currently covered
    int touching;           // How many mines the cell is touching
} Cell;

typedef struct Minefield
{
    int columns;        // The amount of columns
    int rows;           // The amount of rows
    int mines;          // The amount of mines
    Cell field[];       // An array of columns*rows Cells

} Minefield;
```
<p>how im creating new instances of a Minefield</p>
<pre class="lang-c prettyprint-override"><code>Minefield NewGame(int columns, int rows, int mines)
{
    int i = 0;

    Cell cells[columns*rows];

    for (i=0; i < columns*rows; i++) {
        int x = 0;
        int y = 0;

        if (i == 0) {
            Rectangle area = (Rectangle){0, 0, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }
        else {
            Cell previous = cells[i-1];

            x = previous.area.x + cellsize;
            y = previous.area.y + cellsize;

            Rectangle area = (Rectangle){x, y, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }

    }

    Minefield field = (Minefield){columns, rows, mines, cells};
    return field;
}
</code>```

im new to c, ive done some googling and ive come across some very similar questions, but i cant really understand them or the examples they give. i think you can do what my errendous code is trying to do (or something very similar) with a gcc extension, but i want my code to be portable. how can i have a struct have an unknown size array member?

答:
Yes, it's called flexible array member. It's usually used with dynamically allocated objects. However, you cannot return Minefield by value. The compiler will copy only sizeof(Minefield) data what is the size of object if length of array Minefield::field was 0.

You can do:

```<code>Minefield* NewGame(int columns, int rows, int mines)
{
    Cell cells[columns*rows];
    ...
    // allocate memory for Minefield and cells array just after it
    Minefield* minefield = malloc(sizeof(*minefield) + sizeof cells);
    if (!minefield) { ... error handling ... }

    // set normal fields using compund literal
    *minefield = (Minefield){columns, rows, mines};

    // copy cells `array` to `minefield->field` array
    memcpy(minefield->field, cells, sizeof cells);

    return minefield;
}
</code>```

The memcpy can be avoided by first allocating Minefield and writing directly to field member.

```<code>Minefield* NewGame(int columns, int rows, int mines)
{
    Minefield* minefield = malloc(sizeof(Minefield) + rows * columns * sizeof(Cell));
    if (!minefield) { ... error handling ... }
    *minefield = (Minefield){columns, rows, mines};

    Cell *cells = minefield->field;
    ...
    return minefield;
}
</code>```

Body:
im trying to make a sort of minesweeper clone in c, but i cant figure out how to create a variable length array member of a struct and initialize it.

my struct definitions

typedef struct Cell
{
    Rectangle area;         // The area the cell covers
    bool hasMine;           // If the cell covers a mine
    bool covered;           // If the cell is currently covered
    int touching;           // How many mines the cell is touching
} Cell;

typedef struct Minefield
{
    int columns;        // The amount of columns
    int rows;           // The amount of rows
    int mines;          // The amount of mines
    Cell field[];       // An array of columns*rows Cells

} Minefield;

how im creating new instances of a Minefield

Minefield NewGame(int columns, int rows, int mines)
{
    int i = 0;

    Cell cells[columns*rows];

    for (i=0; i < columns*rows; i++) {
        int x = 0;
        int y = 0;

        if (i == 0) {
            Rectangle area = (Rectangle){0, 0, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }
        else {
            Cell previous = cells[i-1];

            x = previous.area.x + cellsize;
            y = previous.area.y + cellsize;

            Rectangle area = (Rectangle){x, y, cellsize, cellsize};
            cells[i] = (Cell){area, false, true, 0};
        }

    }

    Minefield field = (Minefield){columns, rows, mines, cells};
    return field;
}

im new to c, ive done some googling and ive come across some very similar questions, but i cant really understand them or the examples they give. i think you can do what my errendous code is trying to do (or something very similar) with a gcc extension, but i want my code to be portable. how can i have a struct have an unknown size array member?

Body:
Yes, it's called flexible array member. It's usually used with dynamically allocated objects. However, you cannot return Minefield by value. The compiler will copy only sizeof(Minefield) data what is the size of object if length of array Minefield::field was 0.

You can do:

Minefield* NewGame(int columns, int rows, int mines)
{
    Cell cells[columns*rows];
    ...
    // allocate memory for Minefield and cells array just after it
    Minefield* minefield = malloc(sizeof(*minefield) + sizeof cells);
    if (!minefield) { ... error handling ... }

    // set normal fields using compund literal
    *minefield = (Minefield){columns, rows, mines};

    // copy cells `array` to `minefield->field` array
    memcpy(minefield->field, cells, sizeof cells);

    return minefield;
}

The memcpy can be avoided by first allocating Minefield and writing directly to field member.

Minefield* NewGame(int columns, int rows, int mines)
{
    Minefield* minefield = malloc(sizeof(Minefield) + rows * columns * sizeof(Cell));
    if (!minefield) { ... error handling ... }
    *minefield = (Minefield){columns, rows, mines};

    Cell *cells = minefield->field;
    ...
    return minefield;
}


问:
R heatmap function - can you add more colours so that differences within large regions are more obvious?
I am plotting a heatmap in R using the base R heatmap() function. Is there a way to define more colours so that the heatmap has a greater variation in the colours used. Currently it is using about 10 and the "hottest" area is quite large and dark purple. I want more colours so that this large area itself it broken down into more colours to better differentiate.</p>

答:
Try experimenting with the color palettes of the grDevices package.

```<code>     library(grDevices)
     heatmap(x, col = topo.colors(n))
</code>```

where n is the number of colors.
Or, alternatively

```<code>     col = rainbow(n)
     col = terrain.colors(n)
     col = cm.colors(n)
</code>```

However, often the problem with differentiation does not depend on the number of colors, but on the data variability: many of them may be clustered in a small range of values. In such case you could try to differentiate them by chosing a subrange or transforming the data, for example by graphing their logaritm.

Examples:

50 colors from cm.colors palette:

heatmap(Ca, col=cm.colors(50), Rowv=NA, Colv=NA)

matrix of log values, with 50 colors from cm.colors palette:

heatmap(log(Ca), col=cm.colors(50), Rowv=NA, Colv=NA)

in which subtler differences can be seen.

Body:
Try experimenting with the color palettes of the grDevices package.

     library(grDevices)
     heatmap(x, col = topo.colors(n))

where n is the number of colors.
Or, alternatively

     col = rainbow(n)
     col = terrain.colors(n)
     col = cm.colors(n)

However, often the problem with differentiation does not depend on the number of colors, but on the data variability: many of them may be clustered in a small range of values. In such case you could try to differentiate them by chosing a subrange or transforming the data, for example by graphing their logaritm.

Examples:

50 colors from cm.colors palette:

heatmap(Ca, col=cm.colors(50), Rowv=NA, Colv=NA)

matrix of log values, with 50 colors from cm.colors palette:

heatmap(log(Ca), col=cm.colors(50), Rowv=NA, Colv=NA)

in which subtler differences can be seen.


问:
Adding It function to Cypress fixture
I think I'm missing the point here. The fixture can't be used outside a test but I want to use the 'it' function to test each fixture in a JSON file.

I'm not sure if I understand fixtures correctly or use them correctly at the moment. Here is my Cypress TypeScript code:

```<code>let row: string;
let stream: string;

cy.fixture('AllNotificationStates').then((notifications) => {
  for (let notification in notifications) {
    row = notifications[notification].rowId;
    stream = notifications[notification].streamId;

    it(`${row}`, () => {
      cy.intercept('GET', '**/api/', (req) => {
        req.reply((req) => {
          req.statusCode = 200;
          req.body = [notifications[notification]];
        });
      });
      cy.visit('/notification/dashboard');

      co.setTestId(row);
      co.assertRowIDandStreamID(row, stream);
    });
  }
});
</code>```

答:
You should use cypress-each will run all tests regardless if one or more fail. Depending on how long it takes, you may want to break down the it.each test into another file.

```<code>import 'cypress-each' // can included in /support/index.js
import allNotifications from 'notificaitonsPath'

describe('Disclaimer check', () => {
  it.each(allNotifications)
    ((notify) => notify.rowId, // use function to print out row id for test title
     (notification) => {
       // test code
     })
})
</code>```

Title: Adding It function to Cypress fixture

Body:
I think I'm missing the point here. The fixture can't be used outside a test but I want to use the 'it' function to test each fixture in a JSON file.

I'm not sure if I understand fixtures correctly or use them correctly at the moment. Here is my Cypress TypeScript code:

let row: string;
let stream: string;

cy.fixture('AllNotificationStates').then((notifications) => {
  for (let notification in notifications) {
    row = notifications[notification].rowId;
    stream = notifications[notification].streamId;

    it(`${row}`, () => {
      cy.intercept('GET', '**/api/', (req) => {
        req.reply((req) => {
          req.statusCode = 200;
          req.body = [notifications[notification]];
        });
      });
      cy.visit('/notification/dashboard');

      co.setTestId(row);
      co.assertRowIDandStreamID(row, stream);
    });
  }
});

Body:
You should use cypress-each will run all tests regardless if one or more fail. Depending on how long it takes, you may want to break down the it.each test into another file.

import 'cypress-each' // can included in /support/index.js
import allNotifications from 'notificaitonsPath'

describe('Disclaimer check', () => {
  it.each(allNotifications)
    ((notify) => notify.rowId, // use function to print out row id for test title
     (notification) => {
       // test code
     })
})


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
Faster is 1 in your case however it isn't a fair comparison. You should ask StringBuilder.AppendFormat() vs StringBuilder.Append(string.Format()) - where the first one is faster due to internal working with char array.

Your second option is more readable though.

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

OwnerDisplayName: Miha Markic


问:
How can get list of multiple - GCP projects assigned under one service account ? ( GCP )( python-client library files)
I am trying to list the projects which are assigned under the service account file (credentials.json).

Below: by following this method i have added multiple project under one service account

And then I have generated the key (i.e) credientials.json file from the project B as mentioned in above image.

I checked inside the credientials.json : But that service account has only project name. it doesn't have the project A name.

Even though i applied this credientials.json file to my code its showing only the project B name.
it does't showes the project A name.

if the service account conneting method is wrong please correct me

Here is my code

```<code>import os
import google.auth
credential_path = r'c:test\credientials.json'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
credentials,project = google.auth.default()
print(credentials)
print(project)
</code>```

答:
On Google Cloud, the IAM permission are resource centric (a project is a resource, like a Cloud Functions or a VM) and not account centric (as AWS is).

Therefore, you can't know all the resources granted on an account, but you have to browse ALL the resource and to check if the account is authorized on it.

Because it's boring, you can use Cloud Asset Inventory search IAM policies to make this task easier

Body:
I am trying to list the projects which are assigned under the service account file (credentials.json).

Below: by following this method i have added multiple project under one service account

And then I have generated the key (i.e) credientials.json file from the project B as mentioned in above image.

I checked inside the credientials.json : But that service account has only project name. it doesn't have the project A name.

Even though i applied this credientials.json file to my code its showing only the project B name.
it does't showes the project A name.

if the service account conneting method is wrong please correct me

Here is my code

import os
import google.auth
credential_path = r'c:test\credientials.json'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
credentials,project = google.auth.default()
print(credentials)
print(project)


问:
REST API resource naming suffix
Our project came into discussion about URI pattern for Rest API.

The basic idea is a better description / readability of the endpoints themselves, by adding CRUD elements practically as a suffix in the endpoint name.

CRUD as /api/.../create, /api/.../read, /api/.../update and /api/.../delete endpoint pattern

So, examples (different examples without consistency for one project):

```<code>- GET    /api/v1/endpoint-names/read
- GET    /api/v1/endpoint-names/read/{id}
- GET    /api/v1/endpoint-names/read-paginated/{pageId}
- POST   /api/v1/endpoint-names/create
- PUT    /api/v1/endpoint-names/update-by-id/{id}
- DELETE /api/v1/endpoint-names/delete/{id}
</code>```

I am aware of some recommendations, but I am interested in additional naming conventions / suggestions for web services with more complicated URI structures.

Or there is no real need for something like this?

答:
The basic idea is a better description / readability of the endpoints themselves, by adding CRUD elements practically as a suffix in the endpoint name.

Tradeoffs - among other things, you give up the benefits of general purpose cache invalidation when you use different resource identifiers for different kinds of edits.

Note the difference in language; REST doesn't have endpoints.  Uniform resource identifiers identify resources -- think "web pages".  We send information to a server by proposing changes to its resource model (adding/removing resources, or modifying the representations of those already present).

Part of the point here being that -- because we are all understanding messages the same way -- we can integrate the same general purpose capabilities (browsers, spiders, proxies) to do useful work

The implementation of that useful work is hidden behind this "it's all just documents" facade.  See Webber 2011.

So when you create separate identifiers for each CRUD action

```<code>/foo/12345/read
/foo/12345/update
</code>```

What you are hiding from the HTTP application is the fact that these are in fact the same information, and that messages sent to .../update modify the representations returned by .../read, which means that general purpose components can't know to update their caches automatically, and you miss out on some of that "web scale" that we've all been promised.

And that can be fine: maybe you prefer having unambiguous spellings in the logs that your operators read to having web friendly caching.

Title: REST API resource naming suffix

Body:
Our project came into discussion about URI pattern for Rest API.

The basic idea is a better description / readability of the endpoints themselves, by adding CRUD elements practically as a suffix in the endpoint name.

CRUD as /api/.../create, /api/.../read, /api/.../update and /api/.../delete endpoint pattern

So, examples (different examples without consistency for one project):

- GET    /api/v1/endpoint-names/read
- GET    /api/v1/endpoint-names/read/{id}
- GET    /api/v1/endpoint-names/read-paginated/{pageId}
- POST   /api/v1/endpoint-names/create
- PUT    /api/v1/endpoint-names/update-by-id/{id}
- DELETE /api/v1/endpoint-names/delete/{id}

I am aware of some recommendations, but I am interested in additional naming conventions / suggestions for web services with more complicated URI structures.

Or there is no real need for something like this?

Body:
The basic idea is a better description / readability of the endpoints themselves, by adding CRUD elements practically as a suffix in the endpoint name.

Tradeoffs - among other things, you give up the benefits of general purpose cache invalidation when you use different resource identifiers for different kinds of edits.

Note the difference in language; REST doesn't have endpoints.  Uniform resource identifiers identify resources -- think "web pages".  We send information to a server by proposing changes to its resource model (adding/removing resources, or modifying the representations of those already present).

Part of the point here being that -- because we are all understanding messages the same way -- we can integrate the same general purpose capabilities (browsers, spiders, proxies) to do useful work

The implementation of that useful work is hidden behind this "it's all just documents" facade.  See Webber 2011.

So when you create separate identifiers for each CRUD action

/foo/12345/read
/foo/12345/update

What you are hiding from the HTTP application is the fact that these are in fact the same information, and that messages sent to .../update modify the representations returned by .../read, which means that general purpose components can't know to update their caches automatically, and you miss out on some of that "web scale" that we've all been promised.

And that can be fine: maybe you prefer having unambiguous spellings in the logs that your operators read to having web friendly caching.


问:
Group array of object base on one unique property?
For example, how can I turn the array of objects shown below into the corresponding result where names are grouped by id? I'd like to do this using vanilla Javascript and without using an external library like lodash if possible.

Example array:

```<code>const items = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
    { id: 1, name: 'd' },
    { id: 3, name: 'f' },
    { id: 1, name: 'a' },
    { id: 3, name: 'c' },
  ];
</code>```

Expected result:

```<code> const result = [
   { id: 1, names: ['a', 'd']},
   { id: 2, names: ['b']},
   { id: 3, names: ['c', 'f']}
  ]
</code>```

答:
I'm performing an reduce on the array and it gives me an object in the form of

{
  1: [object Set] { ... },
  2: [object Set] { ... },
  3: [object Set] { ... }
}
```
<p>where <code>Set</code> is used to keep unique values only.</p>
<p>After that I'm running a <code>map</code> on <code>Object.entries</code> to get the data to the format you wanted.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const items = [{ id: 1, name: 'a' },{ id: 2, name: 'b' },{ id: 3, name: 'c' },{ id: 1, name: 'd' },{ id: 3, name: 'f' },{ id: 1, name: 'a' },{ id: 3, name: 'c' },];

  const a = items.reduce((acc,curr)=> {
    if(!acc[curr.id]){
        acc[curr.id] = new Set();
    }

    acc[curr.id].add(curr.name)

    return acc;
  },{})

  let result = Object.entries(a).map((el) => ({id: el[0],names:[...el[1]]}))

  console.log(result)</code>```

.as-console-wrapper { max-height: 100% !important; top: 0; }```

Body:
For example, how can I turn the array of objects shown below into the corresponding result where names are grouped by id? I'd like to do this using vanilla Javascript and without using an external library like lodash if possible.

Example array:

const items = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
    { id: 1, name: 'd' },
    { id: 3, name: 'f' },
    { id: 1, name: 'a' },
    { id: 3, name: 'c' },
  ];

Expected result:

 const result = [
   { id: 1, names: ['a', 'd']},
   { id: 2, names: ['b']},
   { id: 3, names: ['c', 'f']}
  ]

Body:
I'm performing an reduce on the array and it gives me an object in the form of

{
  1: [object Set] { ... },
  2: [object Set] { ... },
  3: [object Set] { ... }
}

where Set is used to keep unique values only.

After that I'm running a map on Object.entries to get the data to the format you wanted.

const items = [{ id: 1, name: 'a' },{ id: 2, name: 'b' },{ id: 3, name: 'c' },{ id: 1, name: 'd' },{ id: 3, name: 'f' },{ id: 1, name: 'a' },{ id: 3, name: 'c' },];

  const a = items.reduce((acc,curr)=> {
    if(!acc[curr.id]){
        acc[curr.id] = new Set();
    }

    acc[curr.id].add(curr.name)

    return acc;
  },{})

  let result = Object.entries(a).map((el) => ({id: el[0],names:[...el[1]]}))

  console.log(result)

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Auto scaling's scale in process with running Kafka Consumer
When auto scale process scales in and selects a node/pod to terminate, it gives some grace period for the HTTP requests that already entered the target node/pod so that HTTP requests gets time to complete processing and respond. Also during this period, the load balancer stops sending new requests to the node/pod which is about to be terminated.

My question is, what if there is a Kafka consumer in one of the process/container which is unaware that it's containing process is about to be terminated and it keeps consuming data from Kafka and processes. There are chances that process will be terminated while consumer in the middle of processing the consumed data.

So, is there any solution that let's Kafka consumer to stop consuming and give it some grace period for processing already consumed record? Similar to how grace period is there for HTTP requests?

There could be some thoughts like, we can manually commit kafka offset after successfully processing it. But all scenarios may not fit for manual commit. May be we have to manually commit as soon as record is consumed and then process or just let consumer to auto commit.

答:
Most programming languages allow you to catch a SIGKILL/SIGTERM OS signal, which the container would receive.

From the signal handler, you could pause/close the consumer instance.

Keep in mind that you cannot scale a consumer application beyond the topic partition count


问:
from tkinter import * doesnt work anymore
I have been working on a project and everything was alright until I got this error:

```<code>File "D:\python\TKinter\amihaiRatson.py", line 1, in <module>
    from tkinter import *
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2472, in <module>
    class Grid:
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2493, in Grid
    self.tk.call(
NameError: name 'self' is not defined
</code>```

tkinter module suddenly not working..

答:
I just found a solution.
I installed again the file init.py

Body:
I have been working on a project and everything was alright until I got this error:

File "D:\python\TKinter\amihaiRatson.py", line 1, in <module>
    from tkinter import *
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2472, in <module>
    class Grid:
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2493, in Grid
    self.tk.call(
NameError: name 'self' is not defined

tkinter module suddenly not working..


答:
Your purchaseDone seems to be an NSString. I assume that because you want to compare it to the NSString @"YES".

If you declared the value for the key @"IN_APP_PURCHASE" as a boolean (in your settings bundle). Then comparing the Strings will never be true. Simply compare boolean values and it should work.

ContentLicense: CC BY-SA 3.0

Title: iphone : strange behaviour of labels

Body:
on viewWillAppear  i am trying to hide labels but is not getting hide here.what could be wrong?

In case when alertview is not being shown it is working fine with hide/unhide.but when alert is shown it is not working

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {

        for (SKPaymentTransaction *transaction in transactions) {

                switch (transaction.transactionState) {
                case SKPaymentTransactionStatePurchasing:

                    break;

                case SKPaymentTransactionStatePurchased:

                    flgCheck = 1;
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                    [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"IN_APP_PURCHASE"];
                    [[NSUserDefaults standardUserDefaults] setValue:@"ON" forKey:@"REMOVEADS"];

                    [appdelegate removeAdmob];

                    [self viewWillAppear:YES];

                    if([[[NSUserDefaults standardUserDefaults] valueForKey:@"FROMPOPUP"] isEqualToString:@"Done"])
                    {
                        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [purchasedone show];
                        [purchasedone release];
                    }
  }
    -(void)viewWillAppear:(BOOL)animated
    {

        purchaseDone = [[NSUserDefaults standardUserDefaults] valueForKey:@"IN_APP_PURCHASE"];
        if([purchaseDone isEqualToString:@"YES"])
        {
            lblinst.hidden=YES;
            lblremovead.enabled = YES;
            adSwitch.enabled = YES;
            btnUpgrade.enabled = NO;
            if([[[NSUserDefaults standardUserDefaults] valueForKey:@"REMOVEADS"] isEqualToString:@"ON"])
            {
                [adSwitch setOn:YES];
                [appdelegate removeAdmob];
            }
            else
            {
                [adSwitch setOn:NO];
                [appdelegate addAdmob];

            }
        }
    }


问:
Excel lookup in kettle 7
I am new to kettle.. I need to use excel sheet lookup for my kettle job.
The problem is stream lookup which compares my excel sheet with the input rows requires exact match. Is there any other step that i can use instead of this
Fir example,

Input row: 196 harrington ave las Vegas

My excel lookup has a rows of address abbreviation. One such is 'ave'

In this case i need to check if my input row has any substring in the lookup.

Kindly suggest me the proper step.

By the way my input is text file input of multiple rows and lookup input is excel sheet

答: You can use the 'Regex evaluation' step and use an expression like ^.*ave.*$ and replacing 'ave' with whatever substring you want to search for. You can then use something like 'Filter rows' to filter out rows that don't match your criteria.

Title: Excel lookup in kettle 7


问:
Finding the full width half maximum of a peak
I have been trying to figure out the full width half maximum (FWHM) of the the blue peak (see image). The green peak and the magenta peak combined make up the blue peak. I have been using the following equation to find the FWHM of the green and magenta peaks: fwhm = 2*np.sqrt(2*(math.log(2)))*sd where sd = standard deviation. I created the green and magenta peaks and I know the standard deviation which is why I can use that equation.

I created the green and magenta peaks using the following code:

```<code>def make_norm_dist(self, x, mean, sd):
    import numpy as np

    norm = []
    for i in range(x.size):
        norm += [1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x[i] - mean)**2/(2*sd**2))]
    return np.array(norm)
</code>```

If I did not know the blue peak was made up of two peaks and I only had the blue peak in my data, how would I find the FWHM?

I have been using this code to find the peak top:

```<code>peak_top = 0.0e-1000
for i in x_axis:
    if i > peak_top:
        peak_top = i
</code>```

I could divide the peak_top by 2 to find the half height and then try and find y-values corresponding to the half height, but then I would run into trouble if there are no x-values exactly matching the half height.

I am pretty sure there is a more elegant solution to the one I am trying.

答:
If you prefer interpolation over fitting:</p>
```<code>import numpy as np

def get_full_width(x: np.ndarray, y: np.ndarray, height: float = 0.5) -> float:
    height_half_max = np.max(y) * height
    index_max = np.argmax(y)
    x_low = np.interp(height_half_max, y[:index_max+1], x[:index_max+1])
    x_high = np.interp(height_half_max, np.flip(y[index_max:]), np.flip(x[index_max:]))

    return x_high - x_low

</code>```

Body:
I have been trying to figure out the full width half maximum (FWHM) of the the blue peak (see image). The green peak and the magenta peak combined make up the blue peak. I have been using the following equation to find the FWHM of the green and magenta peaks: fwhm = 2*np.sqrt(2*(math.log(2)))*sd where sd = standard deviation. I created the green and magenta peaks and I know the standard deviation which is why I can use that equation.

I created the green and magenta peaks using the following code:

def make_norm_dist(self, x, mean, sd):
    import numpy as np

    norm = []
    for i in range(x.size):
        norm += [1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x[i] - mean)**2/(2*sd**2))]
    return np.array(norm)

If I did not know the blue peak was made up of two peaks and I only had the blue peak in my data, how would I find the FWHM?

I have been using this code to find the peak top:

peak_top = 0.0e-1000
for i in x_axis:
    if i > peak_top:
        peak_top = i

I could divide the peak_top by 2 to find the half height and then try and find y-values corresponding to the half height, but then I would run into trouble if there are no x-values exactly matching the half height.

I am pretty sure there is a more elegant solution to the one I am trying.

Body:
If you prefer interpolation over fitting:

import numpy as np

def get_full_width(x: np.ndarray, y: np.ndarray, height: float = 0.5) -> float:
    height_half_max = np.max(y) * height
    index_max = np.argmax(y)
    x_low = np.interp(height_half_max, y[:index_max+1], x[:index_max+1])
    x_high = np.interp(height_half_max, np.flip(y[index_max:]), np.flip(x[index_max:]))

    return x_high - x_low


问:
Alternative routines when using Mercurial Hg
I would like to get your opinion on which of the following routines should I use, or which of them is more desirable, when using Mercurial. Suppose that I have the latest code.

First routine is following:

Do my work

hg commit

Repeat steps 1 and 2 if needed

When I'm ready to push I hg pull, hg update

hg merge, hg commit

hg push

Second is:

Do my work

when I'm ready to commit I hg pull, hg update

hg commit, hg push

The thing is that, as far as I know the first alternative is the one which most of the developers (should) use because, unlike in second option of usage, it provides the opportunity to use local repository, as it is a normal thing for DVCS.

My colleagues encourage me to use the second way, because that way I avoid branching and later possible problems with merging (because in past, somehow, they had such problems), so I stay on trunk development line.
I guess that the first option is the option that should be preferable because merging is something that shouldn't be afraid of in DVCS, unlike in CVCS, and it gives me the opportunity of using local repository.

答:
Basically, you already answered the question yourself:

The first routine is the "default" one for DVCS because it takes advantage of the typical DVCS features

(local repository, faster commits because no network is involved, more detailed history because of many small commits vs. few big ones...)

Using the second routine is not "wrong" or "bad", but you have to be aware of the fact that you're using a DVCS as if it were a CVCS, so you intentionally choose not to use some of the advantages of a DVCS (see above).

People who are long-time CVCS users (like your colleagues, probably) often prefer the second routine because that feels more what they already know.

Plus, merging works better in DVCS than CVCS, so their "possible problems with merging" argument is probably only because they had problems in CVCS in the past and assume it will be the same in DVCS (which is not the case).


问:
C# Rotate a Polygon(Triangle)
I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

```<code>Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);
</code>```

Thanks in advance.

答: You can rotate your polygon if you rotate every point. You also have to find out your rotation center O. Probably you want to use your polygon center as rotation center.</p>

Title: C# Rotate a Polygon(Triangle)

Body:
I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);

Thanks in advance.


问:
Use BeautifulSoup to scrape data but I'm not get data all
I want scrape data in table but nothing data after I request url

```<code>import requests
url='https://iprice.hk/insights/mapofecommerce/iframe/?lang=en&loc=th'
headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'}
r=requests.get(url,headers=headers)
print(r.content.decode())
</code>```
```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content,'html5lib')
</code>```
```<code>table=soup.find('div', attrs={'id':'data'})
</code>```

I failed to retrieve data

```<code>print(table.prettify())
</code>```

I am not sure if it's related to data permission or not.

答:
As Scott Hunter says, pulling the data from the csv is a way out to do this:</p>
```<code>import requests
import csv

download = requests.get('https://ipg-moe.s3-ap-southeast-1.amazonaws.com/th/2021-q3.csv')

decoded_content = download.content.decode('utf-8')

cr = csv.reader(decoded_content.splitlines(), delimiter=',')
rows = list(cr)

# first element of rows are column_names, we'll delete it
del rows[0]

for row in rows:
    print(f'''
    Name: {row[1]}
    Url: {row[2]}
    Traffic: {row[4]}
    iOS: {row[5]}
    Android: {row[6]}
    Line: {row[7]}
    Instagram: {row[8]}
    Facebook: {row[9]}
    Type: {row[10]}
    Category: {row[11]}
    Location: {row[12]}
    ''')
</code>```

Body:
I want scrape data in table but nothing data after I request url

import requests
url='https://iprice.hk/insights/mapofecommerce/iframe/?lang=en&loc=th'
headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'}
r=requests.get(url,headers=headers)
print(r.content.decode())

from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content,'html5lib')

table=soup.find('div', attrs={'id':'data'})

I failed to retrieve data

print(table.prettify())

I am not sure if it's related to data permission or not.

Body:
As Scott Hunter says, pulling the data from the csv is a way out to do this:

import requests
import csv

download = requests.get('https://ipg-moe.s3-ap-southeast-1.amazonaws.com/th/2021-q3.csv')

decoded_content = download.content.decode('utf-8')

cr = csv.reader(decoded_content.splitlines(), delimiter=',')
rows = list(cr)

# first element of rows are column_names, we'll delete it
del rows[0]

for row in rows:
    print(f'''
    Name: {row[1]}
    Url: {row[2]}
    Traffic: {row[4]}
    iOS: {row[5]}
    Android: {row[6]}
    Line: {row[7]}
    Instagram: {row[8]}
    Facebook: {row[9]}
    Type: {row[10]}
    Category: {row[11]}
    Location: {row[12]}
    ''')


问:
Passing data from the form to the server, what to specify in the action
I need to transfer the data from the form to the server (created on the nodeJS express framework), for further use of the data from the forms. But the "send" button should send the user to another html page (I create a chat, the first html is registration, the second is the chat itself, with registration data). What should I specify in the action method in order to transfer data to the index.js server, but at the same time open an html page that is located on a different path.

index.html (registration):

```<code><form action="/index" method="post" class="FORM">
        <label>Username</label><br>
        <input type="TEXT" class="CHECK" autocomplete="off" name="Username"/>
        <button type="submit" onclick="redirect()" class="BTN">Send</button>
    </form>
</code>```

redirect() - initially, when there was no need to send to the server, redirected to the page with the chat (using window.location).

index.js

```<code>const express = require('express');
const app = express();
const db = require('./database/database');
const bodyParser = require('body-parser');
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

const port = 3000;
let id = 0;
let users = {};

const urlencodedParser = bodyParser.urlencoded({
    extended: false,
})
app.use(express.static(__dirname));
app.get('/index', (request, response ) => {
    response.sendFile(__dirname + '/index.html');
});
app.post('/index', urlencodedParser, function (
    request,
    response
) {
    if (!request.body) return response.sendStatus(400)
    console.log(request.body.Username)
})
io.on('connection', (socket) => {
.....
</code>```

答:
The action should be the URL you want to send the form data to.

The end point in your Express code which matches that URL should be responsible for processing the submitting data and sending the response back to the browser.

Typically that response will be the HTML document you want to send back. You might want to issue a redirect response to tell the browser to make a second request to a different URL.

Body:
I need to transfer the data from the form to the server (created on the nodeJS express framework), for further use of the data from the forms. But the "send" button should send the user to another html page (I create a chat, the first html is registration, the second is the chat itself, with registration data). What should I specify in the action method in order to transfer data to the index.js server, but at the same time open an html page that is located on a different path.

index.html (registration):

<form action="/index" method="post" class="FORM">
        Username

        <input type="TEXT" class="CHECK" autocomplete="off" name="Username"/>
        <button type="submit" onclick="redirect()" class="BTN">Send</button>
    </form>

redirect() - initially, when there was no need to send to the server, redirected to the page with the chat (using window.location).

index.js

const express = require('express');
const app = express();
const db = require('./database/database');
const bodyParser = require('body-parser');
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

const port = 3000;
let id = 0;
let users = {};

const urlencodedParser = bodyParser.urlencoded({
    extended: false,
})
app.use(express.static(__dirname));
app.get('/index', (request, response ) => {
    response.sendFile(__dirname + '/index.html');
});
app.post('/index', urlencodedParser, function (
    request,
    response
) {
    if (!request.body) return response.sendStatus(400)
    console.log(request.body.Username)
})
io.on('connection', (socket) => {
.....


问:
What's the Go (mod) equivalent of npm-outdated?
I'd like to keep my go.mod dependencies up to date. With Node.js, I run the npm outdated (and later npm update).

What's the closest for Go mod?

Ideally, I'd see a report of outdated dependencies of my project (not all recursively). Thanks

答:
The problem with built-in go list is that it won't show you new major versions of a dependency. See: https://github.com/golang/go/issues/40323

Here's a tool which shows outdated direct dependencies including new major versions.

https://github.com/icholy/gomajor

Example of running it on Hashicorp's Vault:

```<code>$ gomajor list
cloud.google.com/go: v0.65.0 [latest v0.100.2]
cloud.google.com/go/spanner: v1.5.1 [latest v1.29.0]
cloud.google.com/go/storage: v1.10.0 [latest v1.20.0]
github.com/Azure/go-autorest/autorest: v0.11.21 [latest v0.11.24]
github.com/Azure/go-autorest/autorest/adal: v0.9.14 [latest v0.9.18]
github.com/SAP/go-hdb: v0.14.1 [latest v0.105.5]
github.com/aerospike/aerospike-client-go/v5: v5.6.0 [latest v5.7.0]
github.com/aliyun/alibaba-cloud-sdk-go: v0.0.0-20190620160927-9418d7b0cd0f [latest v1.61.1479]
github.com/aliyun/aliyun-oss-go-sdk: v0.0.0-20190307165228-86c17b95fcd5 [latest v2.2.0+incompatible]
github.com/aws/aws-sdk-go: v1.37.19 [latest v1.42.49]
github.com/cenkalti/backoff/v3: v3.0.0 [latest v4.1.2]
github.com/cockroachdb/cockroach-go: v0.0.0-20181001143604-e0a95dfd547c [latest v2.2.8]
github.com/docker/docker: v20.10.10+incompatible [latest v20.10.12+incompatible]
github.com/go-errors/errors: v1.4.1 [latest v1.4.2]
github.com/go-sql-driver/mysql: v1.5.0 [latest v1.6.0]
github.com/google/go-cmp: v0.5.6 [latest v0.5.7]
github.com/google/go-github: v17.0.0+incompatible [latest v42.0.0]
github.com/google/go-metrics-stackdriver: v0.2.0 [latest v0.4.0]
github.com/hashicorp/consul-template: v0.27.2-0.20211014231529-4ff55381f1c4 [latest v0.27.2]
github.com/hashicorp/consul/api: v1.11.0 [latest v1.12.0]
github.com/hashicorp/go-secure-stdlib/awsutil: v0.1.5 [latest v0.1.6]
github.com/hashicorp/go-secure-stdlib/mlock: v0.1.1 [latest v0.1.2]
github.com/hashicorp/go-secure-stdlib/strutil: v0.1.1 [latest v0.1.2]
github.com/hashicorp/hcl: v1.0.1-vault-3 [latest v2.11.1]
github.com/hashicorp/raft: v1.3.3 [latest v1.3.4]
github.com/hashicorp/raft-autopilot: v0.1.3 [latest v0.1.5]
github.com/hashicorp/raft-boltdb/v2: v2.0.0-20210421194847-a7e34179d62c [latest v2.2.1]
github.com/hashicorp/vault-plugin-auth-kubernetes: v0.7.1-0.20220107030939-d289258274b7 [latest v0.11.5]
github.com/hashicorp/vault-plugin-mock: v0.16.1 [latest v0.19.13]
github.com/hashicorp/vault-plugin-secrets-kv: v0.5.7-0.20220112155832-c2eb38b5f5b6 [latest v0.10.1]
github.com/hashicorp/vault/api/auth/approle: v0.1.0 [latest v0.1.1]
github.com/jefferai/jsonx: v1.0.0 [latest v1.0.1]
github.com/lib/pq: v1.10.3 [latest v1.10.4]
github.com/michaelklishin/rabbit-hole/v2: v2.11.0 [latest v2.12.0]
github.com/mitchellh/copystructure: v1.0.0 [latest v1.2.0]
github.com/mitchellh/go-testing-interface: v1.14.0 [latest v1.14.1]
github.com/mitchellh/go-wordwrap: v1.0.0 [latest v1.0.1]
github.com/mitchellh/mapstructure: v1.4.2 [latest v1.4.3]
github.com/mongodb/go-client-mongodb-atlas: v0.1.2 [latest v0.14.0]
github.com/natefinch/atomic: v0.0.0-20150920032501-a62ce929ffcc [latest v1.0.1]
github.com/ncw/swift: v1.0.47 [latest v2.0.1]
github.com/oklog/run: v1.0.0 [latest v1.1.0]
github.com/okta/okta-sdk-golang/v2: v2.9.1 [latest v2.10.1]
github.com/oracle/oci-go-sdk: v13.1.0+incompatible [latest v57.0.0]
github.com/ory/dockertest: v3.3.5+incompatible [latest v3.8.1]
github.com/ory/dockertest/v3: v3.8.0 [latest v3.8.1]
github.com/pquerna/otp: v1.2.1-0.20191009055518-468c2dd2b58d [latest v1.3.0]
github.com/prometheus/client_golang: v1.11.0 [latest v1.12.1]
github.com/prometheus/common: v0.26.0 [latest v0.32.1]
github.com/ryanuber/columnize: v2.1.0+incompatible [latest v2.1.2+incompatible]
github.com/sasha-s/go-deadlock: v0.2.0 [latest v0.3.1]
github.com/sethvargo/go-limiter: v0.7.1 [latest v0.7.2]
github.com/shirou/gopsutil: v3.21.5+incompatible [latest v3.22.1]
go.etcd.io/etcd/client/pkg/v3: v3.5.0 [latest v3.5.2]
go.etcd.io/etcd/client/v2: v2.305.0 [latest v3.5.2]
go.etcd.io/etcd/client/v3: v3.5.0 [latest v3.5.2]
go.mongodb.org/mongo-driver: v1.7.3 [latest v1.8.3]
go.opentelemetry.io/otel: v0.20.0 [latest v1.3.0]
go.opentelemetry.io/otel/sdk: v0.20.0 [latest v1.3.0]
go.opentelemetry.io/otel/trace: v0.20.0 [latest v1.3.0]
go.uber.org/goleak: v1.1.11-0.20210813005559-691160354723 [latest v1.1.12]
golang.org/x/tools: v0.1.5 [latest v0.1.9]
google.golang.org/api: v0.30.0 [latest v0.68.0]
google.golang.org/grpc: v1.41.0 [latest v1.44.0]
google.golang.org/grpc/cmd/protoc-gen-go-grpc: v1.1.0 [latest v1.2.0]
gopkg.in/ory-am/dockertest.v3: v3.3.4 [latest v3.8.1]
mvdan.cc/gofumpt: v0.1.1 [latest v0.2.1]
</code>```

Body:
The problem with built-in go list is that it won't show you new major versions of a dependency. See: https://github.com/golang/go/issues/40323

Here's a tool which shows outdated direct dependencies including new major versions.

https://github.com/icholy/gomajor

Example of running it on Hashicorp's Vault:

$ gomajor list
cloud.google.com/go: v0.65.0 [latest v0.100.2]
cloud.google.com/go/spanner: v1.5.1 [latest v1.29.0]
cloud.google.com/go/storage: v1.10.0 [latest v1.20.0]
github.com/Azure/go-autorest/autorest: v0.11.21 [latest v0.11.24]
github.com/Azure/go-autorest/autorest/adal: v0.9.14 [latest v0.9.18]
github.com/SAP/go-hdb: v0.14.1 [latest v0.105.5]
github.com/aerospike/aerospike-client-go/v5: v5.6.0 [latest v5.7.0]
github.com/aliyun/alibaba-cloud-sdk-go: v0.0.0-20190620160927-9418d7b0cd0f [latest v1.61.1479]
github.com/aliyun/aliyun-oss-go-sdk: v0.0.0-20190307165228-86c17b95fcd5 [latest v2.2.0+incompatible]
github.com/aws/aws-sdk-go: v1.37.19 [latest v1.42.49]
github.com/cenkalti/backoff/v3: v3.0.0 [latest v4.1.2]
github.com/cockroachdb/cockroach-go: v0.0.0-20181001143604-e0a95dfd547c [latest v2.2.8]
github.com/docker/docker: v20.10.10+incompatible [latest v20.10.12+incompatible]
github.com/go-errors/errors: v1.4.1 [latest v1.4.2]
github.com/go-sql-driver/mysql: v1.5.0 [latest v1.6.0]
github.com/google/go-cmp: v0.5.6 [latest v0.5.7]
github.com/google/go-github: v17.0.0+incompatible [latest v42.0.0]
github.com/google/go-metrics-stackdriver: v0.2.0 [latest v0.4.0]
github.com/hashicorp/consul-template: v0.27.2-0.20211014231529-4ff55381f1c4 [latest v0.27.2]
github.com/hashicorp/consul/api: v1.11.0 [latest v1.12.0]
github.com/hashicorp/go-secure-stdlib/awsutil: v0.1.5 [latest v0.1.6]
github.com/hashicorp/go-secure-stdlib/mlock: v0.1.1 [latest v0.1.2]
github.com/hashicorp/go-secure-stdlib/strutil: v0.1.1 [latest v0.1.2]
github.com/hashicorp/hcl: v1.0.1-vault-3 [latest v2.11.1]
github.com/hashicorp/raft: v1.3.3 [latest v1.3.4]
github.com/hashicorp/raft-autopilot: v0.1.3 [latest v0.1.5]
github.com/hashicorp/raft-boltdb/v2: v2.0.0-20210421194847-a7e34179d62c [latest v2.2.1]
github.com/hashicorp/vault-plugin-auth-kubernetes: v0.7.1-0.20220107030939-d289258274b7 [latest v0.11.5]
github.com/hashicorp/vault-plugin-mock: v0.16.1 [latest v0.19.13]
github.com/hashicorp/vault-plugin-secrets-kv: v0.5.7-0.20220112155832-c2eb38b5f5b6 [latest v0.10.1]
github.com/hashicorp/vault/api/auth/approle: v0.1.0 [latest v0.1.1]
github.com/jefferai/jsonx: v1.0.0 [latest v1.0.1]
github.com/lib/pq: v1.10.3 [latest v1.10.4]
github.com/michaelklishin/rabbit-hole/v2: v2.11.0 [latest v2.12.0]
github.com/mitchellh/copystructure: v1.0.0 [latest v1.2.0]
github.com/mitchellh/go-testing-interface: v1.14.0 [latest v1.14.1]
github.com/mitchellh/go-wordwrap: v1.0.0 [latest v1.0.1]
github.com/mitchellh/mapstructure: v1.4.2 [latest v1.4.3]
github.com/mongodb/go-client-mongodb-atlas: v0.1.2 [latest v0.14.0]
github.com/natefinch/atomic: v0.0.0-20150920032501-a62ce929ffcc [latest v1.0.1]
github.com/ncw/swift: v1.0.47 [latest v2.0.1]
github.com/oklog/run: v1.0.0 [latest v1.1.0]
github.com/okta/okta-sdk-golang/v2: v2.9.1 [latest v2.10.1]
github.com/oracle/oci-go-sdk: v13.1.0+incompatible [latest v57.0.0]
github.com/ory/dockertest: v3.3.5+incompatible [latest v3.8.1]
github.com/ory/dockertest/v3: v3.8.0 [latest v3.8.1]
github.com/pquerna/otp: v1.2.1-0.20191009055518-468c2dd2b58d [latest v1.3.0]
github.com/prometheus/client_golang: v1.11.0 [latest v1.12.1]
github.com/prometheus/common: v0.26.0 [latest v0.32.1]
github.com/ryanuber/columnize: v2.1.0+incompatible [latest v2.1.2+incompatible]
github.com/sasha-s/go-deadlock: v0.2.0 [latest v0.3.1]
github.com/sethvargo/go-limiter: v0.7.1 [latest v0.7.2]
github.com/shirou/gopsutil: v3.21.5+incompatible [latest v3.22.1]
go.etcd.io/etcd/client/pkg/v3: v3.5.0 [latest v3.5.2]
go.etcd.io/etcd/client/v2: v2.305.0 [latest v3.5.2]
go.etcd.io/etcd/client/v3: v3.5.0 [latest v3.5.2]
go.mongodb.org/mongo-driver: v1.7.3 [latest v1.8.3]
go.opentelemetry.io/otel: v0.20.0 [latest v1.3.0]
go.opentelemetry.io/otel/sdk: v0.20.0 [latest v1.3.0]
go.opentelemetry.io/otel/trace: v0.20.0 [latest v1.3.0]
go.uber.org/goleak: v1.1.11-0.20210813005559-691160354723 [latest v1.1.12]
golang.org/x/tools: v0.1.5 [latest v0.1.9]
google.golang.org/api: v0.30.0 [latest v0.68.0]
google.golang.org/grpc: v1.41.0 [latest v1.44.0]
google.golang.org/grpc/cmd/protoc-gen-go-grpc: v1.1.0 [latest v1.2.0]
gopkg.in/ory-am/dockertest.v3: v3.3.4 [latest v3.8.1]
mvdan.cc/gofumpt: v0.1.1 [latest v0.2.1]


问:
Python print statement problem. Print function not working
I am working on a percentage calculator that does everything like it counts profit, loss, profit percent, loss percent on given circumstances.

```<code>
CP = input("Is Cost Price given?\n").lower
SP = input("Is Selling Price given?\n").lower
PROFIT = input("Is Profit in amoung given?\n").lower
LOSS = input("Is Loss in amount given?\n").lower
PROFIT_PERCENT = input("Is Profit in percentage given?\n").lower
LOSS_PERCENT = input("Is Loss in percent given?\n").lower

if CP == SP == PROFIT == LOSS == PROFIT_PERCENT == LOSS_PERCENT == "yes":
    print("Everything is given man.")
time.sleep(3)
exit()
</code>```

Here it asks for multiple things. Now I wanted to code that if all the values are given yes then it prints there is no need. But there is a problem. The print statement is not displayed. The code works fine there are no errors even but the print statement doesnt appear at all.

答: Change all .lower to .lower().

Body:
I am working on a percentage calculator that does everything like it counts profit, loss, profit percent, loss percent on given circumstances.

CP = input("Is Cost Price given?\n").lower
SP = input("Is Selling Price given?\n").lower
PROFIT = input("Is Profit in amoung given?\n").lower
LOSS = input("Is Loss in amount given?\n").lower
PROFIT_PERCENT = input("Is Profit in percentage given?\n").lower
LOSS_PERCENT = input("Is Loss in percent given?\n").lower

if CP == SP == PROFIT == LOSS == PROFIT_PERCENT == LOSS_PERCENT == "yes":
    print("Everything is given man.")
time.sleep(3)
exit()

Here it asks for multiple things. Now I wanted to code that if all the values are given yes then it prints there is no need. But there is a problem. The print statement is not displayed. The code works fine there are no errors even but the print statement doesnt appear at all.

Body: Change all .lower to .lower().


问:
escaping single quotes the escape character vanishes during the process using sed
```<code>#/!bin/sh
# infile is "person's clothes"
infile=$1
outfile=$2
sed -z "s|'|\\\\'|g;" <$infile >temp.txt
txt=`cat temp.txt`
echo $txt
# displays person\'s clothes
sed -e "s|paste_area|$txt|" blank.html >"$outfile"
# the relevant part of $outfile is "person's clothes" expecting "person\'s clothes"
</code>```
<p>"please add some context to explain the code sections" please read the code it has comments included</p>

答:
You need to double all the backslashes in $txt to make them literal when used in the sed replacement string. Otherwise they'll be treated as the escape prefix.

```<code>sed -e "s|paste_area|${txt/\\/\\\\}|" blank.html >"$outfile"
</code>```

Body:
#/!bin/sh
# infile is "person's clothes"
infile=$1
outfile=$2
sed -z "s|'|\\\\'|g;" <$infile >temp.txt
txt=`cat temp.txt`
echo $txt
# displays person\'s clothes
sed -e "s|paste_area|$txt|" blank.html >"$outfile"
# the relevant part of $outfile is "person's clothes" expecting "person\'s clothes"

"please add some context to explain the code sections" please read the code it has comments included

Body:
You need to double all the backslashes in $txt to make them literal when used in the sed replacement string. Otherwise they'll be treated as the escape prefix.

sed -e "s|paste_area|${txt/\\/\\\\}|" blank.html >"$outfile"


问:
Can't go into object defined by rollup plugin-replace
In a Svelte component, I'm trying to access an object I set up in my rollup config file.
My rollup.config.js file looks like this:

import replace from '@rollup/plugin-replace';

...
export default {
...
    replace({
        foo: JSON.stringify({ bar: 'Hello' }),
    }),

...
```

In my Svelte component, a simple console.log(foo) works:

But when I try to go into that foo object like console.log(foo.bar), I get foo is not defined:

答:
This section of the document explains your exact problem.

https://github.com/rollup/plugins/tree/master/packages/replace#delimiters

The delimiters option controls how the strings will be matched. With the default delimiters being ['\b', '\b(?!\.)'], it would only replace foo if it follows a word boundary and is followed by a word boundary that is not a dot. Hence with your rollup.config.js the behaviour would be

console.log(foo)
// becomes
console.log({"bar":"Hello"})

console.log(foo.bar)
// is not replaced by the plugin as `foo` IS followed by a dot

console.log(foo['bar'])
console.log(foo .bar) // space after `foo`
// both satisfy the delimiter check again and print: Hello
// (horrible coding style in the latter but to illustrate how it works)

const { bar } = foo
// also satisfy the delimiter check hence
console.log(bar) // prints: Hello
```
<p>As you see, the replace plugin doesn't really parse your code but instead only preforms simple text replacement not too different from the search-and-replace feature of your IDE/editor. Gauss what would it say below?</p>
<pre class="lang-js prettyprint-override"><code>console.log('foo')
// Guess what?
// ...
// ...
// printed: {"bar":"Hello"}
// as if it were
console.log('{"bar":"Hello"}')
</code>```

To conclude, your workaround might be

foo['bar'],

const { bar } = foo,

avoid object replacement and use keys like __FOO_BAR__, __FOO_BAZ__, ...

pass delimiters: ['\\b', '\\b'] to allow dots following the key.

(However at the moment of writing, the last one doesn't seem to work yet due to a bugfix waiting to be merged).

https://github.com/rollup/plugins/pull/1088

If you use delimiters: ['', ''] the earlier caveat requires much higher level of caution. Even a string literal 'food' or a HTML template tag  might be changed to gibberish like '{"bar":"Hello"}d' or <{"bar":"Hello"}ter>. So name your keys wisely or use some unusual delimiters depending on your usage, like what the old version of the plugin once demonstrated: delimiters: ['<@', '@>'].

https://github.com/rollup/rollup-plugin-replace

Nevertheless since these kind of preprocessing is pretty rudimentary, care is always needed when adding replaced keys and when using them.

Body:
In a Svelte component, I'm trying to access an object I set up in my rollup config file.
My rollup.config.js file looks like this:

import replace from '@rollup/plugin-replace';

...
export default {
...
    replace({
        foo: JSON.stringify({ bar: 'Hello' }),
    }),

...

In my Svelte component, a simple console.log(foo) works:

But when I try to go into that foo object like console.log(foo.bar), I get foo is not defined:

Body:
This section of the document explains your exact problem.

https://github.com/rollup/plugins/tree/master/packages/replace#delimiters

The delimiters option controls how the strings will be matched. With the default delimiters being ['\b', '\b(?!\.)'], it would only replace foo if it follows a word boundary and is followed by a word boundary that is not a dot. Hence with your rollup.config.js the behaviour would be

console.log(foo)
// becomes
console.log({"bar":"Hello"})

console.log(foo.bar)
// is not replaced by the plugin as `foo` IS followed by a dot

console.log(foo['bar'])
console.log(foo .bar) // space after `foo`
// both satisfy the delimiter check again and print: Hello
// (horrible coding style in the latter but to illustrate how it works)

const { bar } = foo
// also satisfy the delimiter check hence
console.log(bar) // prints: Hello

As you see, the replace plugin doesn't really parse your code but instead only preforms simple text replacement not too different from the search-and-replace feature of your IDE/editor. Gauss what would it say below?

console.log('foo')
// Guess what?
// ...
// ...
// printed: {"bar":"Hello"}
// as if it were
console.log('{"bar":"Hello"}')

To conclude, your workaround might be

foo['bar'],

const { bar } = foo,

avoid object replacement and use keys like __FOO_BAR__, __FOO_BAZ__, ...

pass delimiters: ['\\b', '\\b'] to allow dots following the key.

(However at the moment of writing, the last one doesn't seem to work yet due to a bugfix waiting to be merged).

https://github.com/rollup/plugins/pull/1088

If you use delimiters: ['', ''] the earlier caveat requires much higher level of caution. Even a string literal 'food' or a HTML template tag <footer> might be changed to gibberish like '{"bar":"Hello"}d' or <{"bar":"Hello"}ter>. So name your keys wisely or use some unusual delimiters depending on your usage, like what the old version of the plugin once demonstrated: delimiters: ['<@', '@>'].

https://github.com/rollup/rollup-plugin-replace

Nevertheless since these kind of preprocessing is pretty rudimentary, care is always needed when adding replaced keys and when using them.


问:
How to invoke a REST API when an object arrives on S3?
S3 can be configured to invoke lambda when an object arrives in it.

Is it possible to invoke a REST API (endpoint of a microservice running in EKS) when an object arrives in S3?

答:
From November 2021 is possible to integrate S3 with Amazon EventBridge.
So you can create an EventBridge rule which is triggered on bucket object creation and has API destination as a target.

For this, the option Bucket Properties -> Amazon EventBridge -> "Send notifications to Amazon EventBridge for all events in this bucket" should be enabled.

Then, on EventBridge create the rule with an event pattern like this:

```<code>{
  "source": ["aws.s3"],
  "detail-type": ["Object Created"],
  "detail": {
    "bucket": {
      "name": ["<my-bucket-name>"]
    }
  }
}
</code>```

And configure the target as API destination endpoint (configure http method, endpoint, authorization).

Body:
From November 2021 is possible to integrate S3 with Amazon EventBridge.
So you can create an EventBridge rule which is triggered on bucket object creation and has API destination as a target.

For this, the option Bucket Properties -> Amazon EventBridge -> "Send notifications to Amazon EventBridge for all events in this bucket" should be enabled.

Then, on EventBridge create the rule with an event pattern like this:

{
  "source": ["aws.s3"],
  "detail-type": ["Object Created"],
  "detail": {
    "bucket": {
      "name": ["<my-bucket-name>"]
    }
  }
}

And configure the target as API destination endpoint (configure http method, endpoint, authorization).


问:
How to get lilypond to generate glissando in midi output
My lilypond snippet generates a score, containing a glissando (slide from one pitch to another) correctly. It generates a midi file, but it doesn't sound like a slide from one pitch to another. It sounds like 2 distinct pitches. My instrument is set to violin.

What is the correct way to generate glissando in midi file?

```<code>\version "2.18.2"
\include "articulate.ly"

\score {
  \articulate
  <<
  \new Staff {
    \set Staff.midiInstrument = #"violin"

    \relative a' {
      a4 \glissando d
    }
  }
  >>
  \layout { }
  \midi { }

}
</code>```

答:
LilyPond can't produce a midi glissando automatically, (even in the latest version 2.23), but you can make one manually:

The trick is to use seperate score blocks for the pdf and midi, and to use tags that are filtered out of these blocks (with \removeWithTag).

```<code>\version "2.18.2"
\include "articulate.ly"

contents = {
    <<
        \new Staff {
            \set Staff.midiInstrument = #"violin"
            \relative a' {
                \tag #'pdfonly {
                    a4 \glissando^\markup{\italic"gliss."} d r2 |
                }
                \tag #'midionly {
                    \tuplet 5/4 {a16 ais b c cis} d4 r2 |
                }
            }
        }
    >>
}

% PDF
\score {
    \removeWithTag #'midionly
    \contents
    \layout { }
}

% MIDI
\score {
    \removeWithTag #'pdfonly
    \articulate
    \contents
    \midi { }
}

</code>```

I've used a \tuplet to fit in all of the discrete pitches between the notes.  A really glissando will not be discrete but this is as good as you can get with a midi.

I've also moved the \articulate.ly script into the midi block.  It makes sense to apply this script the midi, but it messes up the pdf.

Body:
My lilypond snippet generates a score, containing a glissando (slide from one pitch to another) correctly. It generates a midi file, but it doesn't sound like a slide from one pitch to another. It sounds like 2 distinct pitches. My instrument is set to violin.

What is the correct way to generate glissando in midi file?

\version "2.18.2"
\include "articulate.ly"

\score {
  \articulate
  <<
  \new Staff {
    \set Staff.midiInstrument = #"violin"

    \relative a' {
      a4 \glissando d
    }
  }
  >>
  \layout { }
  \midi { }

}

Body:
LilyPond can't produce a midi glissando automatically, (even in the latest version 2.23), but you can make one manually:

The trick is to use seperate score blocks for the pdf and midi, and to use tags that are filtered out of these blocks (with \removeWithTag).

\version "2.18.2"
\include "articulate.ly"

contents = {
    <<
        \new Staff {
            \set Staff.midiInstrument = #"violin"
            \relative a' {
                \tag #'pdfonly {
                    a4 \glissando^\markup{\italic"gliss."} d r2 |
                }
                \tag #'midionly {
                    \tuplet 5/4 {a16 ais b c cis} d4 r2 |
                }
            }
        }
    >>
}

% PDF
\score {
    \removeWithTag #'midionly
    \contents
    \layout { }
}

% MIDI
\score {
    \removeWithTag #'pdfonly
    \articulate
    \contents
    \midi { }
}

I've used a \tuplet to fit in all of the discrete pitches between the notes.  A really glissando will not be discrete but this is as good as you can get with a midi.

I've also moved the \articulate.ly script into the midi block.  It makes sense to apply this script the midi, but it messes up the pdf.


问:
Variables aren't passing from one function to another why?
I'm a Python beginner and trying to build upon my code below. I have the base working and want to collect the data from the calculator and store it in a dictionary. I created the last function to do this, but I can't pass the variables from bmi_metrics(). Why?</p>
```<code>#Intro to BMI Calculator
print("Welcome to my BMI calculator!")
print("Give me your height and weight, I'll calculate your Body Mass Index")

# Gather BMI metrics from user and create two loops that only accept number inputs for height/weight
def bmi_metrics():
    get_name = (input("\nWhat's your name?  "))

    while True:
        try:
            get_height = float(input(f"\nHi {get_name.title()}, please enter your height in inches: "))
            break
        except ValueError:
            print("Oops, that doesn't look like a number, try again.")
    while True:
        try:
            get_weight = float(input("Please enter your weight in pounds: "))
            break
        except ValueError:
            print("Oops, that doesn't look like a number, try again.")

   #Calculate BMI from height and weight input
    BMI = (get_weight  * 703) / (get_height ** 2)

    #Display user BMI and weight category back to them
    print(f"{get_name.title()}, your BMI is {BMI:.2f}")
    if BMI <= 18.5:
        print(f"A person with a BMI of {BMI:.2f} is underwieght ")
    elif BMI <= 24.9:
        print(f"A person with a BMI of {BMI:.2f} is normal weight ")
    elif BMI <= 29.9:
        print(f"A person with a BMI of {BMI:.2f} is overweight ")
    else:
        print(f"A person with a BMI of {BMI:.2f} is obese")

    return get_name, get_height, get_weight, BMI

#Prompt user to run calculator again
def prompt_again():
    while True:
        run_again = input("\nWould you like to do another calculation (y/n)? ")
        if run_again == 'y':
            bmi_metrics()
        elif run_again == 'Y':
            bmi_metrics()
        elif run_again == 'N':
            break
        elif run_again == 'n':
            break
        else:
            print("Please enter 'y' or 'n' ")
    print("Thanks for playing!")

#Collect Name/BMI data and place it in an empty dictionary
def calc_data():
    calc_results = {"Name": " ", "BMI": " "}
    get_name = name

bmi_metrics()
prompt_again()
</code>```

答:
Hello :) You are missing the storage of the returned values from the call at the end of the script:

```<code>get_name, get_height, get_weight, BMI = bmi_metrics()
</code>```

Otherwise, the result is not stored. You have to keep in mind that all variables in python defined inside a method are local to the method unless you store them in an object, return them as result of the method or define them as global variables. If you want to use the resulting values in another function you need to pass them as arguments.

Body:
I'm a Python beginner and trying to build upon my code below. I have the base working and want to collect the data from the calculator and store it in a dictionary. I created the last function to do this, but I can't pass the variables from bmi_metrics(). Why?

#Intro to BMI Calculator
print("Welcome to my BMI calculator!")
print("Give me your height and weight, I'll calculate your Body Mass Index")

# Gather BMI metrics from user and create two loops that only accept number inputs for height/weight
def bmi_metrics():
    get_name = (input("\nWhat's your name?  "))

    while True:
        try:
            get_height = float(input(f"\nHi {get_name.title()}, please enter your height in inches: "))
            break
        except ValueError:
            print("Oops, that doesn't look like a number, try again.")
    while True:
        try:
            get_weight = float(input("Please enter your weight in pounds: "))
            break
        except ValueError:
            print("Oops, that doesn't look like a number, try again.")

   #Calculate BMI from height and weight input
    BMI = (get_weight  * 703) / (get_height ** 2)

    #Display user BMI and weight category back to them
    print(f"{get_name.title()}, your BMI is {BMI:.2f}")
    if BMI <= 18.5:
        print(f"A person with a BMI of {BMI:.2f} is underwieght ")
    elif BMI <= 24.9:
        print(f"A person with a BMI of {BMI:.2f} is normal weight ")
    elif BMI <= 29.9:
        print(f"A person with a BMI of {BMI:.2f} is overweight ")
    else:
        print(f"A person with a BMI of {BMI:.2f} is obese")

    return get_name, get_height, get_weight, BMI

#Prompt user to run calculator again
def prompt_again():
    while True:
        run_again = input("\nWould you like to do another calculation (y/n)? ")
        if run_again == 'y':
            bmi_metrics()
        elif run_again == 'Y':
            bmi_metrics()
        elif run_again == 'N':
            break
        elif run_again == 'n':
            break
        else:
            print("Please enter 'y' or 'n' ")
    print("Thanks for playing!")

#Collect Name/BMI data and place it in an empty dictionary
def calc_data():
    calc_results = {"Name": " ", "BMI": " "}
    get_name = name

bmi_metrics()
prompt_again()

Body:
Hello :) You are missing the storage of the returned values from the call at the end of the script:

get_name, get_height, get_weight, BMI = bmi_metrics()

Otherwise, the result is not stored. You have to keep in mind that all variables in python defined inside a method are local to the method unless you store them in an object, return them as result of the method or define them as global variables. If you want to use the resulting values in another function you need to pass them as arguments.


问:
The mean value of the binary file array elements
I need to write function which will write elements of array into binary file, and after that find the mean value of elements of binary file.

```<code>#include <stdio.h>
double enterArray(){
    int i=0,n;
    double a[101];
    FILE* fp=fopen("niz.bin", "w");
    while(1){
        scanf("%lf", &a[i]);
        if(a[i]==-1)break;
        i++;
        if(i==100)break;
    }
    n=i;
    for (i=0; i<n; i++)
   fwrite(a,4, n, fp);
    fclose(fp);
  return 0;
}
double meanValue(){
  return 1;
}
int main() {
    enterArray();
    printf("%g\n", meanValue());
    return 0;
}
</code>```

I get some random characters in niz.bin file. Could you help me fix my code?

答:
There are a few problems with the code.

You take an arbitrary number of doubles, and then write the first n * 4 bytes in the array "repeatedly" to the file.

You don't know for sure that sizeof (double) is equal to 4 bytes.

On every iteration, you write (n * 4) bytes from the array a to the file.

What you want is, starting from i * sizeof (double), write sizeof (double) bytes to the file (if you want to use a loop. You could simply just write (n * sizeof (double) bytes to the file at once)

You use the "w" mode in fopen, which is not the "write binary" mode. Use "wb" instead.

Then, in meanValue(), you don't do anything. Writing/reading a 10-element double array to/from a binary file can be done in the following way:

    /* write to the file */
    double write_arr[10] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
    FILE *fp = fopen("niz.bin", "wb");
    fwrite(&write_arr, sizeof(double), 10, fp);
    fclose(fp);

    /* read from the file */
    fp = fopen("niz.bin", "rb");
    double read_arr[10];
    fread(&read_arr, sizeof (double), 10, fp);
```

Also, note that you must identify how many elements you're going to write to the file, as you write the bytes in the file without knowing how many to write in advance. As you don't write the elements immediately, you could serialize the number of elements in the first 4 bytes in the file. And when you read from it, read the first 4 bytes to know how many doubles lying ahead.

Body:
I need to write function which will write elements of array into binary file, and after that find the mean value of elements of binary file.

#include <stdio.h>
double enterArray(){
    int i=0,n;
    double a[101];
    FILE* fp=fopen("niz.bin", "w");
    while(1){
        scanf("%lf", &a[i]);
        if(a[i]==-1)break;
        i++;
        if(i==100)break;
    }
    n=i;
    for (i=0; i<n; i++)
   fwrite(a,4, n, fp);
    fclose(fp);
  return 0;
}
double meanValue(){
  return 1;
}
int main() {
    enterArray();
    printf("%g\n", meanValue());
    return 0;
}

I get some random characters in niz.bin file. Could you help me fix my code?

Body:
There are a few problems with the code.

You take an arbitrary number of doubles, and then write the first n * 4 bytes in the array "repeatedly" to the file.

You don't know for sure that sizeof (double) is equal to 4 bytes.

On every iteration, you write (n * 4) bytes from the array a to the file.

What you want is, starting from i * sizeof (double), write sizeof (double) bytes to the file (if you want to use a loop. You could simply just write (n * sizeof (double) bytes to the file at once)

You use the "w" mode in fopen, which is not the "write binary" mode. Use "wb" instead.

Then, in meanValue(), you don't do anything. Writing/reading a 10-element double array to/from a binary file can be done in the following way:

    /* write to the file */
    double write_arr[10] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
    FILE *fp = fopen("niz.bin", "wb");
    fwrite(&write_arr, sizeof(double), 10, fp);
    fclose(fp);

    /* read from the file */
    fp = fopen("niz.bin", "rb");
    double read_arr[10];
    fread(&read_arr, sizeof (double), 10, fp);

Also, note that you must identify how many elements you're going to write to the file, as you write the bytes in the file without knowing how many to write in advance. As you don't write the elements immediately, you could serialize the number of elements in the first 4 bytes in the file. And when you read from it, read the first 4 bytes to know how many doubles lying ahead.


问:
How do I watch a file for changes?
I have a log file being written by another process which I want to watch for changes. Each time a change occurs I'd like to read the new data in to do some processing on it.

What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the win32file.FindNextChangeNotification function but have no idea how to ask it to watch a specific file.

If anyone's done anything like this I'd be really grateful to hear how...

[Edit] I should have mentioned that I was after a solution that doesn't require polling.

[Edit] Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.

答:
The easiest solution would get the two instances of the same file after an interval and Compare them. You Could try something like this</p>
```<code>    while True:
        # Capturing the two instances models.py after certain interval of time
        print("Looking for changes in " + app_name.capitalize() + " models.py\nPress 'CTRL + C' to stop the program")
        with open(app_name.capitalize() + '/filename', 'r+') as app_models_file:
            filename_content = app_models_file.read()
        time.sleep(5)
        with open(app_name.capitalize() + '/filename', 'r+') as app_models_file_1:
            filename_content_1 = app_models_file_1.read()
        # Comparing models.py after certain interval of time
        if filename_content == filename_content_1:
            pass
        else:
            print("You made a change in " + app_name.capitalize() + " filename.\n")
            cmd = str(input("Do something with the file?(y/n):"))
            if cmd == 'y':
                # Do Something
            elif cmd == 'n':
                # pass or do something
            else:
                print("Invalid input")
</code>```

OwnerDisplayName: Jon Cage

Title: How do I watch a file for changes?

LastEditorDisplayName: Jon Cage

Body:
The easiest solution would get the two instances of the same file after an interval and Compare them. You Could try something like this

    while True:
        # Capturing the two instances models.py after certain interval of time
        print("Looking for changes in " + app_name.capitalize() + " models.py\nPress 'CTRL + C' to stop the program")
        with open(app_name.capitalize() + '/filename', 'r+') as app_models_file:
            filename_content = app_models_file.read()
        time.sleep(5)
        with open(app_name.capitalize() + '/filename', 'r+') as app_models_file_1:
            filename_content_1 = app_models_file_1.read()
        # Comparing models.py after certain interval of time
        if filename_content == filename_content_1:
            pass
        else:
            print("You made a change in " + app_name.capitalize() + " filename.\n")
            cmd = str(input("Do something with the file?(y/n):"))
            if cmd == 'y':
                # Do Something
            elif cmd == 'n':
                # pass or do something
            else:
                print("Invalid input")