问:
RxJs: concat two observables as options for material select
I am having problems trying to concat two different observables and show the results into a Material Select component.

On this example (built using the tool from Material docs) there is a simple example simulating what I want to do. Options are not being shown.

In my current code (on my machine), the problem I see is: the first Observable that is passed to the concat operator is subscribed and all items are shown in the Select. But I belive that the first Observable never completes. It looks like material-select is not "completing" the first Observable and, because of that, concat won't subscribe to the next Observable while the first one never completes, as it says in its docs:

Note that if some input Observable never completes, concat will also never complete and Observables following the one that did not complete will never be subscribed.

What I need is this: taking two different Observables (with different data in each one), concat them (or any other operation), and, in the end, show all their data combined as options of a single select component.

Just as a reference, I'll copy the code here also, so it won't be lost in the future:

// Component:
import { Component, Input } from '@angular/core';
import { from } from 'rxjs';
import { concatWith } from 'rxjs/operators';

interface Option {
  value: number;
  label: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
})
export class SelectOverviewExample {
  @Input()
  options$: any;

  constructor() {}
  ngOnInit() {
    // Let's pretend this data comes from API 1
    const sourceA$ = from([
      { value: 1, label: 'Value 1' },
      { value: 2, label: 'Value 2' },
      { value: 3, label: 'Value 3' },
    ]);

    // And these ones comes from API 2
    const sourceB$ = from([
      { value: 4, label: 'Value 4' },
      { value: 5, label: 'Value 5' },
      { value: 6, label: 'Value 6' },
    ]);

    // Now, concat the data from both observables and display all of them as options in a Select component:
    this.options$ = concatWith(sourceA$, sourceB$);
  }
}
```
<p>And the template:</p>
<pre class="lang-html prettyprint-override"><code><h4>Basic mat-select</h4>
<mat-form-field appearance="fill">
  <mat-label>Select some value:</mat-label>
  <mat-select>
    <mat-option
      *ngFor="let option of (options$ | async)"
      [value]="option.value"
    >
      {{option.label}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

答:
You can collect the values from multiple observables using the merge function and the scan operator as follows:

```<code>import { from, merge } from 'rxjs';
import { scan } from 'rxjs/operators';

const sourceA$ = from(/* ... */);
const sourceB$ = from(/* ... */);

merge(sourceA$, sourceB$)
  .pipe(
    scan((acc, value) => {
      acc.push(value);
      return acc;
    }, [])
  )
  .subscribe((value) => console.log(value));
</code>```

StackBlitz Example

In this example, you can replace merge with concat and it still works. If the order matters and you want to get all values from sourceA$ before subscribing to sourceB$, then you are correct that concat should be used instead of merge.

Regarding your comment...

It looks like material-select is not "completing" the first Observable

It is not the responsibility of material-select to complete the source Observable. It's the responsibility of the source Observable to complete. material-select has no way of knowing when the source Observable is done emitting values without the source Observable completing itself.

Body:
I am having problems trying to concat two different observables and show the results into a Material Select component.

On this example (built using the tool from Material docs) there is a simple example simulating what I want to do. Options are not being shown.

In my current code (on my machine), the problem I see is: the first Observable that is passed to the concat operator is subscribed and all items are shown in the Select. But I belive that the first Observable never completes. It looks like material-select is not "completing" the first Observable and, because of that, concat won't subscribe to the next Observable while the first one never completes, as it says in its docs:

Note that if some input Observable never completes, concat will also never complete and Observables following the one that did not complete will never be subscribed.

What I need is this: taking two different Observables (with different data in each one), concat them (or any other operation), and, in the end, show all their data combined as options of a single select component.

Just as a reference, I'll copy the code here also, so it won't be lost in the future:

// Component:
import { Component, Input } from '@angular/core';
import { from } from 'rxjs';
import { concatWith } from 'rxjs/operators';

interface Option {
  value: number;
  label: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
})
export class SelectOverviewExample {
  @Input()
  options$: any;

  constructor() {}
  ngOnInit() {
    // Let's pretend this data comes from API 1
    const sourceA$ = from([
      { value: 1, label: 'Value 1' },
      { value: 2, label: 'Value 2' },
      { value: 3, label: 'Value 3' },
    ]);

    // And these ones comes from API 2
    const sourceB$ = from([
      { value: 4, label: 'Value 4' },
      { value: 5, label: 'Value 5' },
      { value: 6, label: 'Value 6' },
    ]);

    // Now, concat the data from both observables and display all of them as options in a Select component:
    this.options$ = concatWith(sourceA$, sourceB$);
  }
}

And the template:

Basic mat-select

<mat-form-field appearance="fill">
  <mat-label>Select some value:</mat-label>
  <mat-select>
    <mat-option
      *ngFor="let option of (options$ | async)"
      [value]="option.value"
    >
      {{option.label}}
    </mat-option>
  </mat-select>
</mat-form-field>

Body:
You can collect the values from multiple observables using the merge function and the scan operator as follows:

import { from, merge } from 'rxjs';
import { scan } from 'rxjs/operators';

const sourceA$ = from(/* ... */);
const sourceB$ = from(/* ... */);

merge(sourceA$, sourceB$)
  .pipe(
    scan((acc, value) => {
      acc.push(value);
      return acc;
    }, [])
  )
  .subscribe((value) => console.log(value));

StackBlitz Example

In this example, you can replace merge with concat and it still works. If the order matters and you want to get all values from sourceA$ before subscribing to sourceB$, then you are correct that concat should be used instead of merge.

Regarding your comment...

It looks like material-select is not "completing" the first Observable

It is not the responsibility of material-select to complete the source Observable. It's the responsibility of the source Observable to complete. material-select has no way of knowing when the source Observable is done emitting values without the source Observable completing itself.


来源: stackexchange

问:
Cannot instantiate qemu-kvm VM inside WSL2 (Windows Subsystem for Linux 2) on Windows 10
I am currently trying out the Windows Subsystem for Linux v2, on a Windows 10 Fast Ring build (Build 20161). More specifically, I am trying to run a qemu-kvm virtual machine using nested virtualization, but each attempt at creating a new VM using virt-manager ends up in failure.

I use Ubuntu 18.04 in my WSL2 instance, with a custom built kernel (that includes everything related to virtualization - please see this guide: https://boxofcables.dev/accelerated-kvm-guests-on-wsl-2/) and "nestedVirtualization" is set to "true" in my WSL config file. Even more so, "sudo kvm-ok" returns positive results when ran inside the Ubuntu instance.

I do have DBUS installed in Ubuntu WSL, and the service is running, so I believe this is not the source of the problem. I'm using VcXsrv for displaying X11 windows.

Here are the errors I get with each attempt:

Libvirtd.log

```<code>2020-07-07 03:33:24.507+0000: 1273: info : libvirt version: 4.0.0, package: 1ubuntu8.17 (Marc Deslauriers <marc.deslauriers@ubuntu.com> Wed, 06 May 2020 14:18:23 -0400)
2020-07-07 03:33:24.507+0000: 1273: info : hostname: LAPTOP-DRAGOS
2020-07-07 03:33:24.507+0000: 1273: error : udevGetDMIData:1818 : internal error: Failed to get udev device for syspath '/sys/devices/virtual/dmi/id' or '/sys/class/dmi/id'
2020-07-07 03:39:16.636+0000: 1261: error : virNetSocketNewConnectUNIX:715 : Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
2020-07-07 03:39:29.617+0000: 1258: error : virNetSocketNewConnectUNIX:715 : Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
2020-07-07 03:39:29.617+0000: 1258: error : virNetSocketNewConnectUNIX:715 : Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
2020-07-07 04:01:14.141+0000: 1257: error : virKeepAliveTimerInternal:143 : internal error: connection closed due to keepalive timeout
</code>```

Virt-manager GUI (when I click "Begin Installation" once all options have been set):

```<code>Unable to complete install: 'Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory'

Traceback (most recent call last):
  File "/usr/share/virt-manager/virtManager/asyncjob.py", line 89, in cb_wrapper
    callback(asyncjob, *args, **kwargs)
  File "/usr/share/virt-manager/virtManager/create.py", line 2553, in _do_async_install
    guest.start_install(meter=meter)
  File "/usr/share/virt-manager/virtinst/guest.py", line 498, in start_install
    doboot, transient)
  File "/usr/share/virt-manager/virtinst/guest.py", line 434, in _create_guest
    domain = self.conn.createXML(install_xml or final_xml, 0)
  File "/usr/lib/python2.7/dist-packages/libvirt.py", line 3603, in createXML
    if ret is None:raise libvirtError('virDomainCreateXML() failed', conn=self)
libvirtError: Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
</code>```

What am I doing wrong?
Any input is highly appreciated! Thanks in advance!

UPDATE: As @FreeSoftwareServers suggested, I tried starting the virtlogd service. Since Ubuntu 18.04 does not use initd, I went for sudo service virtlogd start. And that got me over the initial error, but now I seem to encounter some permission issues, because I get the following:

```<code>Unable to complete install: 'internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied
2020-07-08T03:32:26.585442Z qemu-system-x86_64: failed to initialize KVM: Permission denied'

