问:
Can not print out the elements of an array in a for-loop
Why can not I print out the elements of an array in a for-loop?
My environment is Windows 7 Maximum,
gcc (MinGW.org GCC-6.3.0-1) 6.3.0
I input the data from the prompt like 3 1 2 3.
I can do, e.g., printf("%" PRId64 " ", marray[2]) but from the for-loop it doesn't work.

Here is the source code:

```<code>#define __USE_MINGW_ANSI_STDIO 1
#define __STDC_FORMAT_MACROS 1

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

size_t read_size() {
    size_t x;
    scanf("%lu", &x);
    return x;
}

int64_t read_int64() {
    int64_t x;
    scanf("%" SCNd64, &x);
    return x;
}

int main() {
    size_t *size;
    *size = read_size();
    int64_t *marray = malloc(sizeof(int64_t) * *size);
    for (size_t i = 0; i < *size; i++) {
        marray[i] = read_int64();
    }

    for (size_t i = 0; i < *size; i++) {
        printf("%" PRId64 " ", marray[i]);
    }
    free(marray);
    return 0;
}
</code>```

答:
First, in main() you have:

```<code>size_t *size;  //creating an uninitialized pointer
</code>```

then you call

```<code>*size = read_size();
^ (dereferencing an uninitialized pointer
</code>```

