问:
Having an issue getting vaues to onClickHandler Due to MUI
So I want to get a category navigation which contains icons and labels.
I've tried with Chips:

```<code>                 {categories.map((category) => (
                    <Chip
                        key={category._id}
                        avatar={<Avatar alt={category.name} src={category.icon} />}
                        label={category.name}
                        variant="outlined"
                        onClick={(e) => handleClick(e)}
                        value={category._id}
                    />
                ))}
</code>```

Ive tried using Tabs -> Tab. But they don't produce a "value" when i

```<code>const handleClick = (e) => {

    const valueTargeting= e.target.value;
    console.log(valueTargeting);
};
</code>```

Is there a way to use any of these, or do I have to resort to designing a button?
Also notice they do output a "value" when clicked at a certain area(which is small surface area). Is that a bug on my part?

答:
Chip is not returning the expected value is because the Chip does not explicitly maintain a value.  In order for it to return a value to your event handler, you'll need to wrap the value that you want it to return in the onClick handler itself.  For example:

```<code>{categories.map((category) => {
  return (
    <Chip
      label={category.name}
      // Notice 'category._id' being sent from the handler, not `e`
      onClick={handleClick(category._id})}
    />
  );
})}
</code>```

Working MUI 4 Code Sandbox: https://codesandbox.io/s/chip-click-mui4-ggl0z?file=/demo.js:940-1325

Working MUI 5 Code Sandbox: https://codesandbox.io/s/chip-click-mui5-y5xkk?file=/demo.js

Body:
So I want to get a category navigation which contains icons and labels.
I've tried with Chips:

                 {categories.map((category) => (
                    <Chip
                        key={category._id}
                        avatar={<Avatar alt={category.name} src={category.icon} />}
                        label={category.name}
                        variant="outlined"
                        onClick={(e) => handleClick(e)}
                        value={category._id}
                    />
                ))}

Ive tried using Tabs -> Tab. But they don't produce a "value" when i

const handleClick = (e) => {

    const valueTargeting= e.target.value;
    console.log(valueTargeting);
};

Is there a way to use any of these, or do I have to resort to designing a button?
Also notice they do output a "value" when clicked at a certain area(which is small surface area). Is that a bug on my part?

Body:
Chip is not returning the expected value is because the Chip does not explicitly maintain a value.  In order for it to return a value to your event handler, you'll need to wrap the value that you want it to return in the onClick handler itself.  For example:

{categories.map((category) => {
  return (
    <Chip
      label={category.name}
      // Notice 'category._id' being sent from the handler, not `e`
      onClick={handleClick(category._id})}
    />
  );
})}

Working MUI 4 Code Sandbox: https://codesandbox.io/s/chip-click-mui4-ggl0z?file=/demo.js:940-1325

Working MUI 5 Code Sandbox: https://codesandbox.io/s/chip-click-mui5-y5xkk?file=/demo.js


来源: stackexchange

问:
React-Hook Form: Cannot read properties of undefined (reading 'field')
My form is a nested one and if I'll only submit one product, there are no errors, But If I'll click Add More Product and click the button to add more colors this is the error that I'm getting:

```<code>Cannot read properties of undefined (reading 'field')
</code>```

This is where it pointed out:

```<code><input
  36 |   name={`test[${nestIndex}].nestedArray[${k}].color`}
  37 |   ref={register({ required: true })}
> 38 |   defaultValue={item.field}
     |                     ^
  39 |   style={{ marginRight: "25px" }}
  40 | />
</code>```

and here:

```<code>return (
  19 |   <div>
> 20 |     {fields.map((item, k) => {
     |            ^
  21 |       return (
  22 |         <div key={item.id} style={{ marginLeft: 20 }}>
  23 |           <label>{k + 1}</label>
</code>```

Adding more products, and adding more colors will make these errors appear

This is what the form looks like:

Codesandbox link:  https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

The error is in the fieldArray.js:

i

```<code>mport React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].nestedArray[${index}].product`}
                inputRef={register({ required: true })}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}
</code>```

How can I fix this?

答:
Here are the couple of things that I have found.

in fieldArray.js file add item.product instead of item.name

```<code><TextField
   name={`test[${index}].product`}
   inputRef={register({ required: true })}
   defaultValue={item.product}
/>
</code>```

in nestedFieldArray.js add refer and defaultValue in Size component and remove field1 from name and add size

```<code><Size
    name={`test[${nestIndex}].nestedArray[${k}].size`}
    menuItems={menuItems}
    refer={register({ required: true })}
    defaultValue={item.size}
    control={control}