Traceback (most recent call last):
  File "/usr/share/virt-manager/virtManager/asyncjob.py", line 89, in cb_wrapper
    callback(asyncjob, *args, **kwargs)
  File "/usr/share/virt-manager/virtManager/create.py", line 2553, in _do_async_install
    guest.start_install(meter=meter)
  File "/usr/share/virt-manager/virtinst/guest.py", line 498, in start_install
    doboot, transient)
  File "/usr/share/virt-manager/virtinst/guest.py", line 434, in _create_guest
    domain = self.conn.createXML(install_xml or final_xml, 0)
  File "/usr/lib/python2.7/dist-packages/libvirt.py", line 3603, in createXML
    if ret is None:raise libvirtError('virDomainCreateXML() failed', conn=self)
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied
2020-07-08T03:32:26.585442Z qemu-system-x86_64: failed to initialize KVM: Permission denied
</code>```

virt-manager GUI is run with sudo, so this permission denial message seems a bit puzzling.

Best regards,
Dragoș

答:
On Windows 11, I got this working by fixing up /dev/kvm:

```<code>sudo chown root:kvm /dev/kvm
sudo chmod 660 /dev/kvm
</code>```

Full setup:

```<code># Install virt-manager
sudo apt install -y virt-manager

# Add youself to kvm and libvirt group
sudo usermod --append --groups kvm,libvirt "${USER}"

# Fix-up permission to avoid "Could not access KVM kernel module: Permission denied" error
sudo chown root:kvm /dev/kvm
sudo chmod 660 /dev/kvm

# Stat required services
sudo libvirtd &
sudo virtlogd &

# Launch virt-manager
virt-manager &
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying out the Windows Subsystem for Linux v2, on a Windows 10 Fast Ring build (Build 20161). More specifically, I am trying to run a qemu-kvm virtual machine using nested virtualization, but each attempt at creating a new VM using virt-manager ends up in failure.

I use Ubuntu 18.04 in my WSL2 instance, with a custom built kernel (that includes everything related to virtualization - please see this guide: https://boxofcables.dev/accelerated-kvm-guests-on-wsl-2/) and "nestedVirtualization" is set to "true" in my WSL config file. Even more so, "sudo kvm-ok" returns positive results when ran inside the Ubuntu instance.

I do have DBUS installed in Ubuntu WSL, and the service is running, so I believe this is not the source of the problem. I'm using VcXsrv for displaying X11 windows.

Here are the errors I get with each attempt:

Libvirtd.log

2020-07-07 03:33:24.507+0000: 1273: info : libvirt version: 4.0.0, package: 1ubuntu8.17 (Marc Deslauriers <marc.deslauriers@ubuntu.com> Wed, 06 May 2020 14:18:23 -0400)
2020-07-07 03:33:24.507+0000: 1273: info : hostname: LAPTOP-DRAGOS
2020-07-07 03:33:24.507+0000: 1273: error : udevGetDMIData:1818 : internal error: Failed to get udev device for syspath '/sys/devices/virtual/dmi/id' or '/sys/class/dmi/id'
2020-07-07 03:39:16.636+0000: 1261: error : virNetSocketNewConnectUNIX:715 : Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
2020-07-07 03:39:29.617+0000: 1258: error : virNetSocketNewConnectUNIX:715 : Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
2020-07-07 03:39:29.617+0000: 1258: error : virNetSocketNewConnectUNIX:715 : Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory
2020-07-07 04:01:14.141+0000: 1257: error : virKeepAliveTimerInternal:143 : internal error: connection closed due to keepalive timeout

Virt-manager GUI (when I click "Begin Installation" once all options have been set):

Unable to complete install: 'Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory'

Traceback (most recent call last):
  File "/usr/share/virt-manager/virtManager/asyncjob.py", line 89, in cb_wrapper
    callback(asyncjob, *args, **kwargs)
  File "/usr/share/virt-manager/virtManager/create.py", line 2553, in _do_async_install
    guest.start_install(meter=meter)
  File "/usr/share/virt-manager/virtinst/guest.py", line 498, in start_install
    doboot, transient)
  File "/usr/share/virt-manager/virtinst/guest.py", line 434, in _create_guest
    domain = self.conn.createXML(install_xml or final_xml, 0)
  File "/usr/lib/python2.7/dist-packages/libvirt.py", line 3603, in createXML
    if ret is None:raise libvirtError('virDomainCreateXML() failed', conn=self)
libvirtError: Failed to connect socket to '/var/run/libvirt/virtlogd-sock': No such file or directory

What am I doing wrong?
Any input is highly appreciated! Thanks in advance!

UPDATE: As @FreeSoftwareServers suggested, I tried starting the virtlogd service. Since Ubuntu 18.04 does not use initd, I went for sudo service virtlogd start. And that got me over the initial error, but now I seem to encounter some permission issues, because I get the following:

Unable to complete install: 'internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied
2020-07-08T03:32:26.585442Z qemu-system-x86_64: failed to initialize KVM: Permission denied'

Traceback (most recent call last):
  File "/usr/share/virt-manager/virtManager/asyncjob.py", line 89, in cb_wrapper
    callback(asyncjob, *args, **kwargs)
  File "/usr/share/virt-manager/virtManager/create.py", line 2553, in _do_async_install
    guest.start_install(meter=meter)
  File "/usr/share/virt-manager/virtinst/guest.py", line 498, in start_install
    doboot, transient)
  File "/usr/share/virt-manager/virtinst/guest.py", line 434, in _create_guest
    domain = self.conn.createXML(install_xml or final_xml, 0)
  File "/usr/lib/python2.7/dist-packages/libvirt.py", line 3603, in createXML
    if ret is None:raise libvirtError('virDomainCreateXML() failed', conn=self)
libvirtError: internal error: process exited while connecting to monitor: Could not access KVM kernel module: Permission denied
2020-07-08T03:32:26.585442Z qemu-system-x86_64: failed to initialize KVM: Permission denied

virt-manager GUI is run with sudo, so this permission denial message seems a bit puzzling.

Best regards,
Dragoș

Body:
On Windows 11, I got this working by fixing up /dev/kvm:

sudo chown root:kvm /dev/kvm
sudo chmod 660 /dev/kvm

Full setup:

# Install virt-manager
sudo apt install -y virt-manager

# Add youself to kvm and libvirt group
sudo usermod --append --groups kvm,libvirt "${USER}"

# Fix-up permission to avoid "Could not access KVM kernel module: Permission denied" error
sudo chown root:kvm /dev/kvm
sudo chmod 660 /dev/kvm

# Stat required services
sudo libvirtd &
sudo virtlogd &

# Launch virt-manager
virt-manager &


问:
Simple weather app breaking at weather.main.temp variable
I'm building a really basic weather app with React hooks, codesandbox.io and OpenWeatherAPI.
It's breaking at const temp = forecast.main.temp; and returning "TypeError: Cannot read properties of undefined (reading 'temp')" It actually does run when I initially write it but breaks if I add another variable or have to edit the temp variable in any way.

```<code>import React, { useState } from "react";
import "../styles.css";
import CityCard from "./cityCard";

export default function GetWeather() {

  const [city, setCity] = useState('');
  const [forecast, setForecast] = useState([]);

  const getCity = async (e) => {
    e.preventDefault();

  //API variables
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${APIkey}`;

  //fetch response
  try {
  const res = await fetch(url);
  const data = await res.json();
  setForecast(data);
  } catch (err) {
    console.error(err);
  }

};

  return (
    //basic input form to search by city
    <div>
      <h1 className="title">Weather App</h1>
      <CityCard forecast={forecast} />
      <form className="form" onSubmit={getCity}>
      <label className="label" htmlFor="city">
      <p>Search by City</p>
      </label>
      <input
        className="input"
        type="text"
        name="query place"
        placeholder="i.e. Seattle"
        value={city} onChange={(e) => setCity(e.target.value)}
        >
      </input>
      <button
      className="button"
      type="submit"
      >Search</button>
      </form>
    </div>
  );
}
</code>```

CityCard

```<code>import React from "react";
import "../../src/styles.css";

export default function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast.name;
  const temp = forecast.main.temp;

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp} </p>
      </div>

  );
}
</code>```

答:
Issue

The initial forecast state is declared as an array:

```<code>const [forecast, setForecast] = useState([]);
</code>```

and passed to CityCard on forecast prop:

```<code><CityCard forecast={forecast} />
</code>```

then accessed as if it were an object:

```<code>function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast.name;  // OK, undefined
  const temp = forecast.main.temp; // Not OK, can't access temp of undefined

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp}</p>
      </div>

  );
}
</code>```

Solution

Use Optional Chaining operator to protect against null/undefined property accesses.

```<code>function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast?.name;
  const temp = forecast?.main?.temp;

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp}</p>
      </div>

  );
}
</code>```

Or wait to render CityCard when there's a valid forecast data to display.

```<code>const [forecast, setForecast] = useState();

...

{forecast?.name && forecast?.main?.temp && <CityCard forecast={forecast} />}
</code>```

OpenWeather JSON API response

Body:
I'm building a really basic weather app with React hooks, codesandbox.io and OpenWeatherAPI.
It's breaking at const temp = forecast.main.temp; and returning "TypeError: Cannot read properties of undefined (reading 'temp')" It actually does run when I initially write it but breaks if I add another variable or have to edit the temp variable in any way.

import React, { useState } from "react";
import "../styles.css";
import CityCard from "./cityCard";

export default function GetWeather() {

  const [city, setCity] = useState('');
  const [forecast, setForecast] = useState([]);

  const getCity = async (e) => {
    e.preventDefault();

  //API variables
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${APIkey}`;

  //fetch response
  try {
  const res = await fetch(url);
  const data = await res.json();
  setForecast(data);
  } catch (err) {
    console.error(err);
  }

};

  return (
    //basic input form to search by city

Weather App

      <CityCard forecast={forecast} />
      <form className="form" onSubmit={getCity}>

Search by City

      <input
        className="input"
        type="text"
        name="query place"
        placeholder="i.e. Seattle"
        value={city} onChange={(e) => setCity(e.target.value)}
        >
      </input>
      <button
      className="button"
      type="submit"
      >Search</button>
      </form>

  );
}