which will result in undefined behavior. (read about nasal demons here.  Essentially anything can happen here.  On my system, it was a run-time error. ( ...Local 'size' was referenced before being initialized. )  Note:  If you do not see something similar, turn on your compiler warnings.

So, as pointed out in comments, using a pointer here is not the right approach anyway...

```<code>*size = read_size();
</code>```

Suggest changing the following:

```<code>size_t read_size(){
    size_t x;
    scanf("%lu", &x);
    return x;
}
</code>```

To:

```<code>size_t read_size(void){//note, its portable to include `void` in `void` prototypes
    size_t x;
    scanf("%zu", &x); //zu, not lu for size_t format specifier
    return x;
}
</code>```

Then call it like this:

```<code>//size_t* size;
size_t size = read_size();
</code>```

Then also change these :

```<code>int64_t* marray = malloc(sizeof(int64_t)**size);
...
for (size_t i = 0; i < *size; i++){
</code>```

to:

```<code>int64_t* marray = malloc(sizeof(int64_t) * size);
if(marray)
{//always verify successful call before attempting to use memory
...
for (size_t i = 0; i < size; i++){//removed the dereference on size
</code>```

EDIT - comments indicate need to create 2D array dynamically:

comments indicate that your intention is that

```<code>int64_t* marray = malloc(sizeof(int64_t)**size);
</code>```

creates a two dimension array.  That statement will only create a single dimension array, and likely not of the size that you think.

In general, create a pointer to the array, then create pointers to the each column... (for example, without knowing both dimensions, the following will create both to be size)

```<code>int rows = size
int cols = size
int64_t **marray = malloc(sizeof(int64_t) * rows*cols);
if(!marray)//handle error
{
      for(int i = 0; i < cols ; i++)
      {
           marray[i] = malloc( rows * sizeof(int64_t));
           if(!marray[i]) //handle error;
      }
}
</code>```

This method approximates the method indicated in comments, however IMO this is not the best way.  It creates non-contiguous blocks of memory for each call to malloc, and requires one call to free() for each call to malloc().  A much better approach is here. (Uses only one call to malloc()/free() to create and free a 2D array.)

Body:
Why can not I print out the elements of an array in a for-loop?
My environment is Windows 7 Maximum,
gcc (MinGW.org GCC-6.3.0-1) 6.3.0
I input the data from the prompt like 3 1 2 3.
I can do, e.g., printf("%" PRId64 " ", marray[2]) but from the for-loop it doesn't work.

Here is the source code:

#define __USE_MINGW_ANSI_STDIO 1
#define __STDC_FORMAT_MACROS 1

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

size_t read_size() {
    size_t x;
    scanf("%lu", &x);
    return x;
}

int64_t read_int64() {
    int64_t x;
    scanf("%" SCNd64, &x);
    return x;
}

int main() {
    size_t *size;
    *size = read_size();
    int64_t *marray = malloc(sizeof(int64_t) * *size);
    for (size_t i = 0; i < *size; i++) {
        marray[i] = read_int64();
    }

    for (size_t i = 0; i < *size; i++) {
        printf("%" PRId64 " ", marray[i]);
    }
    free(marray);
    return 0;
}

Body:
First, in main() you have:

size_t *size;  //creating an uninitialized pointer

then you call

*size = read_size();
^ (dereferencing an uninitialized pointer

which will result in undefined behavior. (read about nasal demons here.  Essentially anything can happen here.  On my system, it was a run-time error. ( ...Local 'size' was referenced before being initialized. )  Note:  If you do not see something similar, turn on your compiler warnings.

So, as pointed out in comments, using a pointer here is not the right approach anyway...

*size = read_size();

Suggest changing the following:

size_t read_size(){
    size_t x;
    scanf("%lu", &x);
    return x;
}

To:

size_t read_size(void){//note, its portable to include `void` in `void` prototypes
    size_t x;
    scanf("%zu", &x); //zu, not lu for size_t format specifier
    return x;
}

Then call it like this:

//size_t* size;
size_t size = read_size();

Then also change these :

int64_t* marray = malloc(sizeof(int64_t)**size);
...
for (size_t i = 0; i < *size; i++){

to:

int64_t* marray = malloc(sizeof(int64_t) * size);
if(marray)
{//always verify successful call before attempting to use memory
...
for (size_t i = 0; i < size; i++){//removed the dereference on size

EDIT - comments indicate need to create 2D array dynamically:

comments indicate that your intention is that

int64_t* marray = malloc(sizeof(int64_t)**size);

creates a two dimension array.  That statement will only create a single dimension array, and likely not of the size that you think.

In general, create a pointer to the array, then create pointers to the each column... (for example, without knowing both dimensions, the following will create both to be size)

int rows = size
int cols = size
int64_t **marray = malloc(sizeof(int64_t) * rows*cols);
if(!marray)//handle error
{
      for(int i = 0; i < cols ; i++)
      {
           marray[i] = malloc( rows * sizeof(int64_t));
           if(!marray[i]) //handle error;
      }
}

This method approximates the method indicated in comments, however IMO this is not the best way.  It creates non-contiguous blocks of memory for each call to malloc, and requires one call to free() for each call to malloc().  A much better approach is here. (Uses only one call to malloc()/free() to create and free a 2D array.)


来源: stackexchange

问:
NSTextAttachment images are not dynamic (light/dark mode)
I have an image that is dynamic for light/dark mode. If I place this image in a UIImageView, the dynamism works: when the user switches from light to dark mode and back, the image changes the version of itself that is displayed. But if I place the same image in an NSAttributedString as an NSTextAttachment and display the string in a label, the dynamism does not work: when the user switches from light to dark mode, the image does not change.

To see the problem in action, paste this code into your viewDidLoad:

```<code>    let size = CGSize(width: 20, height: 20)
    let renderer = UIGraphicsImageRenderer(size: size)
    let image1 = renderer.image {
        UIColor.red.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let image2 = renderer.image {
        UIColor.green.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let asset = UIImageAsset()
    asset.register(image1, with: .init(userInterfaceStyle: .light))
    asset.register(image2, with: .init(userInterfaceStyle: .dark))

    let iv = UIImageView(image: image1)
    iv.frame.origin = .init(x: 100, y: 100)
    self.view.addSubview(iv)

    let text = NSMutableAttributedString(string: "Howdy ", attributes: [
        .foregroundColor: UIColor(dynamicProvider: { traits in
            switch traits.userInterfaceStyle {
            case .light: return .red
            case .dark: return .green
            default: return .red
            }
        })
    ])
    let attachment = NSTextAttachment(image: image1)
    let attachmentCharacter = NSAttributedString(attachment: attachment)
    text.append(attachmentCharacter)

    let label = UILabel()
    label.attributedText = text
    label.sizeToFit()
    label.frame.origin = .init(x: 100, y: 150)
    self.view.addSubview(label)
</code>```

I have deliberately made the text font color dynamic so that you can see that in general color dynamism does work in an attributed string. But not in an attributed string's text attachment!

So: Is this really how iOS behaves, or am I making some mistake in the way I'm configuring the text attachment? If this is how iOS behaves, how are you working around the issue?

[Note that I cannot use an iOS 15 attachment view provider, because I have to be compatible with iOS 13 and 14. So maybe that would solve the problem, but that solution is not open to me.]

答:
I think that's unfortunately the normal behavior, but I considered it as a forgotten feature non-dev by Apple.

The only way I got currently, is to listen to func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) to detect the mode change.

Then, you can either reconstruct your NSAttributedString, or enumerate over it and update it when needed.

With a enumeration, ie update only what's needed, and not regenerate the whole NSAttributedString:

In your initial attachment creation:

```<code>let attachment = NSTextAttachment(image: asset.image(with: traitCollection))
let attachmentCharacter = NSAttributedString(attachment: attachment)
</code>```

Side note:
I used asset.image(with: traitCollection) instead of image1, else when starting with dark mode, your image will be of light mode instead. So this should set the correct image.

Then, I'd update it with:

```<code>func switchAttachment(for attr: NSAttributedString?) -> NSAttributedString? {
    guard let attr = attr else { return nil }
    let mutable = NSMutableAttributedString(attributedString: attr)
    mutable.enumerateAttribute(.attachment, in: NSRange(location: 0, length: mutable.length), options: []) { attachment, range, stop in
        guard let attachment = attachment as? NSTextAttachment else { return }
        guard let asset = attachment.image?.imageAsset else { return }
        attachment.image = asset.image(with: .current)
        mutable.replaceCharacters(in: range, with: NSAttributedString(attachment: attachment))
    }
    return mutable
}
</code>```

And update when:

```<code>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    label.attributedText = switchAttachment(for: label.attributedText)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an image that is dynamic for light/dark mode. If I place this image in a UIImageView, the dynamism works: when the user switches from light to dark mode and back, the image changes the version of itself that is displayed. But if I place the same image in an NSAttributedString as an NSTextAttachment and display the string in a label, the dynamism does not work: when the user switches from light to dark mode, the image does not change.

To see the problem in action, paste this code into your viewDidLoad:

    let size = CGSize(width: 20, height: 20)
    let renderer = UIGraphicsImageRenderer(size: size)
    let image1 = renderer.image {
        UIColor.red.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let image2 = renderer.image {
        UIColor.green.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let asset = UIImageAsset()
    asset.register(image1, with: .init(userInterfaceStyle: .light))
    asset.register(image2, with: .init(userInterfaceStyle: .dark))

    let iv = UIImageView(image: image1)
    iv.frame.origin = .init(x: 100, y: 100)
    self.view.addSubview(iv)

    let text = NSMutableAttributedString(string: "Howdy ", attributes: [
        .foregroundColor: UIColor(dynamicProvider: { traits in
            switch traits.userInterfaceStyle {
            case .light: return .red
            case .dark: return .green
            default: return .red
            }
        })
    ])
    let attachment = NSTextAttachment(image: image1)
    let attachmentCharacter = NSAttributedString(attachment: attachment)
    text.append(attachmentCharacter)

    let label = UILabel()
    label.attributedText = text
    label.sizeToFit()
    label.frame.origin = .init(x: 100, y: 150)
    self.view.addSubview(label)

I have deliberately made the text font color dynamic so that you can see that in general color dynamism does work in an attributed string. But not in an attributed string's text attachment!

So: Is this really how iOS behaves, or am I making some mistake in the way I'm configuring the text attachment? If this is how iOS behaves, how are you working around the issue?

[Note that I cannot use an iOS 15 attachment view provider, because I have to be compatible with iOS 13 and 14. So maybe that would solve the problem, but that solution is not open to me.]

Body:
I think that's unfortunately the normal behavior, but I considered it as a forgotten feature non-dev by Apple.

The only way I got currently, is to listen to func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) to detect the mode change.

Then, you can either reconstruct your NSAttributedString, or enumerate over it and update it when needed.

With a enumeration, ie update only what's needed, and not regenerate the whole NSAttributedString:

In your initial attachment creation:

let attachment = NSTextAttachment(image: asset.image(with: traitCollection))
let attachmentCharacter = NSAttributedString(attachment: attachment)

Side note:
I used asset.image(with: traitCollection) instead of image1, else when starting with dark mode, your image will be of light mode instead. So this should set the correct image.

Then, I'd update it with:

func switchAttachment(for attr: NSAttributedString?) -> NSAttributedString? {
    guard let attr = attr else { return nil }
    let mutable = NSMutableAttributedString(attributedString: attr)
    mutable.enumerateAttribute(.attachment, in: NSRange(location: 0, length: mutable.length), options: []) { attachment, range, stop in
        guard let attachment = attachment as? NSTextAttachment else { return }
        guard let asset = attachment.image?.imageAsset else { return }
        attachment.image = asset.image(with: .current)
        mutable.replaceCharacters(in: range, with: NSAttributedString(attachment: attachment))
    }
    return mutable
}

And update when:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    label.attributedText = switchAttachment(for: label.attributedText)
}


问:
Websocket sending blob object instead of string
I am somehow able to run Websocket but the problem is that it is sending me object blob on on message event while i want to send the text.

Here is my websocket server code:

```<code>const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 })

var sockets = [];

wss.on('connection', ws => {
    //var id = ws.upgradeReq.headers['sec-websocket-key'];
    //console.log("New connection id ::", id);
    //w.send(id);
    sockets.push(ws);
    console.log("New client connected"+ ws);

  ws.on('message', message => {

    console.log(`Received message => ${message}`)

    //var id = ws.upgradeReq.headers['sec-websocket-key'];
    //var mes = JSON.parse(message);

    //sockets[message.to].send(mes.message);
     // console.log('Message on :: ', id);
    //console.log('On message :: ', message);
    sockets.forEach(w=> {
        w.send(message);
    });
  })

  ws.send('Welcome by server!')
})
</code>```

Client side Code Excerpt

```<code>connection.onmessage = (e) => {
  document.getElementById("ReceviedText").innerHTML += ("<li>" + e.data + "</li>");

   // ReceviedText
  console.log(e.data);
  console.log(e);

  var reader = new FileReader(e.data);
  console.log(reader.result);

  //console.log(reader.readAsText());
  console.log(reader.readAsText(e.data));

}
</code>```

I found that I can convert blob to string using file reader but it returning null.

答:
FileReader.readAsText() is an event based API, as mentioned in MDN docs.

So you need to set reader.onload:

```<code>  const reader = new FileReader();
  reader.onload = function(evt) {
    console.log(evt.target.result);
  };
  reader.readAsText(e.data);
</code>```

Also, Blob.text() can be used.

```<code>websocket.addEventListener("message", e => {
    e.data.text().then(txt=>console.log(txt))
});
</code>```

Docs describes the difference between these two:

Blob.text() returns a promise, whereas FileReader.readAsText() is an
event based API. Blob.text() always uses UTF-8 as encoding, while
FileReader.readAsText() can use a different encoding depending on the
blob's type and a specified encoding name.

Body:
I am somehow able to run Websocket but the problem is that it is sending me object blob on on message event while i want to send the text.

Here is my websocket server code:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 })

var sockets = [];

wss.on('connection', ws => {
    //var id = ws.upgradeReq.headers['sec-websocket-key'];
    //console.log("New connection id ::", id);
    //w.send(id);
    sockets.push(ws);
    console.log("New client connected"+ ws);

  ws.on('message', message => {

    console.log(`Received message => ${message}`)

    //var id = ws.upgradeReq.headers['sec-websocket-key'];
    //var mes = JSON.parse(message);

    //sockets[message.to].send(mes.message);
     // console.log('Message on :: ', id);
    //console.log('On message :: ', message);
    sockets.forEach(w=> {
        w.send(message);
    });
  })

  ws.send('Welcome by server!')
})

Client side Code Excerpt

connection.onmessage = (e) => {
  document.getElementById("ReceviedText").innerHTML += ("
" + e.data + "
");

   // ReceviedText
  console.log(e.data);
  console.log(e);

  var reader = new FileReader(e.data);
  console.log(reader.result);

  //console.log(reader.readAsText());
  console.log(reader.readAsText(e.data));

}

I found that I can convert blob to string using file reader but it returning null.

Body:
FileReader.readAsText() is an event based API, as mentioned in MDN docs.

So you need to set reader.onload:

  const reader = new FileReader();
  reader.onload = function(evt) {
    console.log(evt.target.result);
  };
  reader.readAsText(e.data);

Also, Blob.text() can be used.

websocket.addEventListener("message", e => {
    e.data.text().then(txt=>console.log(txt))
});

Docs describes the difference between these two:

Blob.text() returns a promise, whereas FileReader.readAsText() is an
event based API. Blob.text() always uses UTF-8 as encoding, while
FileReader.readAsText() can use a different encoding depending on the
blob's type and a specified encoding name.


问:
Creating new column based on minimum value on another column - R
So I have a dataframe structured like this:

```<code>df <- data.frame("id" = c(rep("a",4),rep("b",4)),
                 "Year" = c(2020,2019,2018,2017,
                            2020,2019,2018,2017),
                 "value" = c(30,20,0,0,
                             70,50,30,0))

> df
  id Year value
1  a 2020    30
2  a 2019    20
3  a 2018     0
4  a 2017     0
5  b 2020    70
6  b 2019    50
7  b 2018    30
8  b 2017     0
</code>```

What I want to do is create a new column which has the same values as the value column, except wherever there is a 0 value it looks at the closest year with a non-zero value and applies that value to all 0 rows by each id. So the output should be:

```<code>> df
  id Year value newoutput
1  a 2020    30        30
2  a 2019    20        20
3  a 2018     0        20
4  a 2017     0        20
5  b 2020    70        70
6  b 2019    50        50
7  b 2018    30        30
8  b 2017     0        30
</code>```

So for id a we see that years 2018, 2017 both have 0 values so need to be amended. The next year which has a non zero value is 2019, so we take the value in that year which is 20 and apply it to both 2018, 2017. Similar for id b.

Any ideas on how to do this using dplyr?

答:
A possible solution, based on dplyr and cummax:

library(dplyr)

df %>%
  group_by(id) %>%
  mutate(newoutput = value + cummax((value == 0) * lag(value, default = T))) %>%
  ungroup

#> # A tibble: 8 × 4
#>   id     Year value newoutput
#>   <chr> <dbl> <dbl>     <dbl>
#> 1 a      2020    30        30
#> 2 a      2019    20        20
#> 3 a      2018     0        20
#> 4 a      2017     0        20
#> 5 b      2020    70        70
#> 6 b      2019    50        50
#> 7 b      2018    30        30
#> 8 b      2017     0        30
```

Body:
So I have a dataframe structured like this:

df <- data.frame("id" = c(rep("a",4),rep("b",4)),
                 "Year" = c(2020,2019,2018,2017,
                            2020,2019,2018,2017),
                 "value" = c(30,20,0,0,
                             70,50,30,0))

> df
  id Year value
1  a 2020    30
2  a 2019    20
3  a 2018     0
4  a 2017     0
5  b 2020    70
6  b 2019    50
7  b 2018    30
8  b 2017     0

What I want to do is create a new column which has the same values as the value column, except wherever there is a 0 value it looks at the closest year with a non-zero value and applies that value to all 0 rows by each id. So the output should be:

> df
  id Year value newoutput
1  a 2020    30        30
2  a 2019    20        20
3  a 2018     0        20
4  a 2017     0        20
5  b 2020    70        70
6  b 2019    50        50
7  b 2018    30        30
8  b 2017     0        30

So for id a we see that years 2018, 2017 both have 0 values so need to be amended. The next year which has a non zero value is 2019, so we take the value in that year which is 20 and apply it to both 2018, 2017. Similar for id b.

Any ideas on how to do this using dplyr?


问:
Vuetify Combobox add new item as object instead of string
I am building a new/edit item form using Vuetify(v2.6.3). My form has multiple combobox's that pull their items from a backend API as objects. I would like to be able to add new items, which the combobox is able to do. However, when I add a new item it's added as a string. Is there a way to add that new item as an object instead?

I only need the new object to have a name key in order to send it to the API to be created

Desired New item from v-combobox:

{
  name: 'New Item',
}
```
<p>Simplified list of items returned from API and available as combobox choices:</p>
<pre class="lang-js prettyprint-override"><code>[
  {
    id: 1,
    name: 'Item 1',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 2,
    name: 'Item 2',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 3,
    name: 'Item 3',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  }
]
</code>```

Here is a simplified version of my Form:

<template>
  <v-card>
    <v-card-title>
      Edit Item
    </v-card-title>
    <v-card-text>
      <v-container>
        <v-row>
          <v-col>
            <v-combobox
              v-model="item"
              :items="items"
              item-text="name"
              item-value="id"
              label="ComboBox"
              return-object
            ></v-combobox>
          </v-col>
        </v-row>
      </v-container>
    </v-card-text>
  </v-card>
</template>

```

In my method which sends the form to the API, I could check the value of each combobox and convert to an object if needed, but I am wondering if it's possible to handle it in the combobox component.

答:
It does not appear that a ComboBox can directly return an object when adding a new item. However it looks like you can leverage the input event of the component to run a method that converts to an object.

Here is how I call the method on the component's input event:

<v-combobox
  v-model="item"
  :items="items"
  item-text="name"
  item-value="id"
  label="ComboBox"
  return-object
  @input="makeObject"
></v-combobox>
```
<p><code>@input="makeObject"</code> listens for the component's <code>input</code> event and calls the <code>makeObject</code> method and passes the currently selected item</p>
<p>Then I was able to write a method which checks if the combobox value is a string. If so then it converts it to an object</p>
<pre class="lang-html prettyprint-override"><code><script>
export default {
  name: "TestForm",
  data() {
    return {
      item: null
      // Remaining code omitted for readability
    }
  }
  methods: {
    makeObject(val) {
      if (typeof val === "string") {
        this.item = {
          name: val,
        };
      }
    },
  },
};
</script>
</code>```

Here is my full component:

<template>
  <v-card>
    <v-card-title>
      Edit Item
    </v-card-title>
    <v-card-text>
      <v-container>
        <v-row>
          <v-col>
            <v-combobox
              v-model="item"
              :items="items"
              item-text="name"
              item-value="id"
              label="ComboBox"
              return-object
              @input="makeObject"
            ></v-combobox>
          </v-col>
        </v-row>
      </v-container>
    </v-card-text>
    <v-card-text>
      {{ item }}
    </v-card-text>
  </v-card>
</template>

```

sandbox link

Body:
I am building a new/edit item form using Vuetify(v2.6.3). My form has multiple combobox's that pull their items from a backend API as objects. I would like to be able to add new items, which the combobox is able to do. However, when I add a new item it's added as a string. Is there a way to add that new item as an object instead?

I only need the new object to have a name key in order to send it to the API to be created

Desired New item from v-combobox:

{
  name: 'New Item',
}

Simplified list of items returned from API and available as combobox choices:

[
  {
    id: 1,
    name: 'Item 1',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 2,
    name: 'Item 2',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  },
  {
    id: 3,
    name: 'Item 3',
    createdAt: '2020-01-01',
    updatedAt: '2020-01-01'
  }
]

Here is a simplified version of my Form:

<template>
  <v-card>
    <v-card-title>
      Edit Item
    </v-card-title>
    <v-card-text>
      <v-container>
        <v-row>
          <v-col>
            <v-combobox
              v-model="item"
              :items="items"
              item-text="name"
              item-value="id"
              label="ComboBox"
              return-object
            ></v-combobox>
          </v-col>
        </v-row>
      </v-container>
    </v-card-text>
  </v-card>
</template>

In my method which sends the form to the API, I could check the value of each combobox and convert to an object if needed, but I am wondering if it's possible to handle it in the combobox component.

Body:
It does not appear that a ComboBox can directly return an object when adding a new item. However it looks like you can leverage the input event of the component to run a method that converts to an object.

Here is how I call the method on the component's input event:

<v-combobox
  v-model="item"
  :items="items"
  item-text="name"
  item-value="id"
  label="ComboBox"
  return-object
  @input="makeObject"
></v-combobox>

@input="makeObject" listens for the component's input event and calls the makeObject method and passes the currently selected item

Then I was able to write a method which checks if the combobox value is a string. If so then it converts it to an object

<script>
export default {
  name: "TestForm",
  data() {
    return {
      item: null
      // Remaining code omitted for readability
    }
  }
  methods: {
    makeObject(val) {
      if (typeof val === "string") {
        this.item = {
          name: val,
        };
      }
    },
  },
};
</script>

Here is my full component:

<template>
  <v-card>
    <v-card-title>
      <span class="text-h5">Edit Item</span>
    </v-card-title>
    <v-card-text>
      <v-container>
        <v-row>
          <v-col>
            <v-combobox
              v-model="item"
              :items="items"
              item-text="name"
              item-value="id"
              label="ComboBox"
              return-object
              @input="makeObject"
            ></v-combobox>
          </v-col>
        </v-row>
      </v-container>
    </v-card-text>
    <v-card-text>
      {{ item }}
    </v-card-text>
  </v-card>
</template>
<script>
export default {
  name: "TestForm",
  data() {
    return {
      item: null,
      items: [
        {
          id: 1,
          name: "Item 1",
          createdAt: "2020-01-01",
          updatedAt: "2020-01-01",
        },
        {
          id: 2,
          name: "Item 2",
          createdAt: "2020-01-01",
          updatedAt: "2020-01-01",
        },
        {
          id: 3,
          name: "Item 3",
          createdAt: "2020-01-01",
          updatedAt: "2020-01-01",
        },
      ],
    };
  },
  methods: {
    makeObject(val) {
      if (typeof val === "string") {
        this.item = {
          name: val,
        };
      }
    },
  },
};
</script>

sandbox link


问:
Does adding a foreign key to an indexed column boost performance?
A colleague claims that he used foreign keys to optimize queries in past. I think that foreign keys are used only when inserting or updating data in a table. I don't see how they can be used to speed up the search.

How can a foreign key help when creating an execution plan? Am I missing something? If so, then under what circumstances does it help?

(We use PostgreSQL, which I don't have much experience with. Is it possible that it behaves differently than, say, Oracle or MySQL?)

答:
Without an index on foreign key(s) the whole child table needs to be scanned to verify if any rows are referencing the key(s) you're trying to delete or update in the parent (i.e. foreign) table.

So yes, in this particular case having indexes will greatly improve performance.

ContentLicense: CC BY-SA 3.0


问:
Case insensitive duplicates SQL
So I have a users table where the user.username has many duplicates like:

username and Username and useRnAme

john and John and jOhn

That was a bug and these three records should have been only one.

I'm trying to come up with a SQL query that lists all of these cases ordered by their creation date, so ideally the result should be something like this:

```<code>username jan01
useRnAme jan02
Username jan03
john     feb01
John     feb02
jOhn     feb03
</code>```

Any suggestions will be much appreciated

答:
so this is what i came up with. this was written against a postgres db but should work fine still against other sql engine.

```<code>select * from user u join user u2
on upper(u.email)=upper(u2.email) where u.id != u2.id
order by u.email;
</code>```

so the query assume that the email are duplicate but the ids are not so it is looking to pull records with a duplicate email (case insensitive) but with unique id

ContentLicense: CC BY-SA 2.5

Title: Case insensitive duplicates SQL

Body:
So I have a users table where the user.username has many duplicates like:

username and Username and useRnAme

john and John and jOhn

That was a bug and these three records should have been only one.

I'm trying to come up with a SQL query that lists all of these cases ordered by their creation date, so ideally the result should be something like this:

username jan01
useRnAme jan02
Username jan03
john     feb01
John     feb02
jOhn     feb03

Any suggestions will be much appreciated

Body:
so this is what i came up with. this was written against a postgres db but should work fine still against other sql engine.

select * from user u join user u2
on upper(u.email)=upper(u2.email) where u.id != u2.id
order by u.email;

so the query assume that the email are duplicate but the ids are not so it is looking to pull records with a duplicate email (case insensitive) but with unique id


问:
AES encryption error: The input data is not a complete block?
Here's the encryption method:

```<code>public static byte[] Encrypt(byte[] plaintext, byte[] key)
{
    using (var aes = Aes.Create())
    {
        aes.BlockSize = 128;
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.None;

        var iv = new byte[16];
        for (int i = 0; i < iv.Length; i++)
            iv[i] = 0;
        aes.IV = iv;

        var encryptor = aes.CreateEncryptor(key, aes.IV);
        using(var target = new MemoryStream())
        using (var cs = new CryptoStream(target, encryptor, CryptoStreamMode.Write))
        {
            using (var source = new StreamWriter(cs))
                source.Write(plaintext);
            return target.ToArray();
        }
    }
}
</code>```

And how I'm calling it:

```<code>var key = new byte[16] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var plaintext = new byte[16] { 128, 0, 112, 0, 96, 0, 80, 0, 64, 0, 48, 0, 32, 0, 16, 0 };
</code>```

But it keeps throwing an exception at source.Write(plaintext) that says it's not a complete block? I'm using a 16 byte/ 128 bit array with the block size set to 128. I don't understand what's wrong?

Also, just to head off any suggestions that ECB is bad etc, this is not for production, I'm just playing around.

答: From what I have experienced and fixed this issue, I missed to encrypt the field that it is complaining about, I was only decrypting it. It was saving a plain clear text and trying to decrypt it. So just make sure that the field that is complaining about is encrypted first. Thanks</p>

Body:
Here's the encryption method:

public static byte[] Encrypt(byte[] plaintext, byte[] key)
{
    using (var aes = Aes.Create())
    {
        aes.BlockSize = 128;
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.None;

        var iv = new byte[16];
        for (int i = 0; i < iv.Length; i++)
            iv[i] = 0;
        aes.IV = iv;

        var encryptor = aes.CreateEncryptor(key, aes.IV);
        using(var target = new MemoryStream())
        using (var cs = new CryptoStream(target, encryptor, CryptoStreamMode.Write))
        {
            using (var source = new StreamWriter(cs))
                source.Write(plaintext);
            return target.ToArray();
        }
    }
}

And how I'm calling it:

var key = new byte[16] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var plaintext = new byte[16] { 128, 0, 112, 0, 96, 0, 80, 0, 64, 0, 48, 0, 32, 0, 16, 0 };

But it keeps throwing an exception at source.Write(plaintext) that says it's not a complete block? I'm using a 16 byte/ 128 bit array with the block size set to 128. I don't understand what's wrong?

Also, just to head off any suggestions that ECB is bad etc, this is not for production, I'm just playing around.


问:
Set up auto provisioning for custom SAML Web app in Google workspace
I am trying to set up a custom SAML Web app with auto provisioning in my google admin. I am able to create an custom SAML Web app but the auto provisioning feature is not available. As per this community link there are a bunch of other apps which provide auto provisioning. I couldn’t find a way to setup a custom one.

I am creating a custom SAML Web app by following steps:

Logging into google admin

App -> Web and Mobile Apps -> Add App -> Add custom SAML App

Below is how it looks after i create few apps already present in the apps list and when i create a custom SAML App. The custom app clearly does not have the User auto provisioning or there is a setting for the same which i am missing.

How do i set up auto provisioning for custom SAML Web app?
Please help!

答:
Currently there is no support for auto-provisioning on custom SAML apps. In their release blog post Google explains how this works:

Following this launch, admins will be able to set up automated user provisioning and deprovisioning for Salesforce.com and other apps (with support for more applications coming soon).

These are apps that they are specifically adding support to. Since then they have been steadily adding more apps to their catalog, but it's still a predefined list. All SPs have different APIs to provision users so it is probably not so easy to create an interface that will be able to connect with any of them, so Google seems to be sticking to implementing them one by one.

The link that you shared contains another link to Apps that support automated provisioning, which has the full list of supported apps. Any app outside of this list won't have auto-provisioning available.


问:
How to break my For loops into Parallel.For loops?
I have 3 For loops running for a lot of iterations:

```<code>for (int i = 0; i < 1000000; i++)
{
    for (int j = 0; j < 1000000; j++)
    {
      var myObj = new MyObj(i,j);
      var a = myObj.doSomething();
      for (int k = 0; k < 1000000; k++)
      {
       a.work();
      }
    }
}
</code>```

I have to run a total of 10^18 iterations which will take a lot of time to complete.

Is there a fast way to make the loops run faster using Parallel.For? If so - how to change my code?

答:
If the work to be done is too fine-grained, the overhead associated with parallelism might be bigger than the gain from parallel execution. Therefore, using Parallel.For only for the outer loop is sufficient. It has the advantage to create greater chunks of work and to minimize the overhead.

That still adds up to 1 million tasks that need to be performed in parallel. That's pretty much enough.

var options = new ParallelOptions {
    MaxDegreeOfParallelism = Environment.ProcessorCount
};
var result = Parallel.For(0, 1000000, options, (i, state) =>
{
    for (int j = 0; j < 1000000; j++)
    {
        var myObj = new MyObj(i,j);
        var a = myObj.doSomething();
        for (int k = 0; k < 1000000; k++)
        {
            a.work();
        }
    }
});
```

But note that if a.work() uses resources, that require exclusive access, then the locking involved might ruin the advantage.

It is advisable to limit the degree of parallelism to the processor count if the work is mainly CPU bound.

Body:
I have 3 For loops running for a lot of iterations:

for (int i = 0; i < 1000000; i++)
{
    for (int j = 0; j < 1000000; j++)
    {
      var myObj = new MyObj(i,j);
      var a = myObj.doSomething();
      for (int k = 0; k < 1000000; k++)
      {
       a.work();
      }
    }
}

I have to run a total of 10^18 iterations which will take a lot of time to complete.

Is there a fast way to make the loops run faster using Parallel.For? If so - how to change my code?

Body:
If the work to be done is too fine-grained, the overhead associated with parallelism might be bigger than the gain from parallel execution. Therefore, using Parallel.For only for the outer loop is sufficient. It has the advantage to create greater chunks of work and to minimize the overhead.

That still adds up to 1 million tasks that need to be performed in parallel. That's pretty much enough.

var options = new ParallelOptions {
    MaxDegreeOfParallelism = Environment.ProcessorCount
};
var result = Parallel.For(0, 1000000, options, (i, state) =>
{
    for (int j = 0; j < 1000000; j++)
    {
        var myObj = new MyObj(i,j);
        var a = myObj.doSomething();
        for (int k = 0; k < 1000000; k++)
        {
            a.work();
        }
    }
});

But note that if a.work() uses resources, that require exclusive access, then the locking involved might ruin the advantage.

It is advisable to limit the degree of parallelism to the processor count if the work is mainly CPU bound.


问:
Can't iterate through a list in python
After recieving data from mysql connector, when I try to iterate over the list, python keeps telling me the data is of type int:

The execute() and fetchall() statements:

```<code>def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for i in len(s):
            print(i)
</code>```

The above code exits with:

```<code>[('beep', Decimal('3')), ('item1', Decimal('39')), ('Mask', Decimal('53')), ('Mask1', Decimal('2'))]
<class 'list'>
Traceback (most recent call last):
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 326, in <module>
    main(id, password)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 324, in main
    x.load_prompt(acc_type)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 301, in load_prompt
    self.stats()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 243, in stats
    self.top_sellers()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 265, in top_sellers
    for i in len(list(s)):
TypeError: 'int' object is not iterable
</code>```

答:
Instead of iterating through the array by using the len() function, you can iterate using blank variables. Len() is for integers, and there are strings in your list. If I were you I would do...

```<code>def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for row in self:
            for elem in row:
                print(elem)

</code>```

And will return...

```<code>beep
3
item1
39
Mask
53
Mask1
2
</code>```

If you wanted to print "('beep', '3')", just get rid of "for elem in row" and move the print statement into the other for statement.

Title: Can't iterate through a list in python

Body:
After recieving data from mysql connector, when I try to iterate over the list, python keeps telling me the data is of type int:

The execute() and fetchall() statements:

def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for i in len(s):
            print(i)

The above code exits with:

[('beep', Decimal('3')), ('item1', Decimal('39')), ('Mask', Decimal('53')), ('Mask1', Decimal('2'))]
<class 'list'>
Traceback (most recent call last):
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 326, in <module>
    main(id, password)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 324, in main
    x.load_prompt(acc_type)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 301, in load_prompt
    self.stats()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 243, in stats
    self.top_sellers()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 265, in top_sellers
    for i in len(list(s)):
TypeError: 'int' object is not iterable

Body:
Instead of iterating through the array by using the len() function, you can iterate using blank variables. Len() is for integers, and there are strings in your list. If I were you I would do...

def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for row in self:
            for elem in row:
                print(elem)

And will return...

beep
3
item1
39
Mask
53
Mask1
2

If you wanted to print "('beep', '3')", just get rid of "for elem in row" and move the print statement into the other for statement.


问:
Iterate through a string to find matching characters and produce different emoji
How do I call contains_char from my emojified function?

I want to be able to iterate through the guess_word to see if there are any matching letters in the secret_word. If there are matching letters, the output should have green emoji boxes. If there are no matching letters, the output should have white emoji boxes. If there are letters present but they are not in the right position, the output should have yellow boxes.

```<code>def contains_char(any_length: str, single_character: str) -> bool:
    """Loop iterates through each character in string to find matching character."""
    assert len(single_character) == 1
    if single_character in any_length:
        return True
    else:
        return False

def emojified(guess_word: str, secret_word: str) -> str:
    """A way to match letters to its corresponding emoji color output. """
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\U00002B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    emoji_color: str = ""
    i: int = 0
    contains_char
    while i < len(guess_word):
        if guess_word[0] == secret_word[0]:
            emoji_color += GREEN_BOX
        else:
            emoji_color += WHITE_BOX

        print(emoji_color)

</code>```

I want the output to look like this picture below. Thank you!

答:
You are vastly overcomplicating this.

```<code>def emojified(guess_word: str, secret_word: str) -> str:
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\u2B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    output: list = []
    this_box: str = ''
    for i, char in enumerate(guess_word):
        if i < len(secret_word) and secret_word[i] == char:
            this_box = GREEN_BOX
        elif char in secret_word:
            this_box = YELLOW_BOX
        else:
            this_box = WHITE_BOX
        output.append(this_box)
    return ''.join(output)
</code>```

The assert is perhaps not the best way to handle this; Python can disable assert statements in some situations. If the check should be part of your production logic, probably refactor it to raise an exception instead.

The condition i < len(secret_word) is redundant if you make sure both strings are the same length, but I thought it safer to leave it in in case you want to relax that condition.

Appending to strings is relatively expensive, so a good practice is to collect things into a list and only join the list into a string at the end.

Body:
How do I call contains_char from my emojified function?

I want to be able to iterate through the guess_word to see if there are any matching letters in the secret_word. If there are matching letters, the output should have green emoji boxes. If there are no matching letters, the output should have white emoji boxes. If there are letters present but they are not in the right position, the output should have yellow boxes.

def contains_char(any_length: str, single_character: str) -> bool:
    """Loop iterates through each character in string to find matching character."""
    assert len(single_character) == 1
    if single_character in any_length:
        return True
    else:
        return False

def emojified(guess_word: str, secret_word: str) -> str:
    """A way to match letters to its corresponding emoji color output. """
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\U00002B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    emoji_color: str = ""
    i: int = 0
    contains_char
    while i < len(guess_word):
        if guess_word[0] == secret_word[0]:
            emoji_color += GREEN_BOX
        else:
            emoji_color += WHITE_BOX

        print(emoji_color)

I want the output to look like this picture below. Thank you!

Body:
You are vastly overcomplicating this.

def emojified(guess_word: str, secret_word: str) -> str:
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\u2B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    output: list = []
    this_box: str = ''
    for i, char in enumerate(guess_word):
        if i < len(secret_word) and secret_word[i] == char:
            this_box = GREEN_BOX
        elif char in secret_word:
            this_box = YELLOW_BOX
        else:
            this_box = WHITE_BOX
        output.append(this_box)
    return ''.join(output)

The assert is perhaps not the best way to handle this; Python can disable assert statements in some situations. If the check should be part of your production logic, probably refactor it to raise an exception instead.

The condition i < len(secret_word) is redundant if you make sure both strings are the same length, but I thought it safer to leave it in in case you want to relax that condition.

Appending to strings is relatively expensive, so a good practice is to collect things into a list and only join the list into a string at the end.


问:
Flatten only part of a dataframe shape for Euclidean calculation?
I have a data frame with shape:

```<code>(20,30,1024)
</code>```

I want to find the Euclidean distance between every entry and every other entry in the dataframe (ideally non-redundantly, i.e. don't find the distance of row 1 and 5....and then row 5 and 1 but not there yet). I have this code:

```<code>from scipy.spatial.distance import pdist,squareform

distances = pdist(df_test,metric='euclidean')
dist_matrix = squareform(distances)

print(dist_matrix)
</code>```

The error says:

```<code>A 2-dimensional array must be passed.
</code>```

So I guess I want to convert my matrix from shape (20,30,1024) to (20,30720), and then calculate the pdist/squareform between the rows (i.e. 20 rows of vectors that are 30720 in length).

I know that I can use test_df[0:20].flatten().tolist()

But that completely flattened my matrix, the output shape was (1,614400).

Can someone show me how to convert a shape from (20,30,1024) to (20,3072), or if i'm not going about this the right way?

The ultimate end goal is to calculate Euclidean distance between all non-redundant pairs in a data set, but the data set is big, so I need to do it as efficiently as possible/not duplicating calculations.

答:
The most straightforward way to reshape that I can think of, according to how you described the problem, is:

```<code>df_test.values.reshape(20, -1)
</code>```

By calling .values, you are retrieving your dataframe data as a numpy array. From there, .reshape finishes your job. Since you need a 2D-array, you provide the size of the first dimension (in your case, 20), and by passing -1 Numpy will calculate the size of the second dimension for you (in this case it will multiply the remaining dimension sizes in the original 3D-array)

Body:
I have a data frame with shape:

(20,30,1024)

I want to find the Euclidean distance between every entry and every other entry in the dataframe (ideally non-redundantly, i.e. don't find the distance of row 1 and 5....and then row 5 and 1 but not there yet). I have this code:

from scipy.spatial.distance import pdist,squareform

distances = pdist(df_test,metric='euclidean')
dist_matrix = squareform(distances)

print(dist_matrix)

The error says:

A 2-dimensional array must be passed.

So I guess I want to convert my matrix from shape (20,30,1024) to (20,30720), and then calculate the pdist/squareform between the rows (i.e. 20 rows of vectors that are 30720 in length).

I know that I can use test_df[0:20].flatten().tolist()

But that completely flattened my matrix, the output shape was (1,614400).

Can someone show me how to convert a shape from (20,30,1024) to (20,3072), or if i'm not going about this the right way?

The ultimate end goal is to calculate Euclidean distance between all non-redundant pairs in a data set, but the data set is big, so I need to do it as efficiently as possible/not duplicating calculations.

Body:
The most straightforward way to reshape that I can think of, according to how you described the problem, is:

df_test.values.reshape(20, -1)

By calling .values, you are retrieving your dataframe data as a numpy array. From there, .reshape finishes your job. Since you need a 2D-array, you provide the size of the first dimension (in your case, 20), and by passing -1 Numpy will calculate the size of the second dimension for you (in this case it will multiply the remaining dimension sizes in the original 3D-array)


问:
dao recordset updating the wrong record
I'm trying to have a form usable for both creating a new record or updating another. Currently it is doing it through the value of a textbox (new or edit). The structure works fine, but for some reason, when it is performing the edit function, it is saving changes to the wrong record. For instance, if I am editing record 1027, when i submit it, it'll update record 1073. Its consistent, it'll always update the same, wrong record. Edit 1000, it'll update 1073; if i update 1081, it'll update 1073, and so on. Is there a way to specify which record it should be editing? yes, the record number is the primary key/id. Heres the code:</p>

```<code>Private Sub btnSubmit_Click()

 Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim strTable As String
    Dim strField As String
    Dim ID As Long
    Dim newID As Long

    strTable = "record_holdData"
    Set db = CurrentDb
    Set rs = db.OpenRecordset(strTable)

'button has 2 modes
If txtMode.Value = "NEW" Then

    With rs
        .AddNew
        .Fields("PO_no") = txtPONum
        .Fields("prodSupervisor") = cboProdSup
        .Fields("qaSupervisor") = cboQASup
        .Fields("labTech") = cboLabTech
        .Fields("flavor") = cboFlavor
        .Fields("lineNumber") = cboLineNumber
        .Fields("container") = cboContainer
        .Fields("package") = cboPackage
        .Fields("holdQty") = txtQty
        .Fields("productionDate") = txtProdDate
        .Fields("dateCode") = txtDatecode
        .Fields("component") = cboComponent
        .Fields("nonconformance") = cboDiscrepancy
        .Fields("foundDuring") = cboFoundAt
        .Fields("responsibility") = cboRespCode
        .Fields("comments") = txtDescription
        .Fields("rootCause") = txtRootCause
        .Fields("holdStatus") = 1
        .Fields("dateOpened") = Now()
        .Update
        .Bookmark = .LastModified
        newID = !ID
    End With

        MsgBox ("Hold information saved!")
        btnPrintTag.Enabled = True
        DoCmd.OpenReport "Holdtag", acViewPreview, , "[ID] = " & newID
        DoCmd.Close

ElseIf txtMode.Value = "EDIT" Then
    'do editing stuff
    With rs
        .Edit
        .Fields("PO_no") = txtPONum
        .Fields("prodSupervisor") = cboProdSup
        .Fields("qaSupervisor") = cboQASup
        .Fields("labTech") = cboLabTech
        .Fields("flavor") = cboFlavor
        .Fields("lineNumber") = cboLineNumber
        .Fields("container") = cboContainer
        .Fields("package") = cboPackage
        .Fields("holdQty") = txtQty
        .Fields("productionDate") = txtProdDate
        .Fields("dateCode") = txtDatecode
        .Fields("component") = cboComponent
        .Fields("nonconformance") = cboDiscrepancy
        .Fields("foundDuring") = cboFoundAt
        .Fields("responsibility") = cboRespCode
        .Fields("comments") = txtDescription
        .Fields("rootCause") = txtRootCause
        .Fields("lastEditDate") = Now()
        .Update
    End With

    MsgBox ("Information Updated")

End If

End Sub
</code>```

答:
Sorry i caught it. Problem was I was basically redefining the recordset each time the subroutine was called. I changed the second block to the following:</p>

```<code>ElseIf txtMode.Value = "EDIT" Then
    'do editing stuff
    Set rs = db.OpenRecordset("SELECT * FROM record_holdData WHERE ID=" & txtID)
    With rs
        .Edit
        .Fields("PO_no") = txtPONum
        .Fields("prodSupervisor") = cboProdSup
        .Fields("qaSupervisor") = cboQASup
        .Fields("labTech") = cboLabTech
        .Fields("flavor") = cboFlavor
        .Fields("lineNumber") = cboLineNumber
        .Fields("container") = cboContainer
        .Fields("package") = cboPackage
        .Fields("holdQty") = txtQty
        .Fields("productionDate") = txtProdDate
        .Fields("dateCode") = txtDatecode
        .Fields("component") = cboComponent
        .Fields("nonconformance") = cboDiscrepancy
        .Fields("foundDuring") = cboFoundAt
        .Fields("responsibility") = cboRespCode
        .Fields("comments") = txtDescription
        .Fields("rootCause") = txtRootCause
        .Fields("lastEditDate") = Now()
        .Update
    End With
</code>```

Title: dao recordset updating the wrong record

Body:
I'm trying to have a form usable for both creating a new record or updating another. Currently it is doing it through the value of a textbox (new or edit). The structure works fine, but for some reason, when it is performing the edit function, it is saving changes to the wrong record. For instance, if I am editing record 1027, when i submit it, it'll update record 1073. Its consistent, it'll always update the same, wrong record. Edit 1000, it'll update 1073; if i update 1081, it'll update 1073, and so on. Is there a way to specify which record it should be editing? yes, the record number is the primary key/id. Heres the code:

Private Sub btnSubmit_Click()

 Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim strTable As String
    Dim strField As String
    Dim ID As Long
    Dim newID As Long

    strTable = "record_holdData"
    Set db = CurrentDb
    Set rs = db.OpenRecordset(strTable)

'button has 2 modes
If txtMode.Value = "NEW" Then

    With rs
        .AddNew
        .Fields("PO_no") = txtPONum
        .Fields("prodSupervisor") = cboProdSup
        .Fields("qaSupervisor") = cboQASup
        .Fields("labTech") = cboLabTech
        .Fields("flavor") = cboFlavor
        .Fields("lineNumber") = cboLineNumber
        .Fields("container") = cboContainer
        .Fields("package") = cboPackage
        .Fields("holdQty") = txtQty
        .Fields("productionDate") = txtProdDate
        .Fields("dateCode") = txtDatecode
        .Fields("component") = cboComponent
        .Fields("nonconformance") = cboDiscrepancy
        .Fields("foundDuring") = cboFoundAt
        .Fields("responsibility") = cboRespCode
        .Fields("comments") = txtDescription
        .Fields("rootCause") = txtRootCause
        .Fields("holdStatus") = 1
        .Fields("dateOpened") = Now()
        .Update
        .Bookmark = .LastModified
        newID = !ID
    End With

        MsgBox ("Hold information saved!")
        btnPrintTag.Enabled = True
        DoCmd.OpenReport "Holdtag", acViewPreview, , "[ID] = " & newID
        DoCmd.Close

ElseIf txtMode.Value = "EDIT" Then
    'do editing stuff
    With rs
        .Edit
        .Fields("PO_no") = txtPONum
        .Fields("prodSupervisor") = cboProdSup
        .Fields("qaSupervisor") = cboQASup
        .Fields("labTech") = cboLabTech
        .Fields("flavor") = cboFlavor
        .Fields("lineNumber") = cboLineNumber
        .Fields("container") = cboContainer
        .Fields("package") = cboPackage
        .Fields("holdQty") = txtQty
        .Fields("productionDate") = txtProdDate
        .Fields("dateCode") = txtDatecode
        .Fields("component") = cboComponent
        .Fields("nonconformance") = cboDiscrepancy
        .Fields("foundDuring") = cboFoundAt
        .Fields("responsibility") = cboRespCode
        .Fields("comments") = txtDescription
        .Fields("rootCause") = txtRootCause
        .Fields("lastEditDate") = Now()
        .Update
    End With

    MsgBox ("Information Updated")

End If

End Sub

Body:
Sorry i caught it. Problem was I was basically redefining the recordset each time the subroutine was called. I changed the second block to the following:

ElseIf txtMode.Value = "EDIT" Then
    'do editing stuff
    Set rs = db.OpenRecordset("SELECT * FROM record_holdData WHERE ID=" & txtID)
    With rs
        .Edit
        .Fields("PO_no") = txtPONum
        .Fields("prodSupervisor") = cboProdSup
        .Fields("qaSupervisor") = cboQASup
        .Fields("labTech") = cboLabTech
        .Fields("flavor") = cboFlavor
        .Fields("lineNumber") = cboLineNumber
        .Fields("container") = cboContainer
        .Fields("package") = cboPackage
        .Fields("holdQty") = txtQty
        .Fields("productionDate") = txtProdDate
        .Fields("dateCode") = txtDatecode
        .Fields("component") = cboComponent
        .Fields("nonconformance") = cboDiscrepancy
        .Fields("foundDuring") = cboFoundAt
        .Fields("responsibility") = cboRespCode
        .Fields("comments") = txtDescription
        .Fields("rootCause") = txtRootCause
        .Fields("lastEditDate") = Now()
        .Update
    End With


问:
Import length-delimited file with PowerShell and export as csv file
I have a source file which is in .txt format. It looks like a semi-colon separated file:

```<code>100;200;ThisisastringcolumnA;4;
101;400;Thisisastringc;lumnA;5;
102;600;ThisisastringcolumnB;6;
104;600;Thisisa;;ringcolumnB;6;
</code>```

However, it is determined by length. So it is a length-delimited file.

Fist column for example is from first value to the third (100), then a semi-colon follows.
Second column starts at 5th position (including), until (including) 7th position. A string column can contain a semi-colon.

Now I want to import this length-delimited txt file with Powershell and export it as a csv file. This file should be really semi-colon separated. The result should look like

```<code>100;200;ThisisastringcolumnA;4;
101;400;"Thisisastringc;lumnA";5;
102;600;ThisisastringcolumnB;6;
104;600;"Thisisa;;ringcolumnB";6;
</code>```

But I have simply no idea how to do it? I googled it, but I did not find that much useful code examples for importing length-delimited txt files with PowerShell.

Unfortunately, I cannot use Python. I am not sure, if this task is generally possible using Powershell? Because when exporting, Powershell also needs to recognize that there are string values containing the separator, so it has to pay attention to the quoting: "Thisisa;;ringcolumnB". I think it would be also ok for me, if the whole column is quoted, so every entry in a string column gets quotes added.

答:
You can use regex to describe a string in which the 3rd "column" contains a ; and then inject the quotation marks with the -replace operator:

```<code>$lines = Get-Content path\to\file.txt

@($lines) -replace '(.{3});(.{3});(.{20}(?<=;.{0,19}));(.);', '$1;$2;"$3";$4;'
</code>```

The expression (.{20}(?<=;.{0,19})) is going to match the 20-char 3rd column value only if it contains at least one semi-colon - so lines with no semicolon in that column will be left alone:

```<code># let's try it out with your test data
$lines = @'
100;200;ThisisastringcolumnA;4;
101;400;Thisisastringc;lumnA;5;
102;600;ThisisastringcolumnB;6;
104;600;Thisisa;;ringcolumnB;6;
'@ -split '\r?\n'

@($lines) -replace '(.{3});(.{3});(.{20}(?<=;.{0,19}));(.);', '$1;$2;"$3";$4;'
</code>```

Which yields the following four strings:

```<code>100;200;ThisisastringcolumnA;4;
101;400;"Thisisastringc;lumnA";5;
102;600;ThisisastringcolumnB;6;
104;600;"Thisisa;;ringcolumnB";6;
</code>```

To write the output back to file, use Set-Content:

```<code>@($lines) -replace '(.{3});(.{3});(.{20}(?<=;.{0,19}));(.);', '$1;$2;"$3";$4;' |Set-Content path\to\fixed_output.scsv
</code>```

Body:
I have a source file which is in .txt format. It looks like a semi-colon separated file:

100;200;ThisisastringcolumnA;4;
101;400;Thisisastringc;lumnA;5;
102;600;ThisisastringcolumnB;6;
104;600;Thisisa;;ringcolumnB;6;

However, it is determined by length. So it is a length-delimited file.

Fist column for example is from first value to the third (100), then a semi-colon follows.
Second column starts at 5th position (including), until (including) 7th position. A string column can contain a semi-colon.

Now I want to import this length-delimited txt file with Powershell and export it as a csv file. This file should be really semi-colon separated. The result should look like

100;200;ThisisastringcolumnA;4;
101;400;"Thisisastringc;lumnA";5;
102;600;ThisisastringcolumnB;6;
104;600;"Thisisa;;ringcolumnB";6;

But I have simply no idea how to do it? I googled it, but I did not find that much useful code examples for importing length-delimited txt files with PowerShell.

Unfortunately, I cannot use Python. I am not sure, if this task is generally possible using Powershell? Because when exporting, Powershell also needs to recognize that there are string values containing the separator, so it has to pay attention to the quoting: "Thisisa;;ringcolumnB". I think it would be also ok for me, if the whole column is quoted, so every entry in a string column gets quotes added.

Body:
You can use regex to describe a string in which the 3rd "column" contains a ; and then inject the quotation marks with the -replace operator:

$lines = Get-Content path\to\file.txt

@($lines) -replace '(.{3});(.{3});(.{20}(?<=;.{0,19}));(.);', '$1;$2;"$3";$4;'

The expression (.{20}(?<=;.{0,19})) is going to match the 20-char 3rd column value only if it contains at least one semi-colon - so lines with no semicolon in that column will be left alone:

# let's try it out with your test data
$lines = @'
100;200;ThisisastringcolumnA;4;
101;400;Thisisastringc;lumnA;5;
102;600;ThisisastringcolumnB;6;
104;600;Thisisa;;ringcolumnB;6;
'@ -split '\r?\n'

@($lines) -replace '(.{3});(.{3});(.{20}(?<=;.{0,19}));(.);', '$1;$2;"$3";$4;'

Which yields the following four strings:

100;200;ThisisastringcolumnA;4;
101;400;"Thisisastringc;lumnA";5;
102;600;ThisisastringcolumnB;6;
104;600;"Thisisa;;ringcolumnB";6;

To write the output back to file, use Set-Content:

@($lines) -replace '(.{3});(.{3});(.{20}(?<=;.{0,19}));(.);', '$1;$2;"$3";$4;' |Set-Content path\to\fixed_output.scsv


问:
Pull Request not linked to Jira Issue automatically
I would like to include link my pull requests to Jira ticket automatically like this:

I have already prepend JIRA-Id in my pull request title, same goes for the source branch name. However, it did not link. I read from some article that I may need to include JIRA-Id in my commit messages as well. But one of my previous Jira ticket, I did not do so but it managed to link. Why is that so?

答:
Suggestion to have your your branch and commit message include the JIRA-ID.

E.g.

Branch: bugs/JIRA-001

Commit message: "JIRA-001: Fix something in my project"

Check if your Bitbucket already linked to your Jira:

https://support.atlassian.com/bitbucket-cloud/docs/connect-bitbucket-cloud-to-jira-software-cloud/

Click your profile avatar > select a workspace from the Recent workspaces list or select All workspaces to display an entire list from which you can select.

Once you’re in your workspace, click Settings on the left sidebar menu.

Click Jira under Atlassian Integrations.

Choose the Jira Cloud instance you want to integrate with your Bitbucket Cloud workspace and click Connect.

Click Grant access to grant Jira Software access to your Bitbucket Cloud workspace.

Click Grant access to grant Bitbucket access to Jira.

Choose whether or not you would like to automatically sync and enable Smart Commits for all your repositories. Note: These options are selected by default. See Processing Jira issues with Smart Commits for more information. You can manage these settings later from the 'DVCS accounts' page in Jira Software.

Click OK.

And this is how to integrate with GitHub

https://support.atlassian.com/jira-cloud-administration/docs/integrate-with-github/

Install the (free) GitHub for Jira app from the Atlassian Marketplace and follow the instructions to complete the installation.

Select Get started to go to the GitHub configuration page (or go to Apps > Manage apps and select Configure integration in the GitHub menu).

Select Connect GitHub organization.

Find the GitHub organization you want to integrate with and select Connect, or select Install GitHub for Jira on a new organization to install the GitHub for Jira app on another GitHub organization.

Back on your GitHub configuration page, select Connect GitHub organization again and click Connect next to the organization you want to connect to your Jira site.


问:
validate special characters by negating unicode letters with regex pattern?
This regex: \p{L}+ matches these characters "ASKJKSDJKDSJÄÖÅüé" of the example string "ASKJKSDJK_-.;,DSJÄÖÅ!”#€%&/()=?`¨’<>üé" which is great but is the exact opposite of what I want. Which leads me to negating regexes.

Goal:

I want to match any and all characters that are not a letter nor a number in multiple languages.

Could a negative regex be a natural direction for this?

I should mention one intended use for the regex I'd like to find is to validate passwords for the rule:

that it needs to contain at least one special character, which I
define as not being a number nor a letter.

It would seem defining ranges of special characters should be avoided if possible, because why limit the possibilities? Thus my definition. I assume there could be some problems with such a wide definition, but it is a first step.

If you have some suggestions for a better solution I'm giving below or just have some thoughts on the subject, I'm sure I'm not the only one that would like to learn about it. Thanks.

Note I'm using double \\ in the Java code. Platform is Java 11.

答:
You can shove those \\p things in []. And thus, use the fact that you can negate chargroups. This is all you need:

Pattern p = Pattern.compile("[^\\p{L}]");
Matcher m = p.matcher("ASKJKSDJK_-.;,DSJÄÖÅ!”#€%&/()=?`¨’<>üé");
while (m.find()) System.out.print(m.group(0));
```
<p>That prints:</p>
```_-.;,!”#€%&/()=?`¨’<>
```

Which is exactly what you're looking for, no?

No need to mess with lookaheads here.

Body:
You can shove those \\p things in []. And thus, use the fact that you can negate chargroups. This is all you need:

Pattern p = Pattern.compile("[^\\p{L}]");
Matcher m = p.matcher("ASKJKSDJK_-.;,DSJÄÖÅ!”#€%&/()=?`¨’<>üé");
while (m.find()) System.out.print(m.group(0));

That prints:

_-.;,!”#€%&/()=?`¨’<>

Which is exactly what you're looking for, no?

No need to mess with lookaheads here.


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
You are the ones who know and understand the product, so don't assume that just because someone else has 'usability expert' in their title that hiring them will somehow make your product usable.

Also, don't undercut your own instincts for usability. As a programmer, you use software all the time, what products do find the most usable?  Think about what you like about them and compare them to your product.

Think about what your product does, and imagine that you are the person having to use the product and imagine how you would want it to work.  Think of what a user wants to accomplish using your product, and imagine the steps they would have to go through to do it.  Does it seem easy to understand what to do?  Can it be done in fewer steps?

Most importantly, talk to your customers.  Find out what they found confusing or difficult to accomplish.  See if they have come up with their own workarounds for using your product in ways you didn't initially picture.

If you put as much thought, planning and effort into usability as you did into improving the reliability and deployment, you will end up with a much better product.

OwnerDisplayName: Fedyashev Nikita

LastEditorDisplayName: Gortok

OwnerDisplayName: Lorin


问:
Unable to open project in VisualStudio 2010
I created a SilverLight solution in Visual Web Developer Express 2010.  Now, my system got installed with Visual Studio 2010 Professional.  On opening the existing express solution, I got the below error:

Unable to open project. An update to Microsoft Visual Studio is required to support the targeted version of SilverLight.  Download the update at http://go.microsoft.com/fwlink?LinkId=168436

It takes to install the add-on Microsoft Silverlight 4 Tools for Visual Studio 2010.  My question is 'Why itz not part and parcel of professional edition?'

答: If I recall correctly, the silverlight tools for VS2010 were released very shortly after VS2010 went RTM.  Silverlight is a separate technology that isn't dependent on Visual Studio.  It's developed by a different group and they have separate release schedules.</p>


问:
How to subscribe to input for it to save changes into an object?
I have an input in a form of HTML like this:

```<code> <mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input id = "flowRate" type="number" matInput>
  </mat-form-field>
</code>```

To which I subscribe later in my .ts file like this:

```<code>private flowRateInput: any = document.getElementById('flowRate') as HTMLInputElement

 if (flowRateInput: any) {
  let flowObs = fromEvent(this.flowRateInput, 'input').pipe(
      debounceTime(500)
    ).subscribe(res => {
      this.calcData.flowRate = +this.flowRateInput.value;
      console.log(this.flowRateInput.value)
      console.log(this.calcData)
    })
  }
</code>```

However it seems to do nothing when I open the page and change the input. I have a guess that I did something wrong in subscribe part of the code.

答:
Try something like this, using FormControl :

.html file:

```<code><mat-form-field appearance="fill">
  <mat-label>Flowrate: </mat-label>
  <input id="flowRate" type="number" [formControl]="fcFlowRate" matInput>
</mat-form-field>
</code>```

.ts file :

```<code>// Before constructor
fcFlowRate = new FormControl();

// In NgOnInit
this.fcFlowRate.valueChanges.pipe(debounceTime(500)).subscribe( value => {
  this.calcData.flowRate = +value;
  console.log(value)
  console.log(this.calcData)
})
</code>```

Body:
I have an input in a form of HTML like this:

 <mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input id = "flowRate" type="number" matInput>
  </mat-form-field>

To which I subscribe later in my .ts file like this:

private flowRateInput: any = document.getElementById('flowRate') as HTMLInputElement

 if (flowRateInput: any) {
  let flowObs = fromEvent(this.flowRateInput, 'input').pipe(
      debounceTime(500)
    ).subscribe(res => {
      this.calcData.flowRate = +this.flowRateInput.value;
      console.log(this.flowRateInput.value)
      console.log(this.calcData)
    })
  }

However it seems to do nothing when I open the page and change the input. I have a guess that I did something wrong in subscribe part of the code.

Body:
Try something like this, using FormControl :

.html file:

<mat-form-field appearance="fill">
  <mat-label>Flowrate: </mat-label>
  <input id="flowRate" type="number" [formControl]="fcFlowRate" matInput>
</mat-form-field>

.ts file :

// Before constructor
fcFlowRate = new FormControl();

// In NgOnInit
this.fcFlowRate.valueChanges.pipe(debounceTime(500)).subscribe( value => {
  this.calcData.flowRate = +value;
  console.log(value)
  console.log(this.calcData)
})


问:
Voluptuous : give error line in yaml file
I am using voluptuous a lot to validate yaml description files. Often the errors are cumbersome to decipher, especially for regular users.

I am looking for a way to make the error a bit more readable. One way is to identify which line in the YAML file is incrimined.

```<code>from voluptuous import Schema
import yaml
from io import StringIO

Validate = Schema({
    'name': str,
    'age': int,
})

data = """
name: John
age: oops
"""

data = Validate(yaml.load(StringIO(data)))
</code>```

In the above example, I get this error:

```<code>MultipleInvalid: expected int for dictionary value @ data['age']
</code>```

I would rather prefer an error like:

```<code>Error: validation failed on line 2, data.age should be an integer.
</code>```

Is there an elegant way to achieve this?

答:
The problem is that on the API boundary of yaml.load, all representational information of the source has been lost. Validate gets a Python dict and does not know where it originated from, and moreover the dict does not contain this information.

You can, however, implement this yourself. voluptuous' Invalid error carries a path which is a list of keys to follow. Having this path, you can parse the YAML again into nodes (which carry representation information) and discover the position of the item:

import yaml

def line_from(path, yaml_input):
  node = yaml.compose(yaml_input)
  for item in path:
    for entry in node.value:
      if entry[0].value == item:
        node = entry[1]
        break
    else: raise ValueError("unknown path element: " + item)
  return node.start_mark.line

# demostrating this on more complex input than yours

data = """
spam:
  egg:
    sausage:
      spam
"""

print(line_from(["spam", "egg", "sausage"], data))
# gives 4
```
<p>Having this, you can then do</p>
<pre class="lang-py prettyprint-override"><code>try:
  data = Validate(yaml.load(StringIO(data)))
except Invalid as e:
  line = line_from(e.path, data)
  path = "data." + ".".join(e.path)
  print(f"Error: validation failed on line {line} ({path}): {e.error_message}")
</code>```

I'll go this far for this answer as it shows you how to discover the origin line of an error. You will probably need to extend this to:

handle YAML sequences (my code assumes that every intermediate node is a MappingNode, a SequenceNode will have single nodes in its value list instead of a key-value tuple)

handle MultipleInvalid to issue a message for each inner error

rewrite expected int to should be an integer if you really want to (no idea how you'd do that)

abort after printing the error

Body:
I am using voluptuous a lot to validate yaml description files. Often the errors are cumbersome to decipher, especially for regular users.

I am looking for a way to make the error a bit more readable. One way is to identify which line in the YAML file is incrimined.

from voluptuous import Schema
import yaml
from io import StringIO

Validate = Schema({
    'name': str,
    'age': int,
})

data = """
name: John
age: oops
"""

data = Validate(yaml.load(StringIO(data)))

In the above example, I get this error:

MultipleInvalid: expected int for dictionary value @ data['age']

I would rather prefer an error like:

Error: validation failed on line 2, data.age should be an integer.

Is there an elegant way to achieve this?

Body:
The problem is that on the API boundary of yaml.load, all representational information of the source has been lost. Validate gets a Python dict and does not know where it originated from, and moreover the dict does not contain this information.

You can, however, implement this yourself. voluptuous' Invalid error carries a path which is a list of keys to follow. Having this path, you can parse the YAML again into nodes (which carry representation information) and discover the position of the item:

import yaml

def line_from(path, yaml_input):
  node = yaml.compose(yaml_input)
  for item in path:
    for entry in node.value:
      if entry[0].value == item:
        node = entry[1]
        break
    else: raise ValueError("unknown path element: " + item)
  return node.start_mark.line

# demostrating this on more complex input than yours

data = """
spam:
  egg:
    sausage:
      spam
"""

print(line_from(["spam", "egg", "sausage"], data))
# gives 4

Having this, you can then do

try:
  data = Validate(yaml.load(StringIO(data)))
except Invalid as e:
  line = line_from(e.path, data)
  path = "data." + ".".join(e.path)
  print(f"Error: validation failed on line {line} ({path}): {e.error_message}")

I'll go this far for this answer as it shows you how to discover the origin line of an error. You will probably need to extend this to:

handle YAML sequences (my code assumes that every intermediate node is a MappingNode, a SequenceNode will have single nodes in its value list instead of a key-value tuple)

handle MultipleInvalid to issue a message for each inner error

rewrite expected int to should be an integer if you really want to (no idea how you'd do that)

abort after printing the error


问:
File's style corrupts while converting from xls to xlsx
I have .xls excel file. I'm converting it to xlsx by;

```<code>df = panda.read_excel(currentPath)
df.to_excel(currentPath+ 'x')
</code>```

But this messes with the file, columns and rows are changing place, is there a way to convert xls to xlsx without changing anything?

答:
Pandas isn't primarily intended for manipulating Excel files, and XLS and XLSX are separate formats, not just differences in naming convention. Because DataFrames aren't intended to represent either XLS or XLSX format, you're juggling three different formats, and the format change might be in either XLS -> DF or DF -> XLSX. That suggests that you probably should not use Pandas DataFrames for this task. If you need to do other manipulations with Pandas DF, then you can look into reordering DF columns.

Assuming you're really trying to reformat the files and do Excel-style manipulations, I recommend openpyxl, although there are a few competing libraries you might also find useful.  (Also, as @lei-yang notes below, openpyxl may not be able to read XLS files - although other packages listed there should be able to do so.)

If you're not doing any manipulations of the file itself, and don't care about having the file names match the internal formats, the Python os and shutil libraries can cover that.

Body:
I have .xls excel file. I'm converting it to xlsx by;

df = panda.read_excel(currentPath)
df.to_excel(currentPath+ 'x')

But this messes with the file, columns and rows are changing place, is there a way to convert xls to xlsx without changing anything?


问:
How to create LazyList Scala using LazyList.iterate?
My task:

Implement a function to calculate the Look-and-say sequence.

This is done and the tests pass successfully:

```<code>import scala.collection.immutable.LazyList
import scala.language.implicitConversions
import scala.collection.mutable.ListBuffer

object CountAndSay extends App {
  def nextLine(currentLine: List[BigInt]): List[BigInt] = {
    ...

  println(nextLine(List(1, 2, 1, 1)) == List(1, 1, 1, 2, 2, 1))
  println(nextLine(List(1, 1, 1, 2, 2, 1)) == List(3, 1, 2, 2, 1, 1))
  println(nextLine(List(3, 1, 2, 2, 1, 1)) == List(1, 3, 1, 1, 2, 2, 2, 1))
}
</code>```

Implement a lazy list that generates the given sequence.

```<code>val funSeq: LazyList[List[Int]] = ...
println(funSeq(5) === List(3, 1, 2, 2, 1, 1))
</code>```

To create a LazyList with nested lists, I want to use LazyList.iterate.
LazyList.iterate description
But I get a Cannot resolve overloaded method 'iterate' error:

```<code>val funSeq: LazyList[List[BigInt]] = LazyList.iterate(List(1), nextLine(List(1)))
</code>```

I would appreciate any help.

答:
It looks like you do not use LazyList syntax correctly. You need to use it as follow:

```<code>LazyList.iterate(List(BigInt(1)))(nextLine).take(4).force
</code>```

First parameter of iterate is start element that will passed in the function - second parameter of iterate. The take need to do several iterations and force need to evaluate result.

Body:
My task:

Implement a function to calculate the Look-and-say sequence.

This is done and the tests pass successfully:

import scala.collection.immutable.LazyList
import scala.language.implicitConversions
import scala.collection.mutable.ListBuffer

object CountAndSay extends App {
  def nextLine(currentLine: List[BigInt]): List[BigInt] = {
    ...

  println(nextLine(List(1, 2, 1, 1)) == List(1, 1, 1, 2, 2, 1))
  println(nextLine(List(1, 1, 1, 2, 2, 1)) == List(3, 1, 2, 2, 1, 1))
  println(nextLine(List(3, 1, 2, 2, 1, 1)) == List(1, 3, 1, 1, 2, 2, 2, 1))
}

Implement a lazy list that generates the given sequence.

val funSeq: LazyList[List[Int]] = ...
println(funSeq(5) === List(3, 1, 2, 2, 1, 1))

To create a LazyList with nested lists, I want to use LazyList.iterate.
LazyList.iterate description
But I get a Cannot resolve overloaded method 'iterate' error:

val funSeq: LazyList[List[BigInt]] = LazyList.iterate(List(1), nextLine(List(1)))

I would appreciate any help.

Body:
It looks like you do not use LazyList syntax correctly. You need to use it as follow:

LazyList.iterate(List(BigInt(1)))(nextLine).take(4).force

First parameter of iterate is start element that will passed in the function - second parameter of iterate. The take need to do several iterations and force need to evaluate result.