/>
</code>```

in Size.js file first import React from 'react'; then add defautlValue in props

```<code>const Size = ({ name, menuItems, defaultValue, control }) => (
   <Controller
       as={
           <Select>
               {menuItems.map(({ value, label }, index) => (
                   <MenuItem key={index} value={value}>
                       {label}
                   </MenuItem>
               ))}
           </Select>
       }
       name={name}
       control={control}
       defaultValue={defaultValue}
       rules={{ required: true }}
       fullWidth
   />
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My form is a nested one and if I'll only submit one product, there are no errors, But If I'll click Add More Product and click the button to add more colors this is the error that I'm getting:

Cannot read properties of undefined (reading 'field')

This is where it pointed out:

<input
  36 |   name={`test[${nestIndex}].nestedArray[${k}].color`}
  37 |   ref={register({ required: true })}
> 38 |   defaultValue={item.field}
     |                     ^
  39 |   style={{ marginRight: "25px" }}
  40 | />

and here:

return (
  19 |

> 20 |     {fields.map((item, k) => {
     |            ^
  21 |       return (
  22 |

  23 |           {k + 1}

Adding more products, and adding more colors will make these errors appear

This is what the form looks like:

Codesandbox link:  https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

The error is in the fieldArray.js:

i

mport React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>

        {fields.map((item, index) => {
          return (

              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].nestedArray[${index}].product`}
                inputRef={register({ required: true })}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />

          );
        })}

        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>

      Render Count: {renderCount}
    </>
  );
}

How can I fix this?

Body:
Here are the couple of things that I have found.

in fieldArray.js file add item.product instead of item.name

<TextField
   name={`test[${index}].product`}
   inputRef={register({ required: true })}
   defaultValue={item.product}
/>

in nestedFieldArray.js add refer and defaultValue in Size component and remove field1 from name and add size

<Size
    name={`test[${nestIndex}].nestedArray[${k}].size`}
    menuItems={menuItems}
    refer={register({ required: true })}
    defaultValue={item.size}
    control={control}
/>

in Size.js file first import React from 'react'; then add defautlValue in props

const Size = ({ name, menuItems, defaultValue, control }) => (
   <Controller
       as={
           <Select>
               {menuItems.map(({ value, label }, index) => (
                   <MenuItem key={index} value={value}>
                       {label}
                   </MenuItem>
               ))}
           </Select>
       }
       name={name}
       control={control}
       defaultValue={defaultValue}
       rules={{ required: true }}
       fullWidth
   />
);


问:
How do I get a parent div to resize when the children do?
I'm running into this problem with a program I'm working on and I can't figure out the solution. Basically I have a webapp, on initial render the entire page is height X. There is a background color, and that color covers the full height of the page.

Moments after the initial render, data is fetched asynchronously and added to the page. The data causes the total height of the page to get larger. Unfortunately, only the original height of the page shows the background color, below that the background becomes white.

On further investigation, I've discovered this is due to a parent div not resizing when the child div does. Basically, the div getting elements added to it by the asynchronous data loading grows in height, but the parent wrapping around it (and the one that has the background color) does not.

During my investigation, I have found a partial solution: set the "height" to "auto". The problem with this solution is when the page initially loads, the background color is only applied to the part of the page with actual content, rather than filling the screen. So if I have the height at "auto", the color is screwed up when the page first loads before correcting itself after the items are added, and if the height is "100%" then the color is screwed up after the items are added.

I've put together a barebones HTML file that re-creates the issue:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>
</code>```

答: You could use height: fit-content; and width: fit-content; on the parent element

Body:
I'm running into this problem with a program I'm working on and I can't figure out the solution. Basically I have a webapp, on initial render the entire page is height X. There is a background color, and that color covers the full height of the page.

Moments after the initial render, data is fetched asynchronously and added to the page. The data causes the total height of the page to get larger. Unfortunately, only the original height of the page shows the background color, below that the background becomes white.

On further investigation, I've discovered this is due to a parent div not resizing when the child div does. Basically, the div getting elements added to it by the asynchronous data loading grows in height, but the parent wrapping around it (and the one that has the background color) does not.

During my investigation, I have found a partial solution: set the "height" to "auto". The problem with this solution is when the page initially loads, the background color is only applied to the part of the page with actual content, rather than filling the screen. So if I have the height at "auto", the color is screwed up when the page first loads before correcting itself after the items are added, and if the height is "100%" then the color is screwed up after the items are added.

I've put together a barebones HTML file that re-creates the issue:

<!DOCTYPE html>

    <title>Layout Test</title>

Layout Test


问:
Why nested virtualization for the Android emulator is very very slow?
Nested KVM virtualization should have a small overhead, but an Android emulator inside a VM should be usable.

When I launch the Android emulator inside ubuntu 20.04 guest (on ubuntu 20.04 host), it warns me that I'm on a nested virtualization and thus it will be slow. But it's painfully low, not just slow. It takes 10 minutes to boot into Android and yes, all the systems are x86_64, even the android image.

I thought this had to do with OpenGL so I enabled OpenGL virtualization on my virt-manager and thigns are still slow.

I tried the same thing on my Ryzen 7 2700x which has 16 cores, I gave all cores to the VM and passed an AMD gpu to it, and Android emulator is also painfully slow.

Why?

答: The problem is with QXL. Somehow it's slow on the new Ubuntu. Use VirtIO video and possibly 3D acceleration</p>


问:
Python: How to access property from another file ? from file name import class didn't work
I am new in Python programming. I have property consist of getter and setter in a class in file A.

```<code>class Histogram:
    def getHue(self):
        return self.value

    def setHue(self, value):
        self.varHueHist = value

    HueHist = property(getHue, setHue)
</code>```

I want to access the property from another class in another file which is file B. But after I import the file A and the class inside the file B, the property still can not be accessed.

```<code>from Histogram import Histogram

class moment:
   var = Histogram()
</code>```

The property cannot be accessed. When i tried to use automatic completing (Ctrl+space) in my Spyder, the property also didn't show. Unfortunately, when i tried to access the property inside class in the same file with the property, the property is readable.
How to call property from inside class in another file?

Both of the files are already in the same folder.
Please help. Thanks

答:
What you trying to do is achieved using descriptors. You can see more here:

https://docs.python.org/3/howto/descriptor.html

So your code should looks like this:

```<code>class Histogram:

  def __set_name__(self, owner, name):
     self.public_name = name
     self.private_name = '_' + name

  def __get__(self, obj, objtype=None):
     return getattr(obj, self.private_name)

  def __set__(self, obj, value):
     setattr(obj, self.private_name, value)
</code>```

Now you can call it, and it will work as a descriptor setting and getting accordingly.

```<code>import Histogram

class Moment:
    var = Histogram()
</code>```

Also files being in same folders does not means the imports will work. You should create a init.py empty file inside the folder and then do

```<code>from folder.file import class_name
</code>```

Or you  can add the folder to the path:

```<code>import sys
sys.path.extend(['complete_path_to_the_folder_where_code_is'])
</code>```

Body:
I am new in Python programming. I have property consist of getter and setter in a class in file A.

class Histogram:
    def getHue(self):
        return self.value

    def setHue(self, value):
        self.varHueHist = value

    HueHist = property(getHue, setHue)

I want to access the property from another class in another file which is file B. But after I import the file A and the class inside the file B, the property still can not be accessed.

from Histogram import Histogram

class moment:
   var = Histogram()

The property cannot be accessed. When i tried to use automatic completing (Ctrl+space) in my Spyder, the property also didn't show. Unfortunately, when i tried to access the property inside class in the same file with the property, the property is readable.
How to call property from inside class in another file?

Both of the files are already in the same folder.
Please help. Thanks

Body:
What you trying to do is achieved using descriptors. You can see more here:

https://docs.python.org/3/howto/descriptor.html

So your code should looks like this:

class Histogram:

  def __set_name__(self, owner, name):
     self.public_name = name
     self.private_name = '_' + name

  def __get__(self, obj, objtype=None):
     return getattr(obj, self.private_name)

  def __set__(self, obj, value):
     setattr(obj, self.private_name, value)

Now you can call it, and it will work as a descriptor setting and getting accordingly.

import Histogram

class Moment:
    var = Histogram()

Also files being in same folders does not means the imports will work. You should create a init.py empty file inside the folder and then do

from folder.file import class_name

Or you  can add the folder to the path:

import sys
sys.path.extend(['complete_path_to_the_folder_where_code_is'])


问:
SQL query: choosing only the first word in a column
I am using PostgreSQL and Windows.

I have column data that looks like this:

Table name: employees

I need to run an SQL query where the result will:

Display only FullName column.

Display ONLY THE FIRST WORD of each name in the column.

What would be the SQL query?

答:
There are all sorts of string functions described here String operators/functions. One that would work is:</p>
```<code>select split_part('Adrian Klaver', ' ', 1);
 split_part
------------
 Adrian

--So in your case
Select split_part("FullName", ' ', 1) from employees;
</code>```

Body:
There are all sorts of string functions described here String operators/functions. One that would work is:

select split_part('Adrian Klaver', ' ', 1);
 split_part
------------
 Adrian

--So in your case
Select split_part("FullName", ' ', 1) from employees;


问:
How to assert unauthenticated?
In my controller constructor I have middleware auth. How do I assert that somebody is not authenticated in tests? Right now I'm getting Illuminate\Auth\AuthenticationException and the only way to make test positive is to add

```<code>$this->expectException('Illuminate\Auth\AuthenticationException')
</code>```

in the beginning. I saw solutions like using withoutExceptionHandling() in the beginning of test or using assertUnauthorized() but that doesn't change anything.

Is there a better way?

I'm using Laravel 7.2.2 and PHPUnit 8.5.

答:
In Laravel, you can use the auth() helper method to get the currently authenticated user as below. If no authenticated user is found, it will return null. And this is what you can assert to check for unauthenticated.

```<code>$this->assertNull(auth()->user());
</code>```

I believe this will also work:

```<code>$this->assertFalse(auth()->check());
</code>```

Title: How to assert unauthenticated?

Body:
In my controller constructor I have middleware auth. How do I assert that somebody is not authenticated in tests? Right now I'm getting Illuminate\Auth\AuthenticationException and the only way to make test positive is to add

$this->expectException('Illuminate\Auth\AuthenticationException')

in the beginning. I saw solutions like using withoutExceptionHandling() in the beginning of test or using assertUnauthorized() but that doesn't change anything.

Is there a better way?

I'm using Laravel 7.2.2 and PHPUnit 8.5.

Body:
In Laravel, you can use the auth() helper method to get the currently authenticated user as below. If no authenticated user is found, it will return null. And this is what you can assert to check for unauthenticated.

$this->assertNull(auth()->user());

I believe this will also work:

$this->assertFalse(auth()->check());


问:
Installing Docker Desktop 4.5.0 failed: Componet.CommunityInstaller.EnableFeaturesAction failed: Not found
On Windows 10, Version 2004 (OS build 19041.1415)
I am trying to install docker desktop 4.5.0 after having installed WSL2 for Ubuntu. I tried repeatedly after a fresh reboot but this problem doesnt go away. Can anyone shed some light?

```<code>Component CommunityInstaller.EnableFeaturesAction failed: Not found
   at CommunityInstaller.InstallWorkflow.<DoHandleD4WPackageAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CommunityInstaller.InstallWorkflow.<DoProcessAsync>d__24.MoveNext()
</code>```

Full log:

```<code>OS: Windows 10 Enterprise
Edition: Enterprise
Id: 2004
Build: 19041
BuildLabName: 19041.1.amd64fre.vb_release.191206-1406
File: C:\Users\naus-ad-xxx\AppData\Local\Docker\install-log.txt
CommandLine: "C:\Users\xxx\Downloads\Docker Desktop Installer(1).exe" "install" -package "res:DockerDesktop" --relaunch-as-admin
You can send feedback, including this log file, at https://github.com/docker/for-win/issues
[11:23:53.421][ManifestAndExistingInstallationLoader][Info   ] No install path specified, looking for default installation registry key
[11:23:53.421][Program           ][Info   ] No installation found
[11:23:53.784][InstallWorkflow   ][Info   ] Cancel pending background download
[11:23:53.822][BackgroundTransfer][Info   ] Cancel current background transfer job
[11:23:54.856][InstallWorkflow   ][Info   ] Using package: res:DockerDesktop
[11:23:54.856][InstallWorkflow   ][Info   ] Downloading
[11:23:57.240][InstallWorkflow   ][Info   ] Extracting manifest
Failed to track the installer started event[11:23:57.643][InstallWorkflow   ][Info   ] Manifest found: version=74594, displayVersion=4.5.0, channelUrl=https://desktop.docker.com/win/main/amd64/appcast.xml
[11:23:57.643][InstallWorkflow   ][Info   ] Checking prerequisites
[11:23:57.666][InstallWorkflow   ][Info   ] Prompting for optional features
[11:23:59.863][InstallWorkflow   ][Info   ] Unpacking artifacts
[11:26:07.556][InstallWorkflow   ][Info   ] Deploying component CommunityInstaller.CreateGroupAction
[11:26:10.120][InstallWorkflow   ][Info   ] Deploying component CommunityInstaller.AddToGroupAction
[11:26:10.130][InstallWorkflow   ][Info   ] Deploying component CommunityInstaller.EnableFeaturesAction
**[11:26:10.181][InstallWorkflow   ][Error  ] Installation failed
Exception type: System.Exception, Exception message: Component CommunityInstaller.EnableFeaturesAction failed: Not found , StackTrace:
   at CommunityInstaller.InstallWorkflow.<DoHandleD4WPackageAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CommunityInstaller.InstallWorkflow.<DoProcessAsync>d__24.MoveNext()**
[11:26:10.185][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.AddToGroupAction
[11:26:10.186][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.CreateGroupAction
[11:26:10.186][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.UnpackArtifactsStep
[11:26:10.194][FileSystem        ][Info   ] Deleting C:\Program Files\Docker\Docker
[11:26:10.761][FileSystem        ][Info   ] Deleted C:\Program Files\Docker\Docker successfully
[11:26:10.761][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.ExtractManifestStep
[11:26:10.764][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.DownloadStep

</code>```

答:
I had the same issue too, when installing the latest version 4.5.0 (It had been released on Feb 10th, 2022) Try to downgrade to version 4.4.4 it worked for me.

You can find the released note and older versions on this Docker for Windows

Note: You can install an older version and update to latest version 4.5.0

Body:
On Windows 10, Version 2004 (OS build 19041.1415)
I am trying to install docker desktop 4.5.0 after having installed WSL2 for Ubuntu. I tried repeatedly after a fresh reboot but this problem doesnt go away. Can anyone shed some light?

Component CommunityInstaller.EnableFeaturesAction failed: Not found
   at CommunityInstaller.InstallWorkflow.<DoHandleD4WPackageAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CommunityInstaller.InstallWorkflow.<DoProcessAsync>d__24.MoveNext()

Full log:

OS: Windows 10 Enterprise
Edition: Enterprise
Id: 2004
Build: 19041
BuildLabName: 19041.1.amd64fre.vb_release.191206-1406
File: C:\Users\naus-ad-xxx\AppData\Local\Docker\install-log.txt
CommandLine: "C:\Users\xxx\Downloads\Docker Desktop Installer(1).exe" "install" -package "res:DockerDesktop" --relaunch-as-admin
You can send feedback, including this log file, at https://github.com/docker/for-win/issues
[11:23:53.421][ManifestAndExistingInstallationLoader][Info   ] No install path specified, looking for default installation registry key
[11:23:53.421][Program           ][Info   ] No installation found
[11:23:53.784][InstallWorkflow   ][Info   ] Cancel pending background download
[11:23:53.822][BackgroundTransfer][Info   ] Cancel current background transfer job
[11:23:54.856][InstallWorkflow   ][Info   ] Using package: res:DockerDesktop
[11:23:54.856][InstallWorkflow   ][Info   ] Downloading
[11:23:57.240][InstallWorkflow   ][Info   ] Extracting manifest
Failed to track the installer started event[11:23:57.643][InstallWorkflow   ][Info   ] Manifest found: version=74594, displayVersion=4.5.0, channelUrl=https://desktop.docker.com/win/main/amd64/appcast.xml
[11:23:57.643][InstallWorkflow   ][Info   ] Checking prerequisites
[11:23:57.666][InstallWorkflow   ][Info   ] Prompting for optional features
[11:23:59.863][InstallWorkflow   ][Info   ] Unpacking artifacts
[11:26:07.556][InstallWorkflow   ][Info   ] Deploying component CommunityInstaller.CreateGroupAction
[11:26:10.120][InstallWorkflow   ][Info   ] Deploying component CommunityInstaller.AddToGroupAction
[11:26:10.130][InstallWorkflow   ][Info   ] Deploying component CommunityInstaller.EnableFeaturesAction
**[11:26:10.181][InstallWorkflow   ][Error  ] Installation failed
Exception type: System.Exception, Exception message: Component CommunityInstaller.EnableFeaturesAction failed: Not found , StackTrace:
   at CommunityInstaller.InstallWorkflow.<DoHandleD4WPackageAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CommunityInstaller.InstallWorkflow.<DoProcessAsync>d__24.MoveNext()**
[11:26:10.185][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.AddToGroupAction
[11:26:10.186][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.CreateGroupAction
[11:26:10.186][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.UnpackArtifactsStep
[11:26:10.194][FileSystem        ][Info   ] Deleting C:\Program Files\Docker\Docker
[11:26:10.761][FileSystem        ][Info   ] Deleted C:\Program Files\Docker\Docker successfully
[11:26:10.761][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.ExtractManifestStep
[11:26:10.764][InstallWorkflow   ][Info   ] Rollbacking component CommunityInstaller.DownloadStep


问:
Read in command line arguments for folder paths and integer values
The goal of this program is to:

Take in 2 Folder paths

Take in 1 Integer Value

Validate both Folders are in the directory and that the Integer value is an int

Move a specified number of files from the source folder into the destination folder. For example, if the source folder contains 8 files I want to move the last 4 files to the destination folder.

In Command line: python main.py path1 path2 4

I'm in the testing phase of using Command line arguments instead of default value placeholders (Folder paths and integer values assigned to variables) and running through the console.

My issue is:

Everything work as intended when path1, path2, and int are all present and correct values

If the integer is not an int (Example, python main.py path1 path2 string) the program crashes and gives me errors.

If the program reads that the CLI arg is not an int (num = int(sys.argv[3])) I want to default the value to 10, but the program does not seem to do this?

ERROR

Blank = block out personal info

python main.py Path1 Path2 L

```<code>Traceback (most recent call last):
  File "C:\Users\blank\blank\blank\main.py", line 71, in <module>
    main()
  File "C:\Users\blank\blank\blank\main.py", line 66, in main
    read_args()
  File "C:\Users\blank\blank\blank\main.py", line 29, in read_args
    num = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 'L'
</code>```

Main

```<code>import os, sys, shutil, time

def main():
    read_args()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        exit()
</code>```

Code

```<code>def validate_folder(folder):
    """Validates folders in working directory"""
    try:
        isDir = os.path.isdir(folder)
        return isDir
    except Exception as e:
        print(e)
        return None

def validate_number(number1):
    """Validates third argument is an integer value"""
    try:
        int(number1)
        return True
    except ValueError:
        return False

def read_args():
    """Read CLI arguments"""
    source_folder = sys.argv[1]
    destination_folder = sys.argv[2]
    num = int(sys.argv[3])

    """Get main folder and archive folder and validate they are in the directory"""
    main_folder = validate_folder(source_folder)
    archive_folder = validate_folder(destination_folder)
    kept_files = validate_number(num)

    """If any of the inputs is not valid return None proceed with conditional checks"""
    if main_folder is False or archive_folder is False:
        print("Folders cannot be found")
    if main_folder is True and archive_folder is True and kept_files is False:
        num = 10
        sortFiles_and_moveFiles(source_folder, destination_folder, num)
    else:
        """If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
        sortFiles_and_moveFiles(source_folder, destination_folder, num)

def sortFiles_and_moveFiles(path1, path2, n_files):
    source_folder = path1
    destination_folder = path2
    """Get list of all files only in the given directory"""
    list_of_files = filter(lambda x: os.path.isfile(os.path.join(source_folder, x)), os.listdir(source_folder))

    """Sort list of files based on last modification time in descending order"""
    list_of_files = sorted(list_of_files, key=lambda x: os.path.getmtime(os.path.join(source_folder, x)))

    """Iterate over sorted list of files and print file path, along with last modification time of file"""
    for file_name in list_of_files:
        file_path = os.path.join(source_folder, file_name)
        timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))
        print(timestamp_str, ' -->', file_name)
    print("Designated files have been moved")

    """Move designated number of files to archive folder using slice notation."""
    for file_name in list_of_files[n_files:]:
        shutil.move(os.path.join(source_folder, file_name), destination_folder)
</code>```

答:
There is builtin function str.isdigit() that returns True if string could be casted to int else False. Also some of your if checks can be shortened

```<code>if main_folder is True and archive_folder is True and kept_files is False:
</code>```

could be replaced with simple

```<code>elif kept_files is False:
</code>```

But the whole method still can be modified as follows

```<code>def read_args():
    """Read CLI arguments"""
    source_folder = sys.argv[1]
    destination_folder = sys.argv[2]
    num = sys.argv[3]

    """Get main folder and archive folder and validate they are in the directory"""
    main_folder = validate_folder(source_folder)
    archive_folder = validate_folder(destination_folder)

    """If any of the inputs is not valid return None proceed with conditional checks"""
    if main_folder is False or archive_folder is False:
        print("Folders cannot be found")
    elif not num.isdigit():
        num = 10

    else:
        """If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
        num = int(num)
    sortFiles_and_moveFiles(source_folder, destination_folder, num)
</code>```

Body:
The goal of this program is to:

Take in 2 Folder paths

Take in 1 Integer Value

Validate both Folders are in the directory and that the Integer value is an int

Move a specified number of files from the source folder into the destination folder. For example, if the source folder contains 8 files I want to move the last 4 files to the destination folder.

In Command line: python main.py path1 path2 4

I'm in the testing phase of using Command line arguments instead of default value placeholders (Folder paths and integer values assigned to variables) and running through the console.

My issue is:

Everything work as intended when path1, path2, and int are all present and correct values

If the integer is not an int (Example, python main.py path1 path2 string) the program crashes and gives me errors.

If the program reads that the CLI arg is not an int (num = int(sys.argv[3])) I want to default the value to 10, but the program does not seem to do this?

ERROR

Blank = block out personal info

python main.py Path1 Path2 L

Traceback (most recent call last):
  File "C:\Users\blank\blank\blank\main.py", line 71, in <module>
    main()
  File "C:\Users\blank\blank\blank\main.py", line 66, in main
    read_args()
  File "C:\Users\blank\blank\blank\main.py", line 29, in read_args
    num = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 'L'

Main

import os, sys, shutil, time

def main():
    read_args()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        exit()

Code

def validate_folder(folder):
    """Validates folders in working directory"""
    try:
        isDir = os.path.isdir(folder)
        return isDir
    except Exception as e:
        print(e)
        return None

def validate_number(number1):
    """Validates third argument is an integer value"""
    try:
        int(number1)
        return True
    except ValueError:
        return False

def read_args():
    """Read CLI arguments"""
    source_folder = sys.argv[1]
    destination_folder = sys.argv[2]
    num = int(sys.argv[3])

    """Get main folder and archive folder and validate they are in the directory"""
    main_folder = validate_folder(source_folder)
    archive_folder = validate_folder(destination_folder)
    kept_files = validate_number(num)

    """If any of the inputs is not valid return None proceed with conditional checks"""
    if main_folder is False or archive_folder is False:
        print("Folders cannot be found")
    if main_folder is True and archive_folder is True and kept_files is False:
        num = 10
        sortFiles_and_moveFiles(source_folder, destination_folder, num)
    else:
        """If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
        sortFiles_and_moveFiles(source_folder, destination_folder, num)

def sortFiles_and_moveFiles(path1, path2, n_files):
    source_folder = path1
    destination_folder = path2
    """Get list of all files only in the given directory"""
    list_of_files = filter(lambda x: os.path.isfile(os.path.join(source_folder, x)), os.listdir(source_folder))

    """Sort list of files based on last modification time in descending order"""
    list_of_files = sorted(list_of_files, key=lambda x: os.path.getmtime(os.path.join(source_folder, x)))

    """Iterate over sorted list of files and print file path, along with last modification time of file"""
    for file_name in list_of_files:
        file_path = os.path.join(source_folder, file_name)
        timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))
        print(timestamp_str, ' -->', file_name)
    print("Designated files have been moved")

    """Move designated number of files to archive folder using slice notation."""
    for file_name in list_of_files[n_files:]:
        shutil.move(os.path.join(source_folder, file_name), destination_folder)

Body:
There is builtin function str.isdigit() that returns True if string could be casted to int else False. Also some of your if checks can be shortened

if main_folder is True and archive_folder is True and kept_files is False:

could be replaced with simple

elif kept_files is False:

But the whole method still can be modified as follows

def read_args():
    """Read CLI arguments"""
    source_folder = sys.argv[1]
    destination_folder = sys.argv[2]
    num = sys.argv[3]

    """Get main folder and archive folder and validate they are in the directory"""
    main_folder = validate_folder(source_folder)
    archive_folder = validate_folder(destination_folder)

    """If any of the inputs is not valid return None proceed with conditional checks"""
    if main_folder is False or archive_folder is False:
        print("Folders cannot be found")
    elif not num.isdigit():
        num = 10

    else:
        """If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
        num = int(num)
    sortFiles_and_moveFiles(source_folder, destination_folder, num)


问:
How to compare a local Git branch with its remote branch
How can I see the diff between a local branch and a remote branch?

答:
I kept seeing this error

```<code>git diff main origin/master
fatal: ambiguous argument 'main': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

Solution: I had to git push first (since both the remote and local need to be up to date), and then this worked:

git diff master origin/master
```

Body:
I kept seeing this error

git diff main origin/master
fatal: ambiguous argument 'main': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Solution: I had to git push first (since both the remote and local need to be up to date), and then this worked:

git diff master origin/master


问:
How to be notified at the END of Horizontal Scrolling in TListView?
In a VCL Application, I am trying to be notified when I END the horizontal scrolling in a TListView with this interposer class code:

```<code>type
  TListView = class(Vcl.ComCtrls.TListView)
  private
    procedure WMNotify(var AMessage: TWMNotify); message WM_NOTIFY; // used for other purposes
    procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
    procedure WMVScroll(var Msg: TWMHScroll); message WM_VSCROLL;
    procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;
  protected
    procedure CreateWnd; override;
  end;

implementation

procedure TListView.CNCommand(var Message: TWMCommand);
begin
   case Message.NotifyCode of
    EN_VSCROLL: CodeSite.Send('TListView.CNCommand: EN_VSCROLL'); // does not work
    EN_HSCROLL: CodeSite.Send('TListView.CNCommand: EN_HSCROLL'); // does not work
   end;
   inherited ;
end;

procedure TListView.WMHScroll(var Msg: TWMHScroll);
begin
   CodeSite.Send('TListView.WMHScroll: WM_HSCROLL'); // does work
   inherited;
end;

procedure TListView.WMVScroll(var Msg: TWMHScroll);
begin
   CodeSite.Send('TListView.WMVScroll: WM_VSCROLL'); // does work
   inherited;
end;
</code>```

However, only WHILE scrolling I get constantly notified by WM_HSCROLL and WM_VSCROLL generating a lot of messages.

But I need to be notified only at the END of the horizontal scrolling! Is this possible?

答:
The comments given to the Q are very relevant.

First, as Remy Lebeau stated, the WM_HSCROLL message tells you if the operation is done:

procedure TListView.WMHScroll(var Msg: TWMHScroll);
begin
  inherited;
  if Msg.ScrollCode = SB_ENDSCROLL then
    ShowMessage('End scroll')
end;
```
<p>However, this <em>only</em> lets you know when a scrolling operation <em>initiated by the horizontal scroll bar</em> is done. Currently, this includes these scroll-bar operations:</p>
<ul>
<li>Thumb released</li>
<li>Scroll bar LEFT or RIGHT button clicked</li>
<li>Scroll bar empty area clicked (for page scroll)</li>
<li>Scroll bar context menu item selected</li>
</ul>
<p>But there are many other ways the list view control can be scrolled, which have nothing to do with the scroll bar:</p>
<ul>
<li>Using your mouse's horizontal scrolling wheel (or the standard vertical wheel if there is only a horizontal scroll bar and no vertical one)</li>
<li>Using your keyboard's left and right arrow keys (or Ctrl+Left/Right for page scroll)</li>
<li>With <code>MultiSelect = True</code>, making a selection rectangle with the mouse (start dragging outside any list-view item)</li>
</ul>
<p>Hence, by reacting only to <code>WM_HSCROLL</code>, you will not detect these scrolling events. Almost certainly, you want to react when the scroll position has changed, no matter <em>how</em> it was changed.</p>
<p>And, as AmigoJack wrote, it is not absolutely clear what "end" means (other than when you release the mouse button after having dragging the scroll bar thumb). For instance, if you scroll using your mouse wheel, is the result a single large scroll operation or several small ones? After all, in any case, even thumb tracking, the control repaints itself at every small step.</p>
<p>So probably your best option is to use</p>
<pre class="lang-pascal prettyprint-override"><code>procedure TListView.CNNotify(var Message: TMessage);
begin
  inherited;
  if PNMHDR(Message.lParam).code = LVN_ENDSCROLL then
    // Scrolled
end;
</code>```

According to the documentation,

Notifies a list-view control's parent window when a scrolling operation ends.

Notice that the documentation says that the notification is sent when the operation ends. Still, you will find that it is sent for every small update while you drag the scroll bar thumb. As mentioned above, this is reasonable: scrolling has indeed been performed after every such small step.

Body:
In a VCL Application, I am trying to be notified when I END the horizontal scrolling in a TListView with this interposer class code:

type
  TListView = class(Vcl.ComCtrls.TListView)
  private
    procedure WMNotify(var AMessage: TWMNotify); message WM_NOTIFY; // used for other purposes
    procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
    procedure WMVScroll(var Msg: TWMHScroll); message WM_VSCROLL;
    procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;
  protected
    procedure CreateWnd; override;
  end;

implementation

procedure TListView.CNCommand(var Message: TWMCommand);
begin
   case Message.NotifyCode of
    EN_VSCROLL: CodeSite.Send('TListView.CNCommand: EN_VSCROLL'); // does not work
    EN_HSCROLL: CodeSite.Send('TListView.CNCommand: EN_HSCROLL'); // does not work
   end;
   inherited ;
end;

procedure TListView.WMHScroll(var Msg: TWMHScroll);
begin
   CodeSite.Send('TListView.WMHScroll: WM_HSCROLL'); // does work
   inherited;
end;

procedure TListView.WMVScroll(var Msg: TWMHScroll);
begin
   CodeSite.Send('TListView.WMVScroll: WM_VSCROLL'); // does work
   inherited;
end;

However, only WHILE scrolling I get constantly notified by WM_HSCROLL and WM_VSCROLL generating a lot of messages.

But I need to be notified only at the END of the horizontal scrolling! Is this possible?

Body:
The comments given to the Q are very relevant.

First, as Remy Lebeau stated, the WM_HSCROLL message tells you if the operation is done:

procedure TListView.WMHScroll(var Msg: TWMHScroll);
begin
  inherited;
  if Msg.ScrollCode = SB_ENDSCROLL then
    ShowMessage('End scroll')
end;

However, this only lets you know when a scrolling operation initiated by the horizontal scroll bar is done. Currently, this includes these scroll-bar operations:

Thumb released

Scroll bar LEFT or RIGHT button clicked

Scroll bar empty area clicked (for page scroll)

Scroll bar context menu item selected

But there are many other ways the list view control can be scrolled, which have nothing to do with the scroll bar:

Using your mouse's horizontal scrolling wheel (or the standard vertical wheel if there is only a horizontal scroll bar and no vertical one)

Using your keyboard's left and right arrow keys (or Ctrl+Left/Right for page scroll)

With MultiSelect = True, making a selection rectangle with the mouse (start dragging outside any list-view item)

Hence, by reacting only to WM_HSCROLL, you will not detect these scrolling events. Almost certainly, you want to react when the scroll position has changed, no matter how it was changed.

And, as AmigoJack wrote, it is not absolutely clear what "end" means (other than when you release the mouse button after having dragging the scroll bar thumb). For instance, if you scroll using your mouse wheel, is the result a single large scroll operation or several small ones? After all, in any case, even thumb tracking, the control repaints itself at every small step.

So probably your best option is to use

procedure TListView.CNNotify(var Message: TMessage);
begin
  inherited;
  if PNMHDR(Message.lParam).code = LVN_ENDSCROLL then
    // Scrolled
end;

According to the documentation,

Notifies a list-view control's parent window when a scrolling operation ends.

Notice that the documentation says that the notification is sent when the operation ends. Still, you will find that it is sent for every small update while you drag the scroll bar thumb. As mentioned above, this is reasonable: scrolling has indeed been performed after every such small step.


问:
Android my motionlayout constraints does not react to child views
I wonder if this is possible to modify child of direct view in MotionScene. I have FrameLayout with two views inside and one of them (iv_avatar) I want to make smaller width and height at the end of the animation but my motion scene does not work in terms of this problem (the width and height remain the same at the begining and end of animation).

Here is my code.

activity_account.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:background="?colorToolbarBg"
        android:minHeight="?actionBarSize"
        android:orientation="vertical" />

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/my_drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.motion.widget.MotionLayout
            android:id="@+id/motionLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutDescription="@xml/scene_test">

            <FrameLayout
                android:id="@+id/fl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent">

                <ImageView
                    android:id="@+id/iv_avatar"
                    android:layout_width="75dp"
                    android:layout_height="75dp"
                    android:layout_marginTop="16dp"
                    android:scaleType="centerCrop"
                    app:srcCompat="@mipmap/ic_avatar" />

                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom|right"
                    android:layout_marginLeft="50dp"
                    android:layout_marginTop="65dp"
                    android:alpha="0.6"
                    android:background="@null"
                    android:src="@mipmap/ic_edit" />

            </FrameLayout>

            <TextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="username"
                android:textSize="27sp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/fl" />

            <LinearLayout
                android:id="@+id/ll"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@id/toolbarTitle"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@mipmap/ic_join"
                    android:tint="?colorDayNight" />

                <TextView
                    android:id="@+id/tv_when_joined"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Joined "
                    android:textSize="15sp"
                    android:textStyle="bold" />
            </LinearLayout>

            <View
                android:id="@+id/toolbarDivider"
                android:layout_width="0dp"
                android:layout_height="0.5dp"
                android:layout_marginTop="10dp"
                android:background="@color/toolbar_default_bg_day"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/ll" />

            <androidx.core.widget.NestedScrollView
                android:id="@+id/scrollview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@id/toolbarDivider">

                <RelativeLayout
                    android:id="@+id/rl2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/tv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="abc" />

                    <Button
                        android:id="@+id/b_logout"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/tv"
                        android:layout_centerHorizontal="true"
                        android:text="logout" />
                </RelativeLayout>
            </androidx.core.widget.NestedScrollView>

        </androidx.constraintlayout.motion.widget.MotionLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:itemIconTint="?colorDayNight"
            app:menu="@menu/menu_navigation_drawer" />

    </androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>
</code>```

scene_test.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@id/iv_avatar"
            android:layout_width="20dp"
            android:layout_height="wrap_content"
            android:alpha="1" />
        <Constraint
            android:id="@id/fl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            android:alpha="1" />
        <Constraint
            android:id="@id/tv_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@id/fl"
            android:alpha="1" />
        <Constraint
            android:id="@id/ll"
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:alpha="0" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
            android:id="@id/iv_avatar"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:alpha="1" />
        <Constraint
            android:id="@id/fl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:alpha="1" />
        <Constraint
            android:id="@id/tv_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/fl"
            android:alpha="1" />
        <Constraint
            android:id="@id/ll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/tv_username"
            android:alpha="1" />
    </ConstraintSet>

    <Transition
        app:constraintSetEnd="@id/start"
        app:constraintSetStart="@id/end"
        app:duration="1000">
        <OnSwipe
            app:touchAnchorId="@id/scrollview"
            app:touchAnchorSide="top" />
    </Transition>
</MotionScene>
</code>```

Thank you in advance!

答:
MotionLayout can only manipulate its children. This prevents conflict between the two layouts.
In your case you might be able to have iv_avatar be match_parent and f1 be width = 75dp</p>

Body:
I wonder if this is possible to modify child of direct view in MotionScene. I have FrameLayout with two views inside and one of them (iv_avatar) I want to make smaller width and height at the end of the animation but my motion scene does not work in terms of this problem (the width and height remain the same at the begining and end of animation).

Here is my code.

activity_account.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:background="?colorToolbarBg"
        android:minHeight="?actionBarSize"
        android:orientation="vertical" />

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/my_drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.motion.widget.MotionLayout
            android:id="@+id/motionLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutDescription="@xml/scene_test">

            <FrameLayout
                android:id="@+id/fl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent">

                <ImageView
                    android:id="@+id/iv_avatar"
                    android:layout_width="75dp"
                    android:layout_height="75dp"
                    android:layout_marginTop="16dp"
                    android:scaleType="centerCrop"
                    app:srcCompat="@mipmap/ic_avatar" />

                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom|right"
                    android:layout_marginLeft="50dp"
                    android:layout_marginTop="65dp"
                    android:alpha="0.6"
                    android:background="@null"
                    android:src="@mipmap/ic_edit" />

            </FrameLayout>

            <TextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="username"
                android:textSize="27sp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/fl" />

            <LinearLayout
                android:id="@+id/ll"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@id/toolbarTitle"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@mipmap/ic_join"
                    android:tint="?colorDayNight" />

                <TextView
                    android:id="@+id/tv_when_joined"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Joined "
                    android:textSize="15sp"
                    android:textStyle="bold" />
            </LinearLayout>

            <View
                android:id="@+id/toolbarDivider"
                android:layout_width="0dp"
                android:layout_height="0.5dp"
                android:layout_marginTop="10dp"
                android:background="@color/toolbar_default_bg_day"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/ll" />

            <androidx.core.widget.NestedScrollView
                android:id="@+id/scrollview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@id/toolbarDivider">

                <RelativeLayout
                    android:id="@+id/rl2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/tv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="abc" />

                    <Button
                        android:id="@+id/b_logout"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/tv"
                        android:layout_centerHorizontal="true"
                        android:text="logout" />
                </RelativeLayout>
            </androidx.core.widget.NestedScrollView>

        </androidx.constraintlayout.motion.widget.MotionLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:itemIconTint="?colorDayNight"
            app:menu="@menu/menu_navigation_drawer" />

    </androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>

scene_test.xml

<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@id/iv_avatar"
            android:layout_width="20dp"
            android:layout_height="wrap_content"
            android:alpha="1" />
        <Constraint
            android:id="@id/fl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            android:alpha="1" />
        <Constraint
            android:id="@id/tv_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@id/fl"
            android:alpha="1" />
        <Constraint
            android:id="@id/ll"
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:alpha="0" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
            android:id="@id/iv_avatar"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:alpha="1" />
        <Constraint
            android:id="@id/fl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:alpha="1" />
        <Constraint
            android:id="@id/tv_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/fl"
            android:alpha="1" />
        <Constraint
            android:id="@id/ll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/tv_username"
            android:alpha="1" />
    </ConstraintSet>

    <Transition
        app:constraintSetEnd="@id/start"
        app:constraintSetStart="@id/end"
        app:duration="1000">
        <OnSwipe
            app:touchAnchorId="@id/scrollview"
            app:touchAnchorSide="top" />
    </Transition>
</MotionScene>

Thank you in advance!


问:
Fade a color to white (increasing brightness)
I want to make a text box in .NET "glow" yellow, and then "fade" to white (basically, by incrementally increasing the brightness). I think Stackoverflow does this after you've posted an answer. I know that increasing brightness is not all that simple (it's not just uniformly increasing/decreasing RGB), but I'm not sure how to do this.

Perfect color accuracy is not important for this. I am using C#, although VB examples would be just fine, too.

Edit: This is for Winforms.

答:
This may be more than you need, here's the code for the class I use:

```<code>public class ControlColorAnimator
{
    private const int INTERVAL = 100;

    private readonly decimal _alphaIncrement;
    private readonly decimal _blueIncrement;
    private readonly Color _endColor;
    private readonly decimal _greenIncrement;
    private readonly int _iterations;
    private readonly decimal _redIncrement;
    private readonly Color _startColor;

    private decimal _currentAlpha;
    private decimal _currentBlueValue;
    private decimal _currentGreenValue;
    private decimal _currentRedValue;

    private Timer _timer;

    public ControlColorAnimator(TimeSpan duration, Color startColor, Color endColor)
    {
        _startColor = startColor;
        _endColor = endColor;
        resetColor();

        _iterations = duration.Milliseconds / INTERVAL;
        _alphaIncrement = ((decimal) startColor.A - endColor.A) / _iterations;
        _redIncrement = ((decimal) startColor.R - endColor.R) / _iterations;
        _greenIncrement = ((decimal) startColor.G - endColor.G) / _iterations;
        _blueIncrement = ((decimal) startColor.B - endColor.B) / _iterations;
    }

    public Color CurrentColor
    {
        get
        {
            int alpha = Convert.ToInt32(_currentAlpha);
            int red = Convert.ToInt32(_currentRedValue);
            int green = Convert.ToInt32(_currentGreenValue);
            int blue = Convert.ToInt32(_currentBlueValue);

            return Color.FromArgb(alpha, red, green, blue);
        }
    }

    public event EventHandler<DataEventArgs<Color>> ColorChanged;

    public void Go()
    {
        disposeOfTheTimer();
        OnColorChanged(_startColor);

        resetColor();

        int currentIteration = 0;
        _timer = new Timer(delegate
            {
                if (currentIteration++ >= _iterations)
                {
                    Stop();
                    return;
                }
                _currentAlpha -= _alphaIncrement;
                _currentRedValue -= _redIncrement;
                _currentGreenValue -= _greenIncrement;
                _currentBlueValue -= _blueIncrement;
                OnColorChanged(CurrentColor);
            }, null, TimeSpan.FromMilliseconds(INTERVAL), TimeSpan.FromMilliseconds(INTERVAL));
    }

    public void Stop()
    {
        disposeOfTheTimer();
        OnColorChanged(_endColor);
    }

    protected virtual void OnColorChanged(Color color)
    {
        if (ColorChanged == null) return;
        ColorChanged(this, color);
    }

    private void disposeOfTheTimer()
    {
        Timer timer = _timer;
        _timer = null;

        if (timer != null) timer.Dispose();
    }

    private void resetColor()
    {
        _currentAlpha = _startColor.A;
        _currentRedValue = _startColor.R;
        _currentGreenValue = _startColor.G;
        _currentBlueValue = _startColor.B;
    }
}
</code>```

This uses DataEventArgs<T> (shown below)

```<code>/// <summary>
/// Generic implementation of <see cref="EventArgs"/> that allows for a data element to be passed.
/// </summary>
/// <typeparam name="T">The type of data to contain.</typeparam>
[DebuggerDisplay("{Data}")]
public class DataEventArgs<T> : EventArgs
{
    private T _data;

    /// <summary>
    /// Constructs a <see cref="DataEventArgs{T}"/>.
    /// </summary>
    /// <param name="data">The data to contain in the <see cref="DataEventArgs{T}"/></param>
    [DebuggerHidden]
    public DataEventArgs(T data)
    {
        _data = data;
    }

    /// <summary>
    /// Gets the data for this <see cref="DataEventArgs{T}"/>.
    /// </summary>
    public virtual T Data
    {
        [DebuggerHidden]
        get { return _data; }
        [DebuggerHidden]
        protected set { _data = value; }
    }

    [DebuggerHidden]
    public static implicit operator DataEventArgs<T>(T data)
    {
        return new DataEventArgs<T>(data);
    }

    [DebuggerHidden]
    public static implicit operator T(DataEventArgs<T> e)
    {
        return e.Data;
    }
}
</code>```

Use in your form like this:

```<code>private ControlColorAnimator _animator;

private void runColorLoop()
{
    endCurrentAnimation();
    startNewAnimation();
}

private void endCurrentAnimation()
{
    ControlColorAnimator animator = _animator;
    _animator = null;
    if (animator != null)
    {
        animator.ColorChanged -= _animator_ColorChanged;
        animator.Stop();
    }
}

private void startNewAnimation()
{
    _animator = new ControlColorAnimator(TimeSpan.FromSeconds(.6), Color.Yellow, BackColor);
    _animator.ColorChanged += _animator_ColorChanged;
    _animator.Go();
}

private void _animator_ColorChanged(object sender, DataEventArgs<Color> e)
{
    invokeOnFormThread(delegate { setColor(e); });
}

private void setColor(Color color)
{
    // code to set color of the controls goes here
}

private void invokeOnFormThread(MethodInvoker method)
{
    if (IsHandleCreated)
        Invoke(method);
    else
        method();
}
</code>```

OwnerDisplayName: Jon B

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jon B

Body:
This may be more than you need, here's the code for the class I use:

public class ControlColorAnimator
{
    private const int INTERVAL = 100;

    private readonly decimal _alphaIncrement;
    private readonly decimal _blueIncrement;
    private readonly Color _endColor;
    private readonly decimal _greenIncrement;
    private readonly int _iterations;
    private readonly decimal _redIncrement;
    private readonly Color _startColor;

    private decimal _currentAlpha;
    private decimal _currentBlueValue;
    private decimal _currentGreenValue;
    private decimal _currentRedValue;

    private Timer _timer;

    public ControlColorAnimator(TimeSpan duration, Color startColor, Color endColor)
    {
        _startColor = startColor;
        _endColor = endColor;
        resetColor();

        _iterations = duration.Milliseconds / INTERVAL;
        _alphaIncrement = ((decimal) startColor.A - endColor.A) / _iterations;
        _redIncrement = ((decimal) startColor.R - endColor.R) / _iterations;
        _greenIncrement = ((decimal) startColor.G - endColor.G) / _iterations;
        _blueIncrement = ((decimal) startColor.B - endColor.B) / _iterations;
    }

    public Color CurrentColor
    {
        get
        {
            int alpha = Convert.ToInt32(_currentAlpha);
            int red = Convert.ToInt32(_currentRedValue);
            int green = Convert.ToInt32(_currentGreenValue);
            int blue = Convert.ToInt32(_currentBlueValue);

            return Color.FromArgb(alpha, red, green, blue);
        }
    }

    public event EventHandler<DataEventArgs<Color>> ColorChanged;

    public void Go()
    {
        disposeOfTheTimer();
        OnColorChanged(_startColor);

        resetColor();

        int currentIteration = 0;
        _timer = new Timer(delegate
            {
                if (currentIteration++ >= _iterations)
                {
                    Stop();
                    return;
                }
                _currentAlpha -= _alphaIncrement;
                _currentRedValue -= _redIncrement;
                _currentGreenValue -= _greenIncrement;
                _currentBlueValue -= _blueIncrement;
                OnColorChanged(CurrentColor);
            }, null, TimeSpan.FromMilliseconds(INTERVAL), TimeSpan.FromMilliseconds(INTERVAL));
    }

    public void Stop()
    {
        disposeOfTheTimer();
        OnColorChanged(_endColor);
    }

    protected virtual void OnColorChanged(Color color)
    {
        if (ColorChanged == null) return;
        ColorChanged(this, color);
    }

    private void disposeOfTheTimer()
    {
        Timer timer = _timer;
        _timer = null;

        if (timer != null) timer.Dispose();
    }

    private void resetColor()
    {
        _currentAlpha = _startColor.A;
        _currentRedValue = _startColor.R;
        _currentGreenValue = _startColor.G;
        _currentBlueValue = _startColor.B;
    }
}

This uses DataEventArgs<T> (shown below)

/// <summary>
/// Generic implementation of <see cref="EventArgs"/> that allows for a data element to be passed.
/// </summary>
/// <typeparam name="T">The type of data to contain.</typeparam>
[DebuggerDisplay("{Data}")]
public class DataEventArgs<T> : EventArgs
{
    private T _data;

    /// <summary>
    /// Constructs a <see cref="DataEventArgs{T}"/>.
    /// </summary>
    /// <param name="data">The data to contain in the <see cref="DataEventArgs{T}"/></param>
    [DebuggerHidden]
    public DataEventArgs(T data)
    {
        _data = data;
    }

    /// <summary>
    /// Gets the data for this <see cref="DataEventArgs{T}"/>.
    /// </summary>
    public virtual T Data
    {
        [DebuggerHidden]
        get { return _data; }
        [DebuggerHidden]
        protected set { _data = value; }
    }

    [DebuggerHidden]
    public static implicit operator DataEventArgs<T>(T data)
    {
        return new DataEventArgs<T>(data);
    }

    [DebuggerHidden]
    public static implicit operator T(DataEventArgs<T> e)
    {
        return e.Data;
    }
}

Use in your form like this:

private ControlColorAnimator _animator;

private void runColorLoop()
{
    endCurrentAnimation();
    startNewAnimation();
}

private void endCurrentAnimation()
{
    ControlColorAnimator animator = _animator;
    _animator = null;
    if (animator != null)
    {
        animator.ColorChanged -= _animator_ColorChanged;
        animator.Stop();
    }
}

private void startNewAnimation()
{
    _animator = new ControlColorAnimator(TimeSpan.FromSeconds(.6), Color.Yellow, BackColor);
    _animator.ColorChanged += _animator_ColorChanged;
    _animator.Go();
}

private void _animator_ColorChanged(object sender, DataEventArgs<Color> e)
{
    invokeOnFormThread(delegate { setColor(e); });
}

private void setColor(Color color)
{
    // code to set color of the controls goes here
}

private void invokeOnFormThread(MethodInvoker method)
{
    if (IsHandleCreated)
        Invoke(method);
    else
        method();
}

OwnerDisplayName: Michael Meadows

LastEditorDisplayName: Michael Meadows


问:
Swift binding to a computed property
Have the following situation.  I have a view model that is an observable object with a computed property of type Bool.  I want to be able to enable/disable a navigation link based on the computed property, but I need a binding to do so.  Here a simplified example:

```<code>struct Project {
    var name: String
    var duration: Int
}

class MyViewModel: Observable Object {
    @Published var project: Project

    var isProjectValid: Bool {
        return project.name != "" && project.duration > 0
    }
}

struct MyView: View {
    @EnvironmentObject var myVM: MyViewModel

    var body: some View {
        ...
        NavigationLink("Click Link", isActive: ?????, destination: NextView())
        ...
    }
}
</code>```

Since isActive expects a binding I am not able to access computed property such as myVM.isProjectValid.  Tried also with the computed property in project class, still same problem.

Also considered creating custom binding related to the computed property, but not quite sure if/how to go about it.

First question I have posted, so if I am missing some details please be kind :)

答:
The use of the computed property suggests some type of design where the user is not supposed to trigger the NavigationLink directly. But instead the NavigationLink is expected to be triggered programatically as a side-effect of some other mechanism elsewhere in the code. Such as might be done at the completion of a form or similar process by the user.

Not 100% if this is what's being aimed for, but if it is, then one option would be to pass a constant Binding to the NavigationLink, e.g.

NavigationLink("Click Link", isActive: .constant(myVM.isProjectValid), destination: NextView())`
```

Title: Swift binding to a computed property

Body:
Have the following situation.  I have a view model that is an observable object with a computed property of type Bool.  I want to be able to enable/disable a navigation link based on the computed property, but I need a binding to do so.  Here a simplified example:

struct Project {
    var name: String
    var duration: Int
}

class MyViewModel: Observable Object {
    @Published var project: Project

    var isProjectValid: Bool {
        return project.name != "" && project.duration > 0
    }
}

struct MyView: View {
    @EnvironmentObject var myVM: MyViewModel

    var body: some View {
        ...
        NavigationLink("Click Link", isActive: ?????, destination: NextView())
        ...
    }
}

Since isActive expects a binding I am not able to access computed property such as myVM.isProjectValid.  Tried also with the computed property in project class, still same problem.

Also considered creating custom binding related to the computed property, but not quite sure if/how to go about it.

First question I have posted, so if I am missing some details please be kind :)


问:
Flickering Level Bar in Spigot/Minecraft Repeating Task
I'm currently running into a rather annoying problem.

Im running round about this task, with a Spigot-1.8 in Java 1.8. But this exact code gives me two diffrent Results.

In one the Levelbar of Minecraft just counts down and in another the Levelbar just flickers every time it sets the new XP Value.

```<code>private static int buildTask;
private static int buildSeconds = 120;

public static void buildingTime() {
    buildTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(Plugin.getInstance(), () -> {
        for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
            onlinePlayer.setLevel(buildSeconds);
        }

    //executing other Actions with Actionbar and Broadcasting Seconds to all players

    if (buildSeconds <= 0) {
        //ending here
    }

    buildSeconds--;
    }, 0, 20);
}
</code>```

I'm using this Spigot: https://getbukkit.org/get/hNiHm0tuqAg1Xg7w7zudk63uHr0xo48D

答: Already solved.... Let two tasks run at the same time which conflicted</p>

Body:
I'm currently running into a rather annoying problem.

Im running round about this task, with a Spigot-1.8 in Java 1.8. But this exact code gives me two diffrent Results.

In one the Levelbar of Minecraft just counts down and in another the Levelbar just flickers every time it sets the new XP Value.

private static int buildTask;
private static int buildSeconds = 120;

public static void buildingTime() {
    buildTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(Plugin.getInstance(), () -> {
        for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
            onlinePlayer.setLevel(buildSeconds);
        }

    //executing other Actions with Actionbar and Broadcasting Seconds to all players

    if (buildSeconds <= 0) {
        //ending here
    }

    buildSeconds--;
    }, 0, 20);
}

I'm using this Spigot: https://getbukkit.org/get/hNiHm0tuqAg1Xg7w7zudk63uHr0xo48D


问:
How do I Stream Realtime Video to a Website
I have a LEGO Mindstorms robot running Debian and Python. The robot can be controlled using a web interface to move, steer, turn on lights, etc... Currently I use this web interface to control the robot while I'm in the same room. I want to add a camera to the robot so I can control the robot remotely.

I have looked into adding a camera to the Mindstorms Brick, but the Brick does not have enough resources to stream a video source. So I don't think this route is possible.

Does anyone know of a method to stream live video content from a source from a Mindstorms Brick to a website? If not, maybe another source (it must be wireless, like an iPhone, GoPro, etc...) directly to a website.  It's quite important that there is as little delay as possible.

If there is a better forum for asking this questions please let me know, I looked around and could not find one.

答:
There is a similar solution for controlling RaspberryPI robot with camera, please read  this post.

Generally you need some UDP video streaming transport, like WebRTC or SRT.


问:
When adding "--" to animate a slide in RMarkdown, bullet point shifts
I'm writing up a presentation in RMarkdown. When using the -- between 2 lines (to animate the slide), I sometimes have an extra indentations between the bullet and the text.

See the source code here.

```<code>---
## Find patterns in random processes

- Simulations are useful to test the properties of randomly generated data
- Since we designed the simulation, we know parameters of the processes that underlie it.

--

- It is then possible to test various methods to
    1. see if they work and verify their assumptions,
    2. do power analysis,
    3. learn how data is generated
    4. etc.
</code>```

Before:

After:

答:
Just found this answer here:
https://github.com/gnab/remark/wiki/Markdown#incremental-slides

Basically, you shall NOT add a space before the to dashes --

So the code should be:

```<code>---
## Find patterns in random processes

- Simulations are useful to test the properties of randomly generated data
- Since we designed the simulation, we know parameters of the processes that underlie it.
--

- It is then possible to test various methods to
    1. see if they work and verify their assumptions,
    2. do power analysis,
    3. learn how data is generated
    4. etc.
</code>```

I tested it and it now works.

Body:
I'm writing up a presentation in RMarkdown. When using the -- between 2 lines (to animate the slide), I sometimes have an extra indentations between the bullet and the text.

See the source code here.

---
## Find patterns in random processes

- Simulations are useful to test the properties of randomly generated data
- Since we designed the simulation, we know parameters of the processes that underlie it.

--

- It is then possible to test various methods to
    1. see if they work and verify their assumptions,
    2. do power analysis,
    3. learn how data is generated
    4. etc.

Before:

After:

Body:
Just found this answer here:
https://github.com/gnab/remark/wiki/Markdown#incremental-slides

Basically, you shall NOT add a space before the to dashes --

So the code should be:

---
## Find patterns in random processes

- Simulations are useful to test the properties of randomly generated data
- Since we designed the simulation, we know parameters of the processes that underlie it.
--

- It is then possible to test various methods to
    1. see if they work and verify their assumptions,
    2. do power analysis,
    3. learn how data is generated
    4. etc.

I tested it and it now works.


问:
Focus Next Element In Tab Index
I am trying to move the focus to the next element in the tab sequence based upon the current element which has focus. Thus far I have not turned up anything in my searches.

```<code>function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFocusIn

    currentElementId = "";
    currentElement.nextElementByTabIndex.focus();
}
</code>```

Of course the nextElementByTabIndex is the key part for this to work. How do I find the next element in the tab sequence? The solution would need to be based using JScript and not something like JQuery.

答:
```<code>function focusNext() {
  var query = '[tabindex]';
  if (document.activeElement) {
    var elements = [...document.querySelectorAll(query)]
    var index = elements.indexOf(document.activeElement);
    index++
    if (index == elements.length) index = 0
    elements[index].focus()
  }
}
</code>```

If you want to target other elements, you can modify the query to refine the elements.

ContentLicense: CC BY-SA 3.0

Title: Focus Next Element In Tab Index

Body:
I am trying to move the focus to the next element in the tab sequence based upon the current element which has focus. Thus far I have not turned up anything in my searches.

function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFocusIn

    currentElementId = "";
    currentElement.nextElementByTabIndex.focus();
}

Of course the nextElementByTabIndex is the key part for this to work. How do I find the next element in the tab sequence? The solution would need to be based using JScript and not something like JQuery.

Body:
function focusNext() {
  var query = '[tabindex]';
  if (document.activeElement) {
    var elements = [...document.querySelectorAll(query)]
    var index = elements.indexOf(document.activeElement);
    index++
    if (index == elements.length) index = 0
    elements[index].focus()
  }
}

If you want to target other elements, you can modify the query to refine the elements.


问:
Interface to interface association in the book Head First Design Patterns
The book Head First Design Patterns presents the following UML as an example of the Observer pattern:

What strikes me in this diagram is the association relationship between the Subject and Observer interfaces. As far as I understand Java interfaces, they cannot implement a "Has-a" relationship in this way.

When I look at the implementation example provided a few pages later, I find that sure enough, the interfaces are plain old interfaces:

```<code>public interface Subject {
  public void registerObserver(Observer o);
  public void removeObserver(Observer o);
  public void notifyObservers;
}

public interface Observer {
  public void update(float temp, float humidity, float pressure);
}

</code>```

Instead, the association relationship is implemented in the concrete WeatherData and Display classes:

```<code>public class WeatherData implements Subject {
  private List<Observer> observers;
  //more code
}
</code>```

Which does not correspond to the UML and feels a bit wrong to me. Why not just implement Subject as an abstract class instead? Does the UML spec formalize the idea of associating an interface with another interface?

答:
You are right about your questioning. And let's see why the things are as they are:

Interfaces represent contracts. In Java, the contract is mainly about a set of methods. In UML, it can be broader, e.g. be about operations (methods), properties (fields), associations (not a java language feature: there are several ways to implement them), or contraints (preconditions, postconditions, invariants, ...).

Classes have to fulfil the contracts of the interfaces that they realize/implement.  In Java, the compiler will only verify that the class implements the methods required by the interface and with the right signature.  The developper would nevertheles expect more, i.e. that the java class behaves according to the interface's documentation. In UML, you'd similarly expect that a class provides itself all the features promised by the interface (see here).

How are the rules be enforced? In Java, you'll have to be explicit:  all methods must be provided or you'll get a compilation error. If you'd use TDD, you'd also foresee a set of tests that verifies that an object behaves according to contract of the interface. In UML, you can have ambiguities, because you are not forced to show everything in a diagram.  So if you don't show a class feature or an association, it doesn't meant that there is not such thing: the thing  could be in the model but not shown in a particular diagram. So if a class implements an interface, you could assume that it provides the elements even if they are not shown in the diagram.  If you'd use such an ambiguous diagram for code generation,  the code would not compile.

Coming back to your observer:

the diagram tells us that the Subject has a navigable association to Observer.  In the code,  you cannot implement nor even directly declare this kind of relationship in the interface.  However,  the fact that the Subject interface shall allow to register and remove Observers, implicitly suggest such an association.

the diagram don't tell us that WheatherData has a navigable association to CurrentConditionDisplay. But in principle, they should, since these classes realize Subject and Observer respectively. This makes the diagram ambiguous.  However, if we trust these classes to comply with the interface, we could live without showing the extra associations, just assuming that they have to be here.  Moreover, strict UML compliance would require to add 3 such associations here, making the diagram more difficult to read.

Now, as you rightly say,  we could implement the design patterns using an abstract class instead of an interface.  But since Java does not allow multiple inheritance,  this approach would forbid subjects or observers to be in other class hierarchies.

Some additional background

First of all, the observer pattern -- as all patterns in Heads first Design Pattern -- originates from the GoF. Interestingly, GoF predates UML and Java; Its patterns only used class inheritance, if needed with multiple inheritance.  When the book mentioned "interface", it was only about the implicit interface exposed by classes, very often abstract classes.

When Java came out, it was then a challenge to transpose all these design patterns, making explicit difference between interfaces (in the Java sense) and abstract classes.  This is why you'll often find several variants among class diagrams of these patterns.

Heads first is no exception. The goal of that excellent book is to teach using patterns in coding. The main purpose of its diagrams is therefore to convey the design intent, and not to teach the rigorous use of advanced UML. So they used diagrams that might sometimes be formally ambiguous.  Overall I think they made an excellent job.

Body:
The book Head First Design Patterns presents the following UML as an example of the Observer pattern:

What strikes me in this diagram is the association relationship between the Subject and Observer interfaces. As far as I understand Java interfaces, they cannot implement a "Has-a" relationship in this way.

When I look at the implementation example provided a few pages later, I find that sure enough, the interfaces are plain old interfaces:

public interface Subject {
  public void registerObserver(Observer o);
  public void removeObserver(Observer o);
  public void notifyObservers;
}

public interface Observer {
  public void update(float temp, float humidity, float pressure);
}

Instead, the association relationship is implemented in the concrete WeatherData and Display classes:

public class WeatherData implements Subject {
  private List<Observer> observers;
  //more code
}

Which does not correspond to the UML and feels a bit wrong to me. Why not just implement Subject as an abstract class instead? Does the UML spec formalize the idea of associating an interface with another interface?


问:
When to use JFace ComboViewer instead of combo?
In my application I need two combo boxes, the content of second one depends on the current selection of first combo. Should I use JFace ComboViewer for this? or shall I directly use combo?

If I use JFace ComboViewer what flexibility I'll get? or how JFace ComboViewer is better than Combo?

For more clarity, I have to use only strings for my combo.

Thanks in advance!!!

答: The primary difference - as far as I am concerned - is the use of a ILabelProvider for ComboViewer, whereas you have to calculate the entries yourself for Combo. Whether to use one or the other depends on the specific use-case...


问:
How to run a subquery in hive
I have this query that I am trying to run in HIVE:

```<code>select transaction_date, count(total_distinct) from (
SELECT transaction_date, concat(subid,'**', itemid) as total_distinct
FROM TBL_1
group by transaction_date, subid,itemid
) group by transaction_date
</code>```

What I am trying to do it get the distinct combination of subid and itemid, but I need the total count per day. When I run the query above, I get this error:

```<code>Error while compiling statement: FAILED: ParseException line 6:2 cannot recognize input near 'group' 'by' 'TRANSACTION_DATE' in subquery source
</code>```

The query looks correct to me though. Has anyone encountered this error?

答:
Hive requires subqueries to be aliased, so you need to specify a name for it:

```<code>select transaction_date, count(total_distinct) from (
SELECT transaction_date, concat(subid,'**', itemid) as total_distinct
FROM TBL_1
group by transaction_date, subid,itemid
) dummy  -- << note here
group by transaction_date
</code>```

True, the error message is far from helpful.

Title: How to run a subquery in hive

Body:
I have this query that I am trying to run in HIVE:

select transaction_date, count(total_distinct) from (
SELECT transaction_date, concat(subid,'**', itemid) as total_distinct
FROM TBL_1
group by transaction_date, subid,itemid
) group by transaction_date

What I am trying to do it get the distinct combination of subid and itemid, but I need the total count per day. When I run the query above, I get this error:

Error while compiling statement: FAILED: ParseException line 6:2 cannot recognize input near 'group' 'by' 'TRANSACTION_DATE' in subquery source

The query looks correct to me though. Has anyone encountered this error?

Body:
Hive requires subqueries to be aliased, so you need to specify a name for it:

select transaction_date, count(total_distinct) from (
SELECT transaction_date, concat(subid,'**', itemid) as total_distinct
FROM TBL_1
group by transaction_date, subid,itemid
) dummy  -- << note here
group by transaction_date

True, the error message is far from helpful.