CityCard

import React from "react";
import "../../src/styles.css";

export default function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast.name;
  const temp = forecast.main.temp;

  return (

{cityName}

Temp: {temp}

  );
}

Body:
Issue

The initial forecast state is declared as an array:

const [forecast, setForecast] = useState([]);

and passed to CityCard on forecast prop:

<CityCard forecast={forecast} />

then accessed as if it were an object:

function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast.name;  // OK, undefined
  const temp = forecast.main.temp; // Not OK, can't access temp of undefined

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp}</p>
      </div>

  );
}

Solution

Use Optional Chaining operator to protect against null/undefined property accesses.

function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast?.name;
  const temp = forecast?.main?.temp;

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp}</p>
      </div>

  );
}

Or wait to render CityCard when there's a valid forecast data to display.

const [forecast, setForecast] = useState();

...

{forecast?.name && forecast?.main?.temp && <CityCard forecast={forecast} />}

OpenWeather JSON API response


问:
How Do I get Object URL for Amazon S3 object
I uploaded a file to my  Amazon S3 bucket and I would like to get a url using the aws-SDK not console for the object that I put in. The object has public read access
I have tried using

```<code>const url = s3Client.getSignedUrl('getObject', {
        Bucket: srcBucket,
        Key: key,
    });
</code>```

but that generates a signed url that expires. I can't seem to find any other method to fetch just the url. Any help is much appreciated.

答:
You can get the URL of an Amazon S3 object using the AWS SDK for Java V2. Here is the code:</p>
```<code>// snippet-start:[s3.java2.getobjecturl.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetUrlRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.net.URL;
// snippet-end:[s3.java2.getobjecturl.import]

public class GetObjectUrl {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    <bucketName> <keyName> \n\n" +
                "Where:\n" +
                "    bucketName - the Amazon S3 bucket name.\n\n"+
                "    keyName - a key name that represents the object. \n\n";

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String bucketName =  args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1 ;
        S3Client s3 = S3Client.builder()
                .region(region)
                .build();

        getURL(s3,bucketName,keyName);
        s3.close();
    }

    // snippet-start:[s3.java2.getobjecturl.main]
    public static void getURL(S3Client s3, String bucketName, String keyName ) {

        try {

            GetUrlRequest request = GetUrlRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .build();

            URL url = s3.utilities().getUrl(request);
            System.out.println("The URL for  "+keyName +" is "+url.toString());

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
    // snippet-end:[s3.java2.getobjecturl.main]
}
</code>```

Body:
I uploaded a file to my  Amazon S3 bucket and I would like to get a url using the aws-SDK not console for the object that I put in. The object has public read access
I have tried using

const url = s3Client.getSignedUrl('getObject', {
        Bucket: srcBucket,
        Key: key,
    });

but that generates a signed url that expires. I can't seem to find any other method to fetch just the url. Any help is much appreciated.

Body:
You can get the URL of an Amazon S3 object using the AWS SDK for Java V2. Here is the code:

// snippet-start:[s3.java2.getobjecturl.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetUrlRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.net.URL;
// snippet-end:[s3.java2.getobjecturl.import]

public class GetObjectUrl {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    <bucketName> <keyName> \n\n" +
                "Where:\n" +
                "    bucketName - the Amazon S3 bucket name.\n\n"+
                "    keyName - a key name that represents the object. \n\n";

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String bucketName =  args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1 ;
        S3Client s3 = S3Client.builder()
                .region(region)
                .build();

        getURL(s3,bucketName,keyName);
        s3.close();
    }

    // snippet-start:[s3.java2.getobjecturl.main]
    public static void getURL(S3Client s3, String bucketName, String keyName ) {

        try {

            GetUrlRequest request = GetUrlRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .build();

            URL url = s3.utilities().getUrl(request);
            System.out.println("The URL for  "+keyName +" is "+url.toString());

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
    // snippet-end:[s3.java2.getobjecturl.main]
}


问:
How can I retrieve the value of an attribute supported by Oracle?

Tablespace FlashBack

```<code>CREATE TABLESPACE TS_Physical
    DATAFILE
        '\physical_df.dbf'
            SIZE 1024000
            AUTOEXTEND OFF
    BLOCKSIZE 8192
    LOGGING
    FORCE LOGGING
    ONLINE
    EXTENT MANAGEMENT
        LOCAL AUTOALLOCATE
    SEGMENT SPACE MANAGEMENT AUTO
    FLASHBACK ON;
</code>```

I looked up USER_TABLESPACES and DBA_TABLESPACES that store tablespace information, but there is no entry called FlashBack.

SELECT * FROM USER_TABLESPACES;
SELECT * FROM DBA_TABLESPACES;
```

I obviously have flashback on. How can I query whether the tablespace is using flashback or not?

If it is an item that cannot be viewed, please share a link to the related document.

答:
V$TABLESPACE.FLASHBACK_ON</p>
```<code>SQL> select name,flashback_on from v$tablespace;

NAME                           FLASHBACK_ON
------------------------------ ------------
SYSTEM                         YES
SYSAUX                         YES
UNDOTBS1                       YES
TEMP                           YES
USERS                          YES

</code>```

Body:
Tablespace FlashBack

CREATE TABLESPACE TS_Physical
    DATAFILE
        '\physical_df.dbf'
            SIZE 1024000
            AUTOEXTEND OFF
    BLOCKSIZE 8192
    LOGGING
    FORCE LOGGING
    ONLINE
    EXTENT MANAGEMENT
        LOCAL AUTOALLOCATE
    SEGMENT SPACE MANAGEMENT AUTO
    FLASHBACK ON;

I looked up USER_TABLESPACES and DBA_TABLESPACES that store tablespace information, but there is no entry called FlashBack.

SELECT * FROM USER_TABLESPACES;
SELECT * FROM DBA_TABLESPACES;

I obviously have flashback on. How can I query whether the tablespace is using flashback or not?

If it is an item that cannot be viewed, please share a link to the related document.

Body:
V$TABLESPACE.FLASHBACK_ON

SQL> select name,flashback_on from v$tablespace;

NAME                           FLASHBACK_ON
------------------------------ ------------
SYSTEM                         YES
SYSAUX                         YES
UNDOTBS1                       YES
TEMP                           YES
USERS                          YES


问:
Error on deserialization of Array Collection in Flex: RangeError: Error #2006
I am getting this error during serialization:

RangeError: Error #2006: The supplied
  index is out of bounds.
  The error occurs in AbstractMessage.as when it attempts to read input of timestamp.

After that my fault handler gets this error:

faultCode:Server.Acknowledge.Failed
  faultString:'Didn't receive an
  acknowledge message' faultDetail:'Was
  expecting
  mx.messaging.messages.AcknowledgeMessage,
  but received null'

It appears to be happening as a result of an ArrayCollection coming back from the server.

Is it necessary to create custom classes to handle serialization of ArrayCollections with custom objects as shown here?

I've also followed the serialization recommendations here with no luck.

Thanks for your help!

答: The solution was correcting a mistake in writeExternal on the Java side. I was being very careful about the order of serialization but was writing an int as an object using writeObject.  This will cause errors in completely unrelated code on the client side after it tries to readInt.</p>

OwnerDisplayName: Brandon

ContentLicense: CC BY-SA 2.5


问:
PayPal createOrder() How to include multiple items in a purchase_item
This question has been (not fully) addressed in other posts such as PayPal Orders API schema.  The API seems to indicate that multiple purchase_items can exist in an order, which act as 'contracts' between payer and sellor.  The docs also seem indicate a procession like this:
[purchase_items][purchase_item_request][items][item].  I have looked at the example on the API page, and altered it to include three items, and it worked, BUT it makes three charges against the credit card, where it should be just one charge for the total.  So this works ... sorta.

So I tried this to see if I could get Paypal to only make one charge:

And, Trying to follow the documentation, I went with the following:

The last attempt produces an error like the others the purchase_units section is mal-formed, which is partially seen in this graphic:

Now the error message includes a handy link to read about the error:

"href": "https://developer.paypal.com/docs/api/orders/v2/#error-MALFORMED_REQUEST_JSON"

But this just sends you, or changes to https://developer.paypal.com/api/orders/v2/ which is where I have been reading  and reading.

I think, I hope I am close with the last effort above, yet I have tried more than just the two example above.

Your suggestions would be welcome.  This is Orders, v2, paypal api.

I am also using laravel with https://github.com/srmklive/laravel-paypal

I tried this as well.  Did not work.  HELP!

答:
purchase_units takes an array with no key names, i.e. purchase_units[0] must exist (and is usually the only one, unless paying multiple sellers at once)

The key name purchase_units_request is nonsense, there is none called this so it will be ignored....

The key name orders_application_context is also nonsense and will be ignored, there is no key called that either (but there is an application_context key)

Don't confuse object names in the document with the actual key name such an object goes under; look at the parent object's description for the correct key name of its members, starting with the request body and building your hierarchy out that way.

For a working example of a purchase_units with an item in JSON format (not a PHP object array, but can be converted to one), see the Integrate Checkout guide, bullet #6 in 'Add and modify the code'.


问:
diff_match_patch google library is not working as expected in C#
I am writing the text change tracking add-in and my code is:

```<code>   mDiffMatchPatch = new diff_match_patch()
   List<Diff> diffList = mDiffMatchPatch.diff_main(OriginalText, ModifiedText);
   mDiffMatchPatch.diff_cleanupSemantic(diffList);
</code>```

Where  Diff  is an object  with two  properties, 'text' and 'operation'

My original text is :

When I just insert the word 'ice' after 'installer' is shows up as it should:

But when I highlight 'installer' and type 'ice' on top of it (replacing 'installer' by 'ice' in one operation), it shows incorrectly.

That is, it takes the first letter of original 'installer' and separates 'i' from 'ce' in 'ice'.

I checked and re-rechecked and my text color rendering is correct. It is the diff_match_match breaks the 'i' from 'ice' in order to match it with the 'i' of 'installer'.

Is there any remedy for this? If not, is there alternative libraries in C# for diff_match_patch?

M

答: I resolved it by following the guidance on project github page. That is, using the word-based diff function of the diff_match_patch object. You create it by copying line-based function and modifying it per article.</p>

Body:
I am writing the text change tracking add-in and my code is:

   mDiffMatchPatch = new diff_match_patch()
   List<Diff> diffList = mDiffMatchPatch.diff_main(OriginalText, ModifiedText);
   mDiffMatchPatch.diff_cleanupSemantic(diffList);

Where  Diff  is an object  with two  properties, 'text' and 'operation'

My original text is :

When I just insert the word 'ice' after 'installer' is shows up as it should:

But when I highlight 'installer' and type 'ice' on top of it (replacing 'installer' by 'ice' in one operation), it shows incorrectly.

That is, it takes the first letter of original 'installer' and separates 'i' from 'ce' in 'ice'.

I checked and re-rechecked and my text color rendering is correct. It is the diff_match_match breaks the 'i' from 'ice' in order to match it with the 'i' of 'installer'.

Is there any remedy for this? If not, is there alternative libraries in C# for diff_match_patch?

M


问:
Changing a variable attribute into the variable name
I have an SPSS file that I uploaded into R and I want the label attribute to become the actual variable name across the dataframe. What function can I use?</p>

答:
If you used haven to read in the file, you can use labelled::var_label():

```<code>library(haven)
library(labelled)

mydata <- read_sav("filename.sav")

# `var_label()` returns a list - need to coerce to character vector to assign
names(mydata) <- as.character(var_label(mydata))

</code>```

Body:
If you used haven to read in the file, you can use labelled::var_label():

library(haven)
library(labelled)

mydata <- read_sav("filename.sav")

# `var_label()` returns a list - need to coerce to character vector to assign
names(mydata) <- as.character(var_label(mydata))


问:
Convert Python Bytes to String Without Encoding
I am using Python 3.6 and I have an image as bytes:

```<code>img = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00'
</code>```

I need to convert the bytes into a string without encoding so it looks like:

```<code>raw_img = '\xff\xd8\xff\xe0\x00\x10JFIF\x00'
</code>```

The goal is to incorporate this into an html image tag:

```<code><img src="'data:image/png;base64," + base64.b64encode(raw_img) + "' />"
</code>```

答:
I've solved it (2022 - bit late to the party...)
If you try img_raw.decode() you get the
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte error

But if you leave img_raw as a binary string and pass it into b64encode and then decode it, it doesn't have the UnicodeDecodeError, and you can pass it in as a data string to your image tag.

base64.b64encode(raw_image).decode()

ContentLicense: CC BY-SA 3.0

Body:
I am using Python 3.6 and I have an image as bytes:

img = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00'

I need to convert the bytes into a string without encoding so it looks like:

raw_img = '\xff\xd8\xff\xe0\x00\x10JFIF\x00'

The goal is to incorporate this into an html image tag:

"


问:
Rename an image before upload in angular
I'm working with image upload in angular. The image uploading part works fine but now the problem is I should rename the image before uploading.
I want to know if it will be easier to do so from the fronend or from the backend.
The framework used for frontend is angularand backend is nodejs.
Hope someone will help me with this since I dont have much experience with this framework
Thank you.

答:
This is an very opinionated question. On the frontend I imagine your using some sort of form to attach the file. On frontend it could be as easy as this:

formData.append('userpic', myFileInput.files[0], 'chris.jpg');
```

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

Body:
This is an very opinionated question. On the frontend I imagine your using some sort of form to attach the file. On frontend it could be as easy as this:

formData.append('userpic', myFileInput.files[0], 'chris.jpg');

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append


问:
Updating nonzero values in an array, A, with the values of a different array, B, whose size is equal to number of nonzero values in A
I have an array, A. Its length may vary but it’s always filled with 1’s and/or 0's.

```<code>A = np.array([1,0,1,0])
</code>```

A gets passed into a function that produces array B.

```<code>B = np.array([0.75, 0.25])
</code>```

B’s length is always equal to the number of 1's in A.

How can I most efficiently update A (or create a new array) that equals

```<code>[0.75, 0, 0.25, 0]
</code>```

in this example? My hope is for it to work with any size array A that meets the constraints I’ve laid out for B above. The first value of B is always the first 1 in A and so on.

I got it to work by converting them to lists and looping

```<code>pos = 0
for i in range(len(a)):
    if a[i] == 1:
        a[i] = b[pos]
        pos += 1
</code>```

But I’m hoping for a better solution because I’ll have to do this a lot and A and B could potentially be much larger.

答:
```<code>In [1]: A = np.array([1,0,1,0])
</code>```

First you want to identify the nonzero elements.  There are several ways:

```<code>In [2]: A.astype(bool)
Out[2]: array([ True, False,  True, False])
In [3]: A>0
Out[3]: array([ True, False,  True, False])
In [4]: np.nonzero(A)
Out[4]: (array([0, 2]),)
</code>```

Any of these can be used to select those elements; both for getting and setting:

```<code>In [5]: A[np.nonzero(A)]
Out[5]: array([1, 1])
In [6]: A[np.nonzero(A)] = [2,3]
In [7]: A
Out[7]: array([2, 0, 3, 0])
In [8]: A[[0,2]]
Out[8]: array([2, 3])
</code>```

But if we try to assign the two float values, they get truncated:

```<code>In [9]: A[[0,2]] = [.25, .75]
In [10]: A
Out[10]: array([0, 0, 0, 0])
</code>```

A needs to be float dtype:

```<code>In [11]: A1=A.astype(float)
In [12]: A1[[0,2]] = [.25, .75]
In [13]: A1
Out[13]: array([0.25, 0.  , 0.75, 0.  ])
</code>```

Body:
I have an array, A. Its length may vary but it’s always filled with 1’s and/or 0's.

A = np.array([1,0,1,0])

A gets passed into a function that produces array B.

B = np.array([0.75, 0.25])

B’s length is always equal to the number of 1's in A.

How can I most efficiently update A (or create a new array) that equals

[0.75, 0, 0.25, 0]

in this example? My hope is for it to work with any size array A that meets the constraints I’ve laid out for B above. The first value of B is always the first 1 in A and so on.

I got it to work by converting them to lists and looping

pos = 0
for i in range(len(a)):
    if a[i] == 1:
        a[i] = b[pos]
        pos += 1

But I’m hoping for a better solution because I’ll have to do this a lot and A and B could potentially be much larger.

Body:
In [1]: A = np.array([1,0,1,0])

First you want to identify the nonzero elements.  There are several ways:

In [2]: A.astype(bool)
Out[2]: array([ True, False,  True, False])
In [3]: A>0
Out[3]: array([ True, False,  True, False])
In [4]: np.nonzero(A)
Out[4]: (array([0, 2]),)

Any of these can be used to select those elements; both for getting and setting:

In [5]: A[np.nonzero(A)]
Out[5]: array([1, 1])
In [6]: A[np.nonzero(A)] = [2,3]
In [7]: A
Out[7]: array([2, 0, 3, 0])
In [8]: A[[0,2]]
Out[8]: array([2, 3])

But if we try to assign the two float values, they get truncated:

In [9]: A[[0,2]] = [.25, .75]
In [10]: A
Out[10]: array([0, 0, 0, 0])

A needs to be float dtype:

In [11]: A1=A.astype(float)
In [12]: A1[[0,2]] = [.25, .75]
In [13]: A1
Out[13]: array([0.25, 0.  , 0.75, 0.  ])


问:
safety -- late initialization error // FLUTTER

I have an error in the code because of safety in Flutter and I have tried to solve it with the declaration of variables using LATE.<br /

But it appears antother one when I try to build it:

Error

This is my code:

```<code>class AnimacionesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CuadradoAnimado(),
      ),
    );
  }
}

class CuadradoAnimado extends StatefulWidget {
  @override
  _CuadradoAnimadoState createState() => _CuadradoAnimadoState();
}

class _CuadradoAnimadoState extends State<CuadradoAnimado>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> rotacion;

@override
  void initState() {
    controller = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 4000));

    rotacion = Tween(begin: 0.0, end: 2 * Math.pi)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));

 @override
  Widget build(BuildContext context) {
    // Play / Reproducción
    controller.forward();

    return AnimatedBuilder(
      animation: controller,
      child: _Rectangulo(),
</code>```

答:
Hey Ignacio and welcome to the StackOverFlow community

It should work well but try to correct a few things.

At first this is a snippet of code that will explain something like what you want to do:

```<code>import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> rotacion;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 4000));

    rotacion = Tween<double>(begin: 0.0, end: 250)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));
    controller.forward();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
          animation: rotacion,
          builder: (context, _) {
            return Container(
              margin: const EdgeInsets.symmetric(vertical: 10),
              height: rotacion.value,
              width: rotacion.value,
              child: const FlutterLogo(),
            );
          }),
    );
  }
}
</code>```

The first thing (you may forget to add it but it's just a reminder), make sure to close the curly braces of the init state and any other syntax issues.

The second thing is that you should forward the controller in the init state, not in the build because you want to forward it the first time, not every time you build the component.

The third point is the widget that I want to make the animation in, I wrapped it with another widget called AnimatedBuilder: it's a general-purpose widget for building animations (There are other ways to create the animation for sure).

The final point is that don't forget to dispose your controller, because you need to release the resources used by this object because when the widget disposed, the object is no longer usable.

If you did all of that (and make sure to read the snippet of code), it will work very well.

Body:
I have an error in the code because of safety in Flutter and I have tried to solve it with the declaration of variables using LATE.<br /

But it appears antother one when I try to build it:

Error

This is my code:

class AnimacionesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CuadradoAnimado(),
      ),
    );
  }
}

class CuadradoAnimado extends StatefulWidget {
  @override
  _CuadradoAnimadoState createState() => _CuadradoAnimadoState();
}

class _CuadradoAnimadoState extends State<CuadradoAnimado>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> rotacion;

@override
  void initState() {
    controller = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 4000));

    rotacion = Tween(begin: 0.0, end: 2 * Math.pi)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));

 @override
  Widget build(BuildContext context) {
    // Play / Reproducción
    controller.forward();

    return AnimatedBuilder(
      animation: controller,
      child: _Rectangulo(),

Body:
Hey Ignacio and welcome to the StackOverFlow community

It should work well but try to correct a few things.

At first this is a snippet of code that will explain something like what you want to do:

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> rotacion;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 4000));

    rotacion = Tween<double>(begin: 0.0, end: 250)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));
    controller.forward();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
          animation: rotacion,
          builder: (context, _) {
            return Container(
              margin: const EdgeInsets.symmetric(vertical: 10),
              height: rotacion.value,
              width: rotacion.value,
              child: const FlutterLogo(),
            );
          }),
    );
  }
}

The first thing (you may forget to add it but it's just a reminder), make sure to close the curly braces of the init state and any other syntax issues.

The second thing is that you should forward the controller in the init state, not in the build because you want to forward it the first time, not every time you build the component.

The third point is the widget that I want to make the animation in, I wrapped it with another widget called AnimatedBuilder: it's a general-purpose widget for building animations (There are other ways to create the animation for sure).

The final point is that don't forget to dispose your controller, because you need to release the resources used by this object because when the widget disposed, the object is no longer usable.

If you did all of that (and make sure to read the snippet of code), it will work very well.


问:
How can I make a function that prints the number of unique vowels in a string?
I am creating a program that prints the number of unique vowels in a string, whether upper or lower case. For example: "swEet” would print 1. What I have so far prints the number of vowels but not unique ones. What can I change or add to my code to do this? Thank you. I'm a beginner in Python and coding.

```<code>import sys

def count_vowels(sys_str):

    sys_str = sys.argv[1].upper()

    vowels = 'aeiou'

    count = len([c for c in sys_str.lower() if c in
    vowels])

    return count

sys_str = sys.argv[1].upper()
count = count_vowels(sys_str)
print(count)
</code>```

Source: DBrowne's answer at Counting the number of vowels in a string using for loops in Python I got some of my code from this user in this question.

答:
First off Eat actually has 2 vowels "E" and "a".

Second You won't need to use the sys module

You can simplify your code to this if you're just trying to find the vowels in a string:

```<code>def count_vowels(sys_str):
    vowels = 'aeiou'
    count = len([c for c in sys_str.lower() if c in vowels])
    return count
</code>```

As for finding unique vowels you can write something like this:

```<code>    def count_vowels(string):
        vowels = 'aeiou'
        hashmap = {}
        array = []

        for i, c in enumerate(string.lower()):
            if c not in hashmap:
                array.append(c)
                hashmap[c] = i
            else:
                array.pop(hashmap[c])
        return len(array)
</code>```

Example:

```<code>count_vowels('Eeat')
Output: 1 #<- This is because there are 2 e's now so a is the only unique vowel
</code>```

Obviously, there's a lot more efficient time and space solution out there. This is just something off the top of my head. Hopes This helps!

Body:
I am creating a program that prints the number of unique vowels in a string, whether upper or lower case. For example: "swEet” would print 1. What I have so far prints the number of vowels but not unique ones. What can I change or add to my code to do this? Thank you. I'm a beginner in Python and coding.

import sys

def count_vowels(sys_str):

    sys_str = sys.argv[1].upper()

    vowels = 'aeiou'

    count = len([c for c in sys_str.lower() if c in
    vowels])

    return count

sys_str = sys.argv[1].upper()
count = count_vowels(sys_str)
print(count)

Source: DBrowne's answer at Counting the number of vowels in a string using for loops in Python I got some of my code from this user in this question.

Body:
First off Eat actually has 2 vowels "E" and "a".

Second You won't need to use the sys module

You can simplify your code to this if you're just trying to find the vowels in a string:

def count_vowels(sys_str):
    vowels = 'aeiou'
    count = len([c for c in sys_str.lower() if c in vowels])
    return count

As for finding unique vowels you can write something like this:

    def count_vowels(string):
        vowels = 'aeiou'
        hashmap = {}
        array = []

        for i, c in enumerate(string.lower()):
            if c not in hashmap:
                array.append(c)
                hashmap[c] = i
            else:
                array.pop(hashmap[c])
        return len(array)

Example:

count_vowels('Eeat')
Output: 1 #<- This is because there are 2 e's now so a is the only unique vowel

Obviously, there's a lot more efficient time and space solution out there. This is just something off the top of my head. Hopes This helps!


问:
Does anyone can fix my learning C# code of randomNumn and writeOut?
I have a problem of my C# code. Here is an code that I tried:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Console_test
{
    class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine(writeOut(5,4));
          Console.ReadLine();
        }

        static int randomNum()
        {
            return 4;
        }

        static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
        }
    }
}
</code>```

I have a one error, can anyone fix my code? I'm not good with C#.
Error says not all code paths returns a value.

答:
```<code> static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
        }
</code>```

This function is wrong.
After the Static it says "int" this means your function must return an int.
at the end of the function I think you want to add "Return total;"
this will fix your error.

```<code> static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
          return total;
        }
</code>```

Body:
I have a problem of my C# code. Here is an code that I tried:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Console_test
{
    class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine(writeOut(5,4));
          Console.ReadLine();
        }

        static int randomNum()
        {
            return 4;
        }

        static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
        }
    }
}

I have a one error, can anyone fix my code? I'm not good with C#.
Error says not all code paths returns a value.

Body:
 static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
        }

This function is wrong.
After the Static it says "int" this means your function must return an int.
at the end of the function I think you want to add "Return total;"
this will fix your error.

 static int writeOut(int num1, int num2)
        {
            int total = num1 + num2;
          Console.WriteLine(total);
          return total;
        }


问:
How to query in mysql when involving more than one table?
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

```<code>Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED
</code>```

答:
Use JOIN statement.

For example:

```<code>SELECT A.ID, A.`NUMBER OF ORDER`, B.ID, B.STATUS
FROM A
INNER JOIN B ON A.ID = B.A_ID
WHERE B.STATUS = 'COMPLETED';
</code>```

Learn about inner and outer joins, they might be useful in different cases.

To output info only if EVERY status is COMPLETED, you might use nested queries:

```<code>SELECT A.ID, A.`NUMBER OF ORDER`, B.ID, B.STATUS
FROM A
INNER JOIN B ON A.ID = B.A_ID
WHERE (SELECT COUNT(STATUS) FROM B WHERE B.STATUS <> 'COMPLETED') = 0;
</code>```

In this example, first query to be executed will be:

```<code>SELECT COUNT(STATUS)
FROM B
WHERE B.STATUS <> 'COMPLETED'
</code>```

It will return the amount of IDs with statuses NOT equal to COMPLETED.

After that, it will output every row from the joined table, where that amount equals to 0.

Since the amount is not depending on the row of the joined table, it will either output everything or nothing.

Body:
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED

Body:
Use JOIN statement.

For example:

SELECT A.ID, A.`NUMBER OF ORDER`, B.ID, B.STATUS
FROM A
INNER JOIN B ON A.ID = B.A_ID
WHERE B.STATUS = 'COMPLETED';

Learn about inner and outer joins, they might be useful in different cases.

To output info only if EVERY status is COMPLETED, you might use nested queries:

SELECT A.ID, A.`NUMBER OF ORDER`, B.ID, B.STATUS
FROM A
INNER JOIN B ON A.ID = B.A_ID
WHERE (SELECT COUNT(STATUS) FROM B WHERE B.STATUS <> 'COMPLETED') = 0;

In this example, first query to be executed will be:

SELECT COUNT(STATUS)
FROM B
WHERE B.STATUS <> 'COMPLETED'

It will return the amount of IDs with statuses NOT equal to COMPLETED.

After that, it will output every row from the joined table, where that amount equals to 0.

Since the amount is not depending on the row of the joined table, it will either output everything or nothing.


问:
How to make My Sql Pod to save data in Persistent Volume
I started to use Kubernetes to understant concepts like pods, objects and so on. I started to learn about Persistent Volume and Persistent Volume Claim, from my understanding, if i save data from mysql pod to a persistent volume, the data is saved no matter if i delete the mysql pod, the data is saved on the volume, but i don't think it works in my case...

I have a spring boot pod where i save data in mysql pod, data is saved, i can retreived, but when i restart my pods, delete or replace them, that saved data is lost, so i think i messed up something, can you give me a hint, please? Thanks...

Bellow are my Kubernetes files:

Mysql pod:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels: #must match Service and DeploymentLabels
        app: mysql
    spec:
      containers:
        - image: mysql:5.7
          args:
            - "--ignore-db-dir=lost+found"
          name: mysql #name of the db
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-secret #name of the secret obj
                  key: password #which value from inside the secret to take
            - name: MYSQL_ROOT_USER
              valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: username
            - name: MYSQL_DATABASE
              valueFrom:
                configMapKeyRef:
                  name: db-config
                  key: name
          ports:
            - containerPort: 3306
              name: mysql
        volumeMounts: #mount volume obtained from PVC
          - name: mysql-persistent-storage
            mountPath: /var/lib/mysql #mounting in the container will be here

  volumes:
    - name: mysql-persistent-storage #obtaining volume from PVC
      persistentVolumeClaim:
        claimName: mysql-pv-claim # can use the same claim in different pods
</code>```

```<code>apiVersion: v1
kind: Service
metadata:
  name: mysql #DNS name
  labels:
    app: mysql
spec:
  ports:
    - port: 3306
      targetPort: 3306
  selector: #mysql pod should contain same label
    app: mysql
  clusterIP: None # we use DNS
</code>```

Persistent Volume and Persistent Volume Claim files:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim #name of our pvc
  labels:
    app: mysql
spec:
  volumeName: host-pv #claim that volume created with this name
  accessModes:
    - ReadWriteOnce
  storageClassName: standard
  resources:
    requests:
      storage: 1Gi
</code>```

```<code>apiVersion: v1 #version of our PV
kind: PersistentVolume #kind of obj we gonna create
metadata:
  name: host-pv # name of our PV
spec: #spec of our PV
  capacity: #size
    storage: 4Gi
  volumeMode: Filesystem #storage Type, File and Blcok
  storageClassName: standard
  accessModes:
    - ReadWriteOnce  # can be mount from multiple pods on a single nod, cam be use by multiple pods, multiple pods can use this pv but only from a single node
   # - ReadOnlyMany    #                                on multiple nodes
   # - WriteOnlyMany   #  doar pt multiple nods, nu hostPath type
  hostPath: #which type of pv
    path: "/mnt/data"
    type: DirectoryOrCreate
  persistentVolumeReclaimPolicy: Retain
</code>```

My Spring book K8 file:

```<code>apiVersion: v1
kind: Service
metadata:
  name: book-service
spec:
  selector:
    app: book-example
  ports:
    - protocol: 'TCP'
      port: 8080
      targetPort: 8080
  type: LoadBalancer

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: book-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: book-example
  template:
    metadata:
      labels:
        app: book-example
    spec:
      containers:
        - name: book-container
          image: cinevacineva/kubernetes_book_pv:latest
          imagePullPolicy: Always
      #    ports:
      #      - containerPort: 8080
          env:
            - name: DB_HOST
              valueFrom:
                configMapKeyRef:
                  name: db-config
                  key: host
            - name: DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: db-config
                  key: name
            - name: DB_USERNAME
              valueFrom:
                secretKeyRef:
                  name: db-user
                  key: username
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-user
                  key: password

#  & minikube -p minikube docker-env | Invoke-Expression    links docker images we create with minikube, nu mai trebe sa ppusham
</code>```

答:
...if i save data from mysql pod to a persistent volume, the data is saved no matter if i delete the mysql pod, the data is saved on the volume, but i don't think it works in my case...

Your previous data will not be available when the pod switch node. To use hostPath you don't really need PVC/PV. Try:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  ...
spec:
  ...
  template:
    ...
    spec:
      ...
      nodeSelector:    # <-- make sure your pod runs on the same node
        <node label>: <value unique to the mysql node>
      volumes:         # <-- mount the data path on the node, no pvc/pv required.
      - name: mysql-persistent-storage
        hostPath:
          path: /mnt/data
          type: DirectoryOrCreate
      containers:
      - name: mysql
        ...
        volumeMounts:  # <-- let mysql write to it
        - name: mysql-persistent-storage
          mountPath: /var/lib/mysql

</code>```

Body:
I started to use Kubernetes to understant concepts like pods, objects and so on. I started to learn about Persistent Volume and Persistent Volume Claim, from my understanding, if i save data from mysql pod to a persistent volume, the data is saved no matter if i delete the mysql pod, the data is saved on the volume, but i don't think it works in my case...

I have a spring boot pod where i save data in mysql pod, data is saved, i can retreived, but when i restart my pods, delete or replace them, that saved data is lost, so i think i messed up something, can you give me a hint, please? Thanks...

Bellow are my Kubernetes files:

Mysql pod:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels: #must match Service and DeploymentLabels
        app: mysql
    spec:
      containers:
        - image: mysql:5.7
          args:
            - "--ignore-db-dir=lost+found"
          name: mysql #name of the db
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-secret #name of the secret obj
                  key: password #which value from inside the secret to take
            - name: MYSQL_ROOT_USER
              valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: username
            - name: MYSQL_DATABASE
              valueFrom:
                configMapKeyRef:
                  name: db-config
                  key: name
          ports:
            - containerPort: 3306
              name: mysql
        volumeMounts: #mount volume obtained from PVC
          - name: mysql-persistent-storage
            mountPath: /var/lib/mysql #mounting in the container will be here

  volumes:
    - name: mysql-persistent-storage #obtaining volume from PVC
      persistentVolumeClaim:
        claimName: mysql-pv-claim # can use the same claim in different pods

apiVersion: v1
kind: Service
metadata:
  name: mysql #DNS name
  labels:
    app: mysql
spec:
  ports:
    - port: 3306
      targetPort: 3306
  selector: #mysql pod should contain same label
    app: mysql
  clusterIP: None # we use DNS

Persistent Volume and Persistent Volume Claim files:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim #name of our pvc
  labels:
    app: mysql
spec:
  volumeName: host-pv #claim that volume created with this name
  accessModes:
    - ReadWriteOnce
  storageClassName: standard
  resources:
    requests:
      storage: 1Gi

apiVersion: v1 #version of our PV
kind: PersistentVolume #kind of obj we gonna create
metadata:
  name: host-pv # name of our PV
spec: #spec of our PV
  capacity: #size
    storage: 4Gi
  volumeMode: Filesystem #storage Type, File and Blcok
  storageClassName: standard
  accessModes:
    - ReadWriteOnce  # can be mount from multiple pods on a single nod, cam be use by multiple pods, multiple pods can use this pv but only from a single node
   # - ReadOnlyMany    #                                on multiple nodes
   # - WriteOnlyMany   #  doar pt multiple nods, nu hostPath type
  hostPath: #which type of pv
    path: "/mnt/data"
    type: DirectoryOrCreate
  persistentVolumeReclaimPolicy: Retain

My Spring book K8 file:

apiVersion: v1
kind: Service
metadata:
  name: book-service
spec:
  selector:
    app: book-example
  ports:
    - protocol: 'TCP'
      port: 8080
      targetPort: 8080
  type: LoadBalancer

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: book-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: book-example
  template:
    metadata:
      labels:
        app: book-example
    spec:
      containers:
        - name: book-container
          image: cinevacineva/kubernetes_book_pv:latest
          imagePullPolicy: Always
      #    ports:
      #      - containerPort: 8080
          env:
            - name: DB_HOST
              valueFrom:
                configMapKeyRef:
                  name: db-config
                  key: host
            - name: DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: db-config
                  key: name
            - name: DB_USERNAME
              valueFrom:
                secretKeyRef:
                  name: db-user
                  key: username
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-user
                  key: password

#  & minikube -p minikube docker-env | Invoke-Expression    links docker images we create with minikube, nu mai trebe sa ppusham

Body:
...if i save data from mysql pod to a persistent volume, the data is saved no matter if i delete the mysql pod, the data is saved on the volume, but i don't think it works in my case...

Your previous data will not be available when the pod switch node. To use hostPath you don't really need PVC/PV. Try:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  ...
spec:
  ...
  template:
    ...
    spec:
      ...
      nodeSelector:    # <-- make sure your pod runs on the same node
        <node label>: <value unique to the mysql node>
      volumes:         # <-- mount the data path on the node, no pvc/pv required.
      - name: mysql-persistent-storage
        hostPath:
          path: /mnt/data
          type: DirectoryOrCreate
      containers:
      - name: mysql
        ...
        volumeMounts:  # <-- let mysql write to it
        - name: mysql-persistent-storage
          mountPath: /var/lib/mysql


问:
uwp dynamic storyboard target name
I have a Button in inside a ListView.ItemTemplate which mimicks the behavior of a dropdown button. And I want to give the button a rotation animation by using a StoryBoard.

```<code><Storyboard x:Name="FolderPathItemArrowAnimation">
    <DoubleAnimation
        By="90"
        Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)"
        Duration="0:0:0.25" />
</Storyboard>

<ListView
     Background="AntiqueWhite"
     HorizontalAlignment="Stretch"
     ItemsSource="{x:Bind FolderChain, Mode=OneWay}"
     ItemContainerStyle="{StaticResource StretchListViewItemStyle}"
     Style="{StaticResource HorizontalListViewStyle}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="models:FolderTree">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <Button
                            Style="{StaticResource FolderChainButtonStyle}"
                            Click="PathItemButton_Click" >
                            <Button.Content>
                                <TextBlock Text="{x:Bind Name}" />
                            </Button.Content>
                        </Button>
                        <Button
                            Name="{x:Bind Id, Converter={StaticResource FolderChainDropdownButtonNameConverter}}"
                            Grid.Column="1"
                            Width="30"
                            Click="PathItemDropDownButton_Click"
                            Style="{StaticResource FolderChainButtonStyle}"
                            Content=""
                            FontFamily="Segoe MDL2 Assets"
                            RenderTransformOrigin=".5,.5" >
                            <Button.RenderTransform>
                                <RotateTransform />
                            </Button.RenderTransform>
                        </Button>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

Below is the code to start the animation. When running, I get an Exception says that Cannot resolve TargetName FolderChainItemDropdownButton1. How can I use StoryBoard on ListView.ItemTemplate?

```<code>    private void PathItemDropDownButton_Click(object sender, RoutedEventArgs e)
    {
        Storyboard.SetTargetName(FolderPathItemArrowAnimation, (sender as FrameworkElement).Name);
        FolderPathItemArrowAnimation.Begin();
    }
</code>```

答:
get an Exception says that Cannot resolve TargetName FolderChainItemDropdownButton1

It looks SetTargetName method can not get correct element where under DataTemplate. please try to use SetTarget method to replace.

```<code>Storyboard.SetTarget(FolderPathItemArrowAnimation, (sender as FrameworkElement));
</code>```

Title: uwp dynamic storyboard target name

Body:
I have a Button in inside a ListView.ItemTemplate which mimicks the behavior of a dropdown button. And I want to give the button a rotation animation by using a StoryBoard.

<Storyboard x:Name="FolderPathItemArrowAnimation">
    <DoubleAnimation
        By="90"
        Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)"
        Duration="0:0:0.25" />
</Storyboard>

<ListView
     Background="AntiqueWhite"
     HorizontalAlignment="Stretch"
     ItemsSource="{x:Bind FolderChain, Mode=OneWay}"
     ItemContainerStyle="{StaticResource StretchListViewItemStyle}"
     Style="{StaticResource HorizontalListViewStyle}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="models:FolderTree">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <Button
                            Style="{StaticResource FolderChainButtonStyle}"
                            Click="PathItemButton_Click" >
                            <Button.Content>
                                <TextBlock Text="{x:Bind Name}" />
                            </Button.Content>
                        </Button>
                        <Button
                            Name="{x:Bind Id, Converter={StaticResource FolderChainDropdownButtonNameConverter}}"
                            Grid.Column="1"
                            Width="30"
                            Click="PathItemDropDownButton_Click"
                            Style="{StaticResource FolderChainButtonStyle}"
                            Content=""
                            FontFamily="Segoe MDL2 Assets"
                            RenderTransformOrigin=".5,.5" >
                            <Button.RenderTransform>
                                <RotateTransform />
                            </Button.RenderTransform>
                        </Button>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Below is the code to start the animation. When running, I get an Exception says that Cannot resolve TargetName FolderChainItemDropdownButton1. How can I use StoryBoard on ListView.ItemTemplate?

    private void PathItemDropDownButton_Click(object sender, RoutedEventArgs e)
    {
        Storyboard.SetTargetName(FolderPathItemArrowAnimation, (sender as FrameworkElement).Name);
        FolderPathItemArrowAnimation.Begin();
    }

Body:
get an Exception says that Cannot resolve TargetName FolderChainItemDropdownButton1

It looks SetTargetName method can not get correct element where under DataTemplate. please try to use SetTarget method to replace.

Storyboard.SetTarget(FolderPathItemArrowAnimation, (sender as FrameworkElement));


问:
jQuery - Set input range max to variable
I want to set my max on the input to be the difference between .total and .sold. Why is the max attribute not being set on the .qty input?

$(document).ready(function() {
  var total = $(".total").html();
  var sold = $(".sold").html();
  var available = $(".available").html(total - sold);
  $(".qty").attr({
    max: available
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sold<span class="sold">3</span> total
<span class="total">10</span> available
<span class="available"></span>
<input type="range" min="1" value="1" class="qty" name='quantity' oninput="num.value = this.value">
<output id="num">0</output></code>```

答:
It's because var available = $(".available").html(total - sold); returns a jQuery collection not a number. Try this

$(document).ready(function() {
  var total = $(".total").html();
  var sold = $(".sold").html();
  var available = total - sold; // now available is a number
  $(".available").html(available);
  $(".qty").attr({
    max: available
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sold<span class="sold">3</span> total
<span class="total">10</span> available
<span class="available"></span>
<input type="range" min="1" value="1" class="qty" name='quantity' oninput="num.value = this.value">
<output id="num">0</output></code>```

Body:
I want to set my max on the input to be the difference between .total and .sold. Why is the max attribute not being set on the .qty input?

$(document).ready(function() {
  var total = $(".total").html();
  var sold = $(".sold").html();
  var available = $(".available").html(total - sold);
  $(".qty").attr({
    max: available
  });
});

sold3 total
10 available

<input type="range" min="1" value="1" class="qty" name='quantity' oninput="num.value = this.value">
<output id="num">0</output>

Body:
It's because var available = $(".available").html(total - sold); returns a jQuery collection not a number. Try this

$(document).ready(function() {
  var total = $(".total").html();
  var sold = $(".sold").html();
  var available = total - sold; // now available is a number
  $(".available").html(available);
  $(".qty").attr({
    max: available
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sold<span class="sold">3</span> total
<span class="total">10</span> available
<span class="available"></span>
<input type="range" min="1" value="1" class="qty" name='quantity' oninput="num.value = this.value">
<output id="num">0</output>


问:
How to find the duplicates in a list and create another list with them ? with answer
My own Solution:

```<code>list1=[1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
counter=0
for j in list(set(list1)):
    for i in list1:
        if j==i:
            counter=counter+1
    print(j,"have",counter,"duplicates")
    counter=0
</code>```

give some suggestion

答:
Using collections.Counter:

```<code>>>> list1 = [1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
>>> from collections import Counter
>>> [(i, count) for i, count in Counter(list1).items() if count > 1]
[(4, 2), (5, 3), (6, 2), (8, 4)]
</code>```

Body:
My own Solution:

list1=[1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
counter=0
for j in list(set(list1)):
    for i in list1:
        if j==i:
            counter=counter+1
    print(j,"have",counter,"duplicates")
    counter=0

give some suggestion

Body:
Using collections.Counter:

>>> list1 = [1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
>>> from collections import Counter
>>> [(i, count) for i, count in Counter(list1).items() if count > 1]
[(4, 2), (5, 3), (6, 2), (8, 4)]


问:
Use same VM as self hosted integration runtime for two different adf instances
My question is very clear. As you can understand from the title, I want to use the same VM as self-hosted integration runtime for two different ADF instances. Is it possible to do that?

I can not see any option to register new ADF instances on Microsoft Integration Runtime Configuration Manager.

答:
You can share same VM as self-hosted IR with different data factories.

Currently self-hosted integration runtime can only be shared with multiple data factories, it can't be shared across Synapse workspaces or between data factory and Synapse workspace.

This document shows how to do it.

Considerations for using a self-hosted IR


问:
Make div align to bottom of column in card tailwind css
As the title states, I am trying to get a div within a parent div to align across columns using Tailwind CSS. However, they are not aligning due to different image sizes uploaded to each column. I do not want to resize the images. I have circled in red the divs I want aligning at the bottom. Github Repo

I have tried the different settings referenced here

The specific child div that I would like aligned is from

I was wondering if anyone could assist?

```<code>return (
<div className="flex justify-end">
  <div className="px-4" style={{ maxWidth: '1600px' }}>
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pt-4">
      {
        nfts.map((nft, i) => (
          <div key={i} className="border shadow rounded-xl overflow-hidden">
            <img src={nft.image} />
            <div className="p-4">
              <p style={{ height: '64px' }} className="text-2xl font-semibold">{nft.name}</p>
            <div style={{ height: '70px', overflow: 'hidden' }}>
              <p className="text-gray-400">{nft.description}</p>
              </div>
            </div>
            <div className="p-4 bg-black">
              <p className="text-2xl mb-4 font-bold text-white">{nft.price} Matic</p>
              <button className="w-full bg-pink-500 text-white font-bold py-2 px-12 rounded"
              onClick={() => buyNft(nft)}>Buy</button>
              </div>
          </div>
        ))
      }
    </div>
  </div>
</div>
</code>```

)
}

答:
You can wrap your top content in an element and apply CSS flexbox to the parent element.

flex - applies CSS flexbox

flex-col applies CSS flex-direction: column which stacks the child elements vertically

justify-between applies CSS justify-content: space-between, which tells the element to distribute children evenly. The first and last child elements will be at the furthest ends of the parent element (beginning and end).  Since the element has flex-col, the ends will be the top and bottom of the element.

flex-1 applies CSS flex: 1, which makes all the child elements fill to the parent's size; in this case, it will make the children all the same height.

Align details and images to the top and the buying info to the bottom

//must wrap content to be aligned to top

{nft.name}

{description}

//must wrap content to be aligned to bottom

{price} Matic

  <button>Buy</button>

```
<hr />
<p>Additional example - this will have all of the images at the top and all of the content at the bottom</p>
<pre class="lang-js prettyprint-override"><code><div className="flex flex-1 flex-col justify-between">
 <img src={image} /> // aligned top
 <div>// aligned bottom
  <p>{name}<p>
  <p>{description}</p>
  <p>{price} Matic</p>
  <button>Buy</button>
 </div>
</div>
</code>```

Body:
As the title states, I am trying to get a div within a parent div to align across columns using Tailwind CSS. However, they are not aligning due to different image sizes uploaded to each column. I do not want to resize the images. I have circled in red the divs I want aligning at the bottom. Github Repo

I have tried the different settings referenced here

The specific child div that I would like aligned is from

I was wondering if anyone could assist?

return (

      {
        nfts.map((nft, i) => (

{nft.name}

{nft.description}

{nft.price} Matic

              <button className="w-full bg-pink-500 text-white font-bold py-2 px-12 rounded"
              onClick={() => buyNft(nft)}>Buy</button>

        ))
      }

)
}

Body:
You can wrap your top content in an element and apply CSS flexbox to the parent element.

flex - applies CSS flexbox

flex-col applies CSS flex-direction: column which stacks the child elements vertically

justify-between applies CSS justify-content: space-between, which tells the element to distribute children evenly. The first and last child elements will be at the furthest ends of the parent element (beginning and end).  Since the element has flex-col, the ends will be the top and bottom of the element.

flex-1 applies CSS flex: 1, which makes all the child elements fill to the parent's size; in this case, it will make the children all the same height.

Align details and images to the top and the buying info to the bottom

<div className="flex flex-1 flex-col justify-between">
 <div>//must wrap content to be aligned to top
  <img src={image} />
  <p>{nft.name}<p>
  <p>{description}</p>
 </div>
 <div>//must wrap content to be aligned to bottom
  <p>{price} Matic</p>
  <button>Buy</button>
 </div>
</div>

Additional example - this will have all of the images at the top and all of the content at the bottom

<div className="flex flex-1 flex-col justify-between">
 <img src={image} /> // aligned top
 <div>// aligned bottom
  <p>{name}<p>
  <p>{description}</p>
  <p>{price} Matic</p>
  <button>Buy</button>
 </div>
</div>


问:
Using tapply to calculate the mean of a group
In the following CSV file:

```<code>Species, Age
australian, 2.6
australian, 2.3
brown, 2.3
brown, 2.3
brown, 3.4
brown, 3.4
dalmatian, 5.1
dalmatian, 4.4
dalmatian, 4.4
dalmatian, 4.1
dalmatian, 4.2
dalmatian, 4.7
dalmatian, 5.5
</code>```

I am attempting to calculate the mean for the Pelican species, but R is displaying an error about unequal lengths.

```<code>df <- read.csv('c:/Users/Michelle/Downloads/pelican.csv')
tapply(df$Species, df$Age, mean)
</code>```

Error in tapply(df$Species, df$Age, mean) :
arguments must have same length

I assumed the tapply function would output each pelican species with the mean age of each.
Unfortunately, the director at the University of Florida is insisting I use base R functions.

Edit 1:

```<code>str(df) 'data.frame': 13 obs. of 2 variables: $ Species: chr "australian" "australian" "brown" "brown" ... $ Age : num 2.6 2.3 2.3 2.3 3.4 3.4 5.1 4.4 4.4 4.1 ...

dput(df) structure(list(Species = c("australian", "australian", "brown", "brown", "brown", "brown", "dalmatian", "dalmatian", "dalmatian", "dalmatian", "dalmatian", "dalmatian", "dalmatian"), Age = c(2.6, 2.3, 2.3, 2.3, 3.4, 3.4, 5.1, 4.4, 4.4, 4.1, 4.2, 4.7, 5.5)), class = "data.frame", row.names = c(NA, -13L))
</code>```

Thank you Pedro for the help.

Thank you for any help you can provide.

M.

答:
Welcome Michelle! The tapply function works with two main objets (these objects need to be vectors), called X and INDEX. What the error messages is telling you, is that X and INDEX does not have the same length.

The example below, reproduces the same error that you are facing. See that the X object have 4 elements, but INDEX have only 2.

```<code>tapply(X = c(5, 6, 7, 8), INDEX = c(1, 2), mean)
</code>```

This means that, to fix your error, the first and second objects that you pass to tapply(), need to have the same length. In your example, these two objects are df$Species and df$Age. You can confirm if df$Species and df$Age does not have the same length, by comparing the result of length(df$Species) and length(df$Age). If they are equal, then, these two vectors have the same length. But, if they are not equal, then these two vectors have different lengths.

What is probably going wrong in your code, is that the read.csv() function is not correctly reading your CSV file. Maybe df was transformed to a list, and not a data.frame. We cannot give better help than this for you, because we do not know what the df object is, or, how it is structured in your R session.

You could give these useful information for us, by copying and pasting the result of str(df) command, or, dput(df). Both of these commandos would give us enough information to probably point out exactly what you need to do. So, next time, when you post a question, is good idea to include these infos.

Anyway, when I copy and paste the CSV file that you passed, and try to run your code, everything works fine. So, again, your df object is probably not structured as you expected, probably because of some problem at the read.csv() function.

```<code>text <- "
Species, Age
australian, 2.6
australian, 2.3
brown, 2.3
brown, 2.3
brown, 3.4
brown, 3.4
dalmatian, 5.1
dalmatian, 4.4
dalmatian, 4.4
dalmatian, 4.1
dalmatian, 4.2
dalmatian, 4.7
dalmatian, 5.5"

data <- readr::read_csv(text)
tapply(data$Age, data$Species, mean)
</code>```

Result:

```<code>australian      brown  dalmatian
  2.450000   2.850000   4.628571
</code>```

Body:
In the following CSV file:

Species, Age
australian, 2.6
australian, 2.3
brown, 2.3
brown, 2.3
brown, 3.4
brown, 3.4
dalmatian, 5.1
dalmatian, 4.4
dalmatian, 4.4
dalmatian, 4.1
dalmatian, 4.2
dalmatian, 4.7
dalmatian, 5.5

I am attempting to calculate the mean for the Pelican species, but R is displaying an error about unequal lengths.

df <- read.csv('c:/Users/Michelle/Downloads/pelican.csv')
tapply(df$Species, df$Age, mean)

Error in tapply(df$Species, df$Age, mean) :
arguments must have same length

I assumed the tapply function would output each pelican species with the mean age of each.
Unfortunately, the director at the University of Florida is insisting I use base R functions.

Edit 1:

str(df) 'data.frame': 13 obs. of 2 variables: $ Species: chr "australian" "australian" "brown" "brown" ... $ Age : num 2.6 2.3 2.3 2.3 3.4 3.4 5.1 4.4 4.4 4.1 ...

dput(df) structure(list(Species = c("australian", "australian", "brown", "brown", "brown", "brown", "dalmatian", "dalmatian", "dalmatian", "dalmatian", "dalmatian", "dalmatian", "dalmatian"), Age = c(2.6, 2.3, 2.3, 2.3, 3.4, 3.4, 5.1, 4.4, 4.4, 4.1, 4.2, 4.7, 5.5)), class = "data.frame", row.names = c(NA, -13L))

Thank you Pedro for the help.

Thank you for any help you can provide.

M.

Body:
Welcome Michelle! The tapply function works with two main objets (these objects need to be vectors), called X and INDEX. What the error messages is telling you, is that X and INDEX does not have the same length.

The example below, reproduces the same error that you are facing. See that the X object have 4 elements, but INDEX have only 2.

tapply(X = c(5, 6, 7, 8), INDEX = c(1, 2), mean)

This means that, to fix your error, the first and second objects that you pass to tapply(), need to have the same length. In your example, these two objects are df$Species and df$Age. You can confirm if df$Species and df$Age does not have the same length, by comparing the result of length(df$Species) and length(df$Age). If they are equal, then, these two vectors have the same length. But, if they are not equal, then these two vectors have different lengths.

What is probably going wrong in your code, is that the read.csv() function is not correctly reading your CSV file. Maybe df was transformed to a list, and not a data.frame. We cannot give better help than this for you, because we do not know what the df object is, or, how it is structured in your R session.

You could give these useful information for us, by copying and pasting the result of str(df) command, or, dput(df). Both of these commandos would give us enough information to probably point out exactly what you need to do. So, next time, when you post a question, is good idea to include these infos.

Anyway, when I copy and paste the CSV file that you passed, and try to run your code, everything works fine. So, again, your df object is probably not structured as you expected, probably because of some problem at the read.csv() function.

text <- "
Species, Age
australian, 2.6
australian, 2.3
brown, 2.3
brown, 2.3
brown, 3.4
brown, 3.4
dalmatian, 5.1
dalmatian, 4.4
dalmatian, 4.4
dalmatian, 4.1
dalmatian, 4.2
dalmatian, 4.7
dalmatian, 5.5"

data <- readr::read_csv(text)
tapply(data$Age, data$Species, mean)

Result:

australian      brown  dalmatian
  2.450000   2.850000   4.628571