问:
MSIX Include Additional Required Files
I have a simple WinForms app that I'm trying to package with MSIX. The app itself requires additional files that when I build the MSIX App Project doesn't copy/include.

Specifically this LIBVLC folder that gets included during the WinForms app build itself.

If I manually copy that folder over into the AppX build folder, everything works. Obviously I'm trying to automate including that folder.

Folder manually copied over in screenshot below:

How can I accomplish this? GitHub minimal repo:
https://github.com/aherrick/MSIXWinFormsLIBVLC

答:
I suspect that this line is your issue : https://github.com/aherrick/MSIXWinFormsLIBVLC/blob/0e717828a16e796a7a27e415cf45d33a50327da9/MSIXWinFormsLIBVLC.AppPackage/MSIXWinFormsLIBVLC.AppPackage.wapproj#L80

The nuget package isn't really well understood by the build tools as those are native files that we collect "before build". It seems to cause issues when a project references a project that references the nuget package, and the usual workaround is to reference the nuget package directly in the topmost project.

Is it possible to reference a nuget package in a .wapproj ?

If it isn't, that's an issue for this repository https://code.videolan.org/videolan/libvlc-nuget/ . Contributions welcome

Title: MSIX Include Additional Required Files


来源: stackexchange

问:
WPF DataGridTemplateColumn with ComboBox Binding (MVVM pattern)
I'm going bonkers with the following WPF DataGrid+ComboBox scenario.

I have a set of classes which look like;

```<code>class Owner
{
    int ID { get; }
    string Name { get; }

    public override ToString()
    {
        return this.Name;
    }
}

class House
{
    int ID { get; }
    Owner HouseOwner { get; set; }
}

class ViewModel
{
    ObservableCollection<Owner> Owners;
    ObservableCollection<House> Houses
}
</code>```

Now my desired outcome is a DataGrid which shows a list of rows of type House, and in one of the columns, is a ComboBox which allows the user to change the value of House.HouseOwner.

In this scenario, the DataContext for the grid is ViewModel.Houses and for the ComboBox, I want the ItemsSource to be bound to ViewModel.Owners.

Is this even possible? I'm going mental with this... the best I've been able to do is to correctly get the ItemsSource bound, however the ComboBox (inside a DataGridTemplateColumn) is not showing the correct values for House.HouseOwner in each row.

NOTE: If I take the ComboBox out of the picture and put a TextBlock in the DataTemplate instead, I can correctly see the values for each row, but getting both an ItemsSource as well as show the correct value in the selection is not working for me...

Inside my code behind, I have set the DataContext on the Window to ViewModel and on the grid, the DataContext is set to ViewModel.Houses. For everything except this combobox, it's working...

My XAML for the offending column looks like;

```<code><DataGridTemplateColumn Header="HouseOwner">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding Path=DataContext.Owners, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                        DisplayMemberPath="Name"
                        SelectedItem="{Binding HouseOwner, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                        SelectedValue="{Binding HouseOwner.ID, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Mode=OneWay}"
                        SelectedValuePath="ID" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code>```

Would love some help on this one... seems like a bit of Voodoo is required though...

答:
Thanks for the help all - I finally worked out why I couldn't select the ComboBox items - was due to a mouse preview event handler I had attached to the cell style when I was using a DataGridComboBoxColumn.

Have slapped myself for that one, thanks for the other assistance.

Also, as a note; the only way this will work for me is with an additional;

```<code>IsSynchronizedWithCurrentItem="False"
</code>```

Added to the ComboBox, else they all show the same value for some reason.

Also, I don't appear to require the SelectedValue/SelectedValuePath properties in my Binding, I believe because I have overridden Equals in my bound Owner type.

And lastly, I have to explicitly set;

Mode=TwoWay, UpdateSourceTrigger=PropertyChanged

In the Binding in order for the values to be written back to the bound items when the ComboBox has changed.

So, the final (working) XAML for the binding looks like this;

```<code>    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox
                ItemsSource="{Binding Path=DataContext.Owners,
                RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                IsSynchronizedWithCurrentItem="False"
                SelectedItem="{Binding HouseOwner, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</code>```

Cheers!

rJ

ContentLicense: CC BY-SA 3.0

Body:
I'm going bonkers with the following WPF DataGrid+ComboBox scenario.

I have a set of classes which look like;

class Owner
{
    int ID { get; }
    string Name { get; }

    public override ToString()
    {
        return this.Name;
    }
}

class House
{
    int ID { get; }
    Owner HouseOwner { get; set; }
}

class ViewModel
{
    ObservableCollection<Owner> Owners;
    ObservableCollection<House> Houses
}

Now my desired outcome is a DataGrid which shows a list of rows of type House, and in one of the columns, is a ComboBox which allows the user to change the value of House.HouseOwner.

In this scenario, the DataContext for the grid is ViewModel.Houses and for the ComboBox, I want the ItemsSource to be bound to ViewModel.Owners.

Is this even possible? I'm going mental with this... the best I've been able to do is to correctly get the ItemsSource bound, however the ComboBox (inside a DataGridTemplateColumn) is not showing the correct values for House.HouseOwner in each row.

NOTE: If I take the ComboBox out of the picture and put a TextBlock in the DataTemplate instead, I can correctly see the values for each row, but getting both an ItemsSource as well as show the correct value in the selection is not working for me...

Inside my code behind, I have set the DataContext on the Window to ViewModel and on the grid, the DataContext is set to ViewModel.Houses. For everything except this combobox, it's working...

My XAML for the offending column looks like;

<DataGridTemplateColumn Header="HouseOwner">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding Path=DataContext.Owners, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                        DisplayMemberPath="Name"
                        SelectedItem="{Binding HouseOwner, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                        SelectedValue="{Binding HouseOwner.ID, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Mode=OneWay}"
                        SelectedValuePath="ID" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Would love some help on this one... seems like a bit of Voodoo is required though...

Body:
Thanks for the help all - I finally worked out why I couldn't select the ComboBox items - was due to a mouse preview event handler I had attached to the cell style when I was using a DataGridComboBoxColumn.

Have slapped myself for that one, thanks for the other assistance.

Also, as a note; the only way this will work for me is with an additional;

IsSynchronizedWithCurrentItem="False"

Added to the ComboBox, else they all show the same value for some reason.

Also, I don't appear to require the SelectedValue/SelectedValuePath properties in my Binding, I believe because I have overridden Equals in my bound Owner type.

And lastly, I have to explicitly set;

Mode=TwoWay, UpdateSourceTrigger=PropertyChanged

In the Binding in order for the values to be written back to the bound items when the ComboBox has changed.

So, the final (working) XAML for the binding looks like this;

    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox
                ItemsSource="{Binding Path=DataContext.Owners,
                RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                IsSynchronizedWithCurrentItem="False"
                SelectedItem="{Binding HouseOwner, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>

Cheers!

rJ


问:
Functions as a argument
Just started learning python and came across this

```<code>def f(g):
    return g(2)

def square(x):
    return x ** 2

print(f(square)) # which gives 4
</code>```

How does inputting square into the f function equate to 4?

答: Calling f(square) is square(2) which is 2**2 so 4

ContentLicense: CC BY-SA 4.0

Title: Functions as a argument

Body:
Just started learning python and came across this

def f(g):
    return g(2)

def square(x):
    return x ** 2

print(f(square)) # which gives 4

How does inputting square into the f function equate to 4?


问:
How to compute CDF from a given PMF in Matlab
For a given PMF p=f(\theta) for \theta between 0 and 2\pi, i computed the CDF in Matlab as

```<code>theta=0:2*pi/n:2*pi
for i=1:n
cdf(i)=trapz(theta(1:i),p(1:i));
end
</code>```

and the result is verified.

I tried to do the same with cumsum as cdf=cumsum(p)*(2*pi)/n but the result is wrong. why?

How can i compute the CDF if the given PMF is in 2D asp=f(\theta,\phi) ? Can i do it without going into detail as explained here ?

答:
In 1D case you can use cumsum to get the vectorized version of loop (assuming that both theta and p are column vectors):

```<code>n = 10;
theta = linspace(0, 2*pi, n).';
p = rand(n,1);
cdf = [0; 0.5 * cumsum((p(1:n-1) + p(2:n)) .* diff(theta(1:n)))];
</code>```

In 2D case the function cumsum will be applied two times, in vertical and horizontal directions:

```<code>nthet = 10;
nphi = 10;
theta = linspace(0, 2*pi, nthet).';     % as column vector
phi = linspace(0, pi, nphi);            % as row vector
p = rand(nthet, nphi);
cdf1 =  0.5 * cumsum((p(1:end-1, :) + p(2:end, :)) .* diff(theta), 1);
cdf2 =  0.5 * cumsum((cdf1(:, 1:end-1) + cdf1(:, 2:end)) .* diff(phi), 2);
cdf = zeros(nthet, nphi);
cdf(2:end, 2:end) = cdf2;
</code>```

Body:
For a given PMF p=f(\theta) for \theta between 0 and 2\pi, i computed the CDF in Matlab as

theta=0:2*pi/n:2*pi
for i=1:n
cdf(i)=trapz(theta(1:i),p(1:i));
end

and the result is verified.

I tried to do the same with cumsum as cdf=cumsum(p)*(2*pi)/n but the result is wrong. why?

How can i compute the CDF if the given PMF is in 2D asp=f(\theta,\phi) ? Can i do it without going into detail as explained here ?

Body:
In 1D case you can use cumsum to get the vectorized version of loop (assuming that both theta and p are column vectors):

n = 10;
theta = linspace(0, 2*pi, n).';
p = rand(n,1);
cdf = [0; 0.5 * cumsum((p(1:n-1) + p(2:n)) .* diff(theta(1:n)))];

In 2D case the function cumsum will be applied two times, in vertical and horizontal directions:

nthet = 10;
nphi = 10;
theta = linspace(0, 2*pi, nthet).';     % as column vector
phi = linspace(0, pi, nphi);            % as row vector
p = rand(nthet, nphi);
cdf1 =  0.5 * cumsum((p(1:end-1, :) + p(2:end, :)) .* diff(theta), 1);
cdf2 =  0.5 * cumsum((cdf1(:, 1:end-1) + cdf1(:, 2:end)) .* diff(phi), 2);
cdf = zeros(nthet, nphi);
cdf(2:end, 2:end) = cdf2;


问:
process is not defined in Vue.js
I tried to use the process.env.process.env.VUE_APP_SERVER_URL in my vue project. But I got the error like the following.

```<code>Uncaught ReferenceError: process is not defined
</code>```

It's using the webpack and run by npm start command.

Once you know the solution, please feel free to contact me.

答:
You can add the following code in webpack.config.js.

```<code>const webpack = require('webpack');
const dotenv = require('dotenv').config({ path: __dirname + '/.env' })

module.exports = {
   ...
   plugins: [
      new webpack.DefinePlugin({
          'process.env': JSON.stringify(dotenv.parsed),
      }),
   ]
   ...
}
</code>```

Title: process is not defined in Vue.js

Body:
I tried to use the process.env.process.env.VUE_APP_SERVER_URL in my vue project. But I got the error like the following.

Uncaught ReferenceError: process is not defined

It's using the webpack and run by npm start command.

Once you know the solution, please feel free to contact me.

Body:
You can add the following code in webpack.config.js.

const webpack = require('webpack');
const dotenv = require('dotenv').config({ path: __dirname + '/.env' })

module.exports = {
   ...
   plugins: [
      new webpack.DefinePlugin({
          'process.env': JSON.stringify(dotenv.parsed),
      }),
   ]
   ...
}


问:
find method returns undefined
I make find method on users array but selectedUserId = undefined
How can I execute this method necessarily after the async function so that the selectedUserId is not undefined?</p>
```<code>function App() {
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const [loading, setLoading] = useState(false)
console.log(users)

useAsyncEffect(async () => {
  setLoading(true)
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await res.json()
  setUsers(data)
  setLoading(false)
 }, [])

 const selectedUser = users.find(u => u.id === selectedUserId)
 console.log(selectedUser)

 const onUserClick = (userId) => {
  setSelectedUserId(userId)
}

if(loading) {
  return <img src={preloader} alt="preloader"/>
}

return (
  <div>
  { !selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user=
  {selectedUser}  />
  }
  </div>
 )
 }
</code>```

答:
useEffect() hook will be called after rendering / component update.
so, on First time the users value will be empty array.

so, the selectedUser value will be undefined.
Wrap it in another useEffect will work.

Title: find method returns undefined

Body:
I make find method on users array but selectedUserId = undefined
How can I execute this method necessarily after the async function so that the selectedUserId is not undefined?

function App() {
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const [loading, setLoading] = useState(false)
console.log(users)

useAsyncEffect(async () => {
  setLoading(true)
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await res.json()
  setUsers(data)
  setLoading(false)
 }, [])

 const selectedUser = users.find(u => u.id === selectedUserId)
 console.log(selectedUser)

 const onUserClick = (userId) => {
  setSelectedUserId(userId)
}

if(loading) {
  return
}

return (

  { !selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user=
  {selectedUser}  />
  }

 )
 }


问:
How to compare column values in different dataframes?
I have found this code , and it is working very well.

```<code>df1 = pd.DataFrame({'c1': [1, 4, 7], 'c2': [2, 5, 1], 'c3': [3, 1, 1]})
 df2 = pd.DataFrame({'c4': [1, 4, 7], 'c2': [3, 5, 2], 'c3': [3, 7, 5]})
 set(df1['c2']).intersection(set(df2['c2']))
</code>```

But I need to compare them with multiple column names like

```<code>set(df1['c2']['c3']).intersection(set(df2['c2']['c3']))
</code>```

But it is not working. How to fix or what is another way to compare them and find similar values ( matches ) ?

答:
You can try with merge follow by drop_duplicates

```<code>df1.merge(df2,on = ['c2','c3'])[['c2','c3']].drop_duplicates()
</code>```

Body:
I have found this code , and it is working very well.

df1 = pd.DataFrame({'c1': [1, 4, 7], 'c2': [2, 5, 1], 'c3': [3, 1, 1]})
 df2 = pd.DataFrame({'c4': [1, 4, 7], 'c2': [3, 5, 2], 'c3': [3, 7, 5]})
 set(df1['c2']).intersection(set(df2['c2']))

But I need to compare them with multiple column names like

set(df1['c2']['c3']).intersection(set(df2['c2']['c3']))

But it is not working. How to fix or what is another way to compare them and find similar values ( matches ) ?

Body:
You can try with merge follow by drop_duplicates

df1.merge(df2,on = ['c2','c3'])[['c2','c3']].drop_duplicates()


问:
How to verify email in firebase auth?
I am using expo client for my app. When I send the email, the verification immediately fails. When I go to the email and verify it, the verification still doesn't work. This is my function:

```<code>firebase.auth().createUserWithEmailAndPassword(emailID, password)
    .then(async ({
        user
    }) => {
        //console.log(this.state)
        await user.sendEmailVerification().then(async () => {
            user = await firebase.auth().currentUser;

            await user.reload();

            user = await firebase.auth().currentUser;
            if (user.emailVerified) {
                db.collection("Users").add({
                    'firstName': this.state.firstName,
                    'lastName': this.state.lastName,
                    'contact': this.state.contact,
                    'emailID': this.state.emailID,
                    'password': this.state.password,
                    'description': '',
                    'profilePicture': ''
                })
                return alert('Account has been created. You can now login.');
            } else {
                return alert('Failed to verify email!')
            }
        })
    })
    .catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        return alert(errorMessage);
    });
</code>```

Can anyone please provide me a solution for this? Thanks,

答:
The code in your inner then block looks good, but it runs only once: immediately after you sent the verification email.

When you call sendEmailVerification that merely sends the email. Only once you click the link in that email will the email address on the profile be set to verify.

So you will need to re-sign in, or call user.reload(), after clicking the link in order to get the profile with the updated verification status. This means you'll typically run the code that you have in then then block:

When the app regains the focus, as often the user needs to toggle to another app to click the verification link, so when the app regains focus is a good moment to check the verification status again.

Tell the user to click a button to recheck the verification status.

Periodically (say every few second) run the check.

You can pick one of these, but also use any combination of them to ensure the verification status gets picked up quickly in your app.

Title: How to verify email in firebase auth?

Body:
I am using expo client for my app. When I send the email, the verification immediately fails. When I go to the email and verify it, the verification still doesn't work. This is my function:

firebase.auth().createUserWithEmailAndPassword(emailID, password)
    .then(async ({
        user
    }) => {
        //console.log(this.state)
        await user.sendEmailVerification().then(async () => {
            user = await firebase.auth().currentUser;

            await user.reload();

            user = await firebase.auth().currentUser;
            if (user.emailVerified) {
                db.collection("Users").add({
                    'firstName': this.state.firstName,
                    'lastName': this.state.lastName,
                    'contact': this.state.contact,
                    'emailID': this.state.emailID,
                    'password': this.state.password,
                    'description': '',
                    'profilePicture': ''
                })
                return alert('Account has been created. You can now login.');
            } else {
                return alert('Failed to verify email!')
            }
        })
    })
    .catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        return alert(errorMessage);
    });

Can anyone please provide me a solution for this? Thanks,


问:
How to allow buttons to be pressed quickly on a website
I have set up a keyboard on my website where you can click on a key to type a letter. When i access the site on my phone and try to type a word, it misses out keys because it won't allow for buttons to be pressed that quickly.

Is there a way to allow this?
an example would be in wordle: https://www.powerlanguage.co.uk/wordle/ where the buttons can be pressed in quick succession

my website uses react if that helps

答:
In the case in which you cannot "move" the text cursor (as it happens in wordle), you could consider using this combination of event listeners, intervals and queue-like array structures:

HTML:

```<code><div class="output"></div>
...
<button type="button" class="letter"> Q </button>
<button type="button" class="letter"> W </button>
<button type="button" class="letter"> E </button>
...
<button type="button" class="letter"> ← </button>
</code>```

JS:

```<code>let word = [ ];

document.querySelectorAll(".letter").forEach(
    el => el.addEventListener("click", ev => {
        word.push(el.innerText.trim());
    })
);

setInterval(() => {
    if(word.length) {
        let char = word.shift();
        if(char == "←") document.querySelector(".output").innerText = document.querySelector(".output").innerText.slice(0, -1);
        else document.querySelector(".output").innerText += char;
    }
}, 50);
</code>```

Body:
In the case in which you cannot "move" the text cursor (as it happens in wordle), you could consider using this combination of event listeners, intervals and queue-like array structures:

HTML:

<div class="output"></div>
...
<button type="button" class="letter"> Q </button>
<button type="button" class="letter"> W </button>
<button type="button" class="letter"> E </button>
...
<button type="button" class="letter"> ← </button>

JS:

let word = [ ];

document.querySelectorAll(".letter").forEach(
    el => el.addEventListener("click", ev => {
        word.push(el.innerText.trim());
    })
);

setInterval(() => {
    if(word.length) {
        let char = word.shift();
        if(char == "←") document.querySelector(".output").innerText = document.querySelector(".output").innerText.slice(0, -1);
        else document.querySelector(".output").innerText += char;
    }
}, 50);


答:
When you call a function, the value of the argument is assigned to the named parameter. The call

```<code>print(f(square))
</code>```

can be thought of as "expanding" to

```<code>g = square
print(g(2))
</code>```

Title: Functions as a argument

Body:
When you call a function, the value of the argument is assigned to the named parameter. The call

print(f(square))

can be thought of as "expanding" to

g = square
print(g(2))


问:
Lift: Comet component not found / Class not found
For my first steps into Lift I just started with this tutorial but it won't work for me. Instead of the simple chat app I only get these two exceptions:

```<code>Error processing snippet: comet
Reason: Comet Component not found
</code>```

and

```<code>Error processing snippet: ChatIn
Reason: Class Not Found
</code>```

Here is the directory structure of my compiled webapp:

```<code>target/chat-1.0-SNAPSHOT/
├── index.html
├── META-INF
└── WEB-INF
    ├── classes
    │   └── code
    │       ├── comet
    │       │   ├── Chat$$anonfun$lowPriority$1.class
    │       │   ├── Chat.class
    │       │   ├── ChatServer$$anonfun$lowPriority$1.class
    │       │   ├── ChatServer.class
    │       │   └── ChatServer$.class
    │       └── snippet
    │           ├── ChatIn$$anonfun$render$1.class
    │           ├── ChatIn.class
    │           └── ChatIn$.class
    ├── lib
    │   ├── activation-1.1.jar
    │   ├── commons-codec-1.4.jar
    │   ├── commons-fileupload-1.2.2.jar
    │   ├── derby-10.7.1.1.jar
    │   ├── h2-1.2.147.jar
    │   ├── htmlparser-1.2.1.jar
    │   ├── joda-time-1.6.2.jar
    │   ├── lift-actor_2.9.0-2.4-M3.jar
    │   ├── lift-common_2.9.0-2.4-M3.jar
    │   ├── lift-db_2.9.0-2.4-M3.jar
    │   ├── lift-json_2.9.0-2.4-M3.jar
    │   ├── lift-mapper_2.9.0-2.4-M3.jar
    │   ├── lift-proto_2.9.0-2.4-M3.jar
    │   ├── lift-util_2.9.0-2.4-M3.jar
    │   ├── lift-webkit_2.9.0-2.4-M3.jar
    │   ├── mail-1.4.4.jar
    │   ├── paranamer-2.3.jar
    │   ├── scala-compiler-2.9.0.jar
    │   ├── scala-library-2.9.0.jar
    │   ├── scalap-2.9.0.jar
    │   └── slf4j-api-1.6.1.jar
    └── web.xml
</code>```

But as you can see, there are the compiled .class files for Chat, ChatServer and ChatIn, so what's wrong?

答:
Please bring this question to the Lift Google group: https://groups.google.com/forum/#!forum/liftweb

It's likely that your Boot.scala doesn't contain the correct information, but without the source, it's tough to figure out the issue.

Body:
For my first steps into Lift I just started with this tutorial but it won't work for me. Instead of the simple chat app I only get these two exceptions:

Error processing snippet: comet
Reason: Comet Component not found

and

Error processing snippet: ChatIn
Reason: Class Not Found

Here is the directory structure of my compiled webapp:

target/chat-1.0-SNAPSHOT/
├── index.html
├── META-INF
└── WEB-INF
    ├── classes
    │   └── code
    │       ├── comet
    │       │   ├── Chat$$anonfun$lowPriority$1.class
    │       │   ├── Chat.class
    │       │   ├── ChatServer$$anonfun$lowPriority$1.class
    │       │   ├── ChatServer.class
    │       │   └── ChatServer$.class
    │       └── snippet
    │           ├── ChatIn$$anonfun$render$1.class
    │           ├── ChatIn.class
    │           └── ChatIn$.class
    ├── lib
    │   ├── activation-1.1.jar
    │   ├── commons-codec-1.4.jar
    │   ├── commons-fileupload-1.2.2.jar
    │   ├── derby-10.7.1.1.jar
    │   ├── h2-1.2.147.jar
    │   ├── htmlparser-1.2.1.jar
    │   ├── joda-time-1.6.2.jar
    │   ├── lift-actor_2.9.0-2.4-M3.jar
    │   ├── lift-common_2.9.0-2.4-M3.jar
    │   ├── lift-db_2.9.0-2.4-M3.jar
    │   ├── lift-json_2.9.0-2.4-M3.jar
    │   ├── lift-mapper_2.9.0-2.4-M3.jar
    │   ├── lift-proto_2.9.0-2.4-M3.jar
    │   ├── lift-util_2.9.0-2.4-M3.jar
    │   ├── lift-webkit_2.9.0-2.4-M3.jar
    │   ├── mail-1.4.4.jar
    │   ├── paranamer-2.3.jar
    │   ├── scala-compiler-2.9.0.jar
    │   ├── scala-library-2.9.0.jar
    │   ├── scalap-2.9.0.jar
    │   └── slf4j-api-1.6.1.jar
    └── web.xml

But as you can see, there are the compiled .class files for Chat, ChatServer and ChatIn, so what's wrong?


问:
Quarter function in Snowflake
I have written the "select" query for the quarter function in SAP HANA.

```<code>select QUARTER (CURRENT_DATE, 8) FROM DUMMY;

output: 2021-Q3
</code>```

Can someone please help me with the equivalent query in Snowflake?

答:
The goal is to handle second argument indicating start month of fiscal year.

```<code>QUARTER (d, [, start_month ])
</code>```

For current date(2022-02-06) the output should not be 2022-Q1 but 2021-Q3.

It could be achieved with some date computations:

first part is handling year(current/previous)

second part is computing quarter adjusted with start month

Query:

```<code>SET FirstMonth = 8;

SELECT  YEAR(d) - IFF(d >= DATEFROMPARTS(YEAR(d),$FirstMonth,1), 0, 1)
        || '-Q' || QUARTER(DATEADD(month, -$FirstMonth+1, d)) AS output
FROM (SELECT CURRENT_DATE() AS d) AS sub;
</code>```

Output: 2021-Q3

Title: Quarter function in Snowflake

Body:
I have written the "select" query for the quarter function in SAP HANA.

select QUARTER (CURRENT_DATE, 8) FROM DUMMY;

output: 2021-Q3

Can someone please help me with the equivalent query in Snowflake?

Body:
The goal is to handle second argument indicating start month of fiscal year.

QUARTER (d, [, start_month ])

For current date(2022-02-06) the output should not be 2022-Q1 but 2021-Q3.

It could be achieved with some date computations:

first part is handling year(current/previous)

second part is computing quarter adjusted with start month

Query:

SET FirstMonth = 8;

SELECT  YEAR(d) - IFF(d >= DATEFROMPARTS(YEAR(d),$FirstMonth,1), 0, 1)
        || '-Q' || QUARTER(DATEADD(month, -$FirstMonth+1, d)) AS output
FROM (SELECT CURRENT_DATE() AS d) AS sub;

Output: 2021-Q3


问:
ImportError: No module named 'spacy.en'
I'm working on a codebase that uses Spacy. I installed spacy using:

```<code>sudo pip3 install spacy
</code>```

and then

```<code>sudo python3 -m spacy download en
</code>```

At the end of this last command, I got a message:

```<code>    Linking successful
/home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm -->
/home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en

You can now load the model via spacy.load('en')
</code>```

Now, when I try running my code, on the line:

```<code>    from spacy.en import English
</code>```

it gives me the following error:

```<code>ImportError: No module named 'spacy.en'
</code>```

I've looked on Stackexchange and the closest is:  Import error with spacy: "No module named en"
which does not solve my problem.

Any help would be appreciated. Thanks.

Edit: I might have solved this by doing the following:

```<code> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spacy
>>> spacy.load('en')
<spacy.lang.en.English object at 0x7ff414e1e0b8>
</code>```

and then using:

```<code>from spacy.lang.en import English
</code>```

I'm still keeping this open in case there are any other answers.

答:
For me the below steps worked in my Jupyter:</p>
```<code>pip install spacy

import spacy

from spacy.cli import download

print(download('en_core_web_sm'))
</code>```

Title: ImportError: No module named 'spacy.en'

Body:
I'm working on a codebase that uses Spacy. I installed spacy using:

sudo pip3 install spacy

and then

sudo python3 -m spacy download en

At the end of this last command, I got a message:

    Linking successful
/home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm -->
/home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en

You can now load the model via spacy.load('en')

Now, when I try running my code, on the line:

    from spacy.en import English

it gives me the following error:

ImportError: No module named 'spacy.en'

I've looked on Stackexchange and the closest is:  Import error with spacy: "No module named en"
which does not solve my problem.

Any help would be appreciated. Thanks.

Edit: I might have solved this by doing the following:

 Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spacy
>>> spacy.load('en')
<spacy.lang.en.English object at 0x7ff414e1e0b8>

and then using:

from spacy.lang.en import English

I'm still keeping this open in case there are any other answers.

Body:
For me the below steps worked in my Jupyter:

pip install spacy

import spacy

from spacy.cli import download

print(download('en_core_web_sm'))


问:
Get all keys with the same value in a dictionary
I have a dictionary with all the letters and I want to get all the letters (so the keys) that occur the most.

```<code>letters = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 1, 'F': 1, 'G': 1, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 2, 'M': 4, 'N': 0, 'O': 1, 'P': 1, 'Q': 4, 'R': 0, 'S': 1, 'T': 2, 'U': 2, 'V': 0, 'W': 0, 'X': 1, 'Y': 0, 'Z': 0}
</code>```

So M and Q are to be output

My Python version is 3.9.2

答:
max_value = max(letters.values())
[key for key, val in letters.items() if val == max_value]
```

Body:
I have a dictionary with all the letters and I want to get all the letters (so the keys) that occur the most.

letters = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 1, 'F': 1, 'G': 1, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 2, 'M': 4, 'N': 0, 'O': 1, 'P': 1, 'Q': 4, 'R': 0, 'S': 1, 'T': 2, 'U': 2, 'V': 0, 'W': 0, 'X': 1, 'Y': 0, 'Z': 0}

So M and Q are to be output

My Python version is 3.9.2


问:
How can I display a bing map in any HTML page?
Bing's got something they call "an AJAX control" that can dynamically embed generated maps into any webpage. There's an online interactive demo for the control. </p>

<p>How can I use this control? </p>

答:
The link you mentioned itself has a View HTML button on bottom, you can click it and grab the code to display in any webpage. Like below (which i got from your link):

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title>Map with valid credentials</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript">
      var map = null;

      function getMap()
      {
          map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: 'Your Bing Maps Key'});
      }
      </script>
   </head>
   <body onload="getMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
   </body>
</html>
</code>```

Body:
Bing's got something they call "an AJAX control" that can dynamically embed generated maps into any webpage. There's an online interactive demo for the control.

How can I use this control?

Body:
The link you mentioned itself has a View HTML button on bottom, you can click it and grab the code to display in any webpage. Like below (which i got from your link):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title>Map with valid credentials</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript">
      var map = null;

      function getMap()
      {
          map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: 'Your Bing Maps Key'});
      }
      </script>
   </head>
   <body onload="getMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
   </body>
</html>


问:
Optimal joins in MySQL or offloading to application layer
I have 3 tables in a MySQL database: courses, users and participants, which contains about 30mil, 30k and 3k entries respectively.

My goal is to (efficiently) figure out the number of users that have been assigned to courses that matches our criteria. The criteria is a little more complex, but for this example we only care about users where deleted_at is null and courses where deleted_at is null and active is 1.

Simplified these are the columns:

users:

id
deleted_at

1
null

2
2022-01-01

courses:

id
active
deleted_at

1
1
null

1
1
2020-01-01

2
0
2020-01-01

participants:

id
participant_id
course_id

1
1
1

2
1
2

3
2
2

Based on the data above, the number we would get would be 1 as only user 1 is not deleted and that user assigned to some course (id 1) that is active and not deleted.

Here is a list of what I've tried.

Joining all the tables and do simple where's.

Joining using subqueries.

Pulling the correct courses and users out to the application layer (PHP), and querying participants using WHERE IN.

Pulling everything out and doing the filtering in the application layer.

Calling using EXPLAIN to add better indexes - I, admittedly, do not do this often and may not have done this well enough.

A combination of all the above.

An example of a query would be:

SELECT COUNT(DISTINCT participant_id)
FROM `participants`
INNER JOIN
  (SELECT `courses`.`id`
   FROM `courses`
   WHERE (`active` = '1')
     AND `deleted_at` IS NULL) AS `tempCourses` ON `tempCourses`.`id` = `participants`.`course_id`
WHERE `participant_type` = 'Eloomi\\Models\\User'
  AND `participant_id` in
    (SELECT `users`.`id`
     FROM `users`
     WHERE `users`.`deleted_at` IS NULL)
```

From what I can gather doing this will create a massive table, which only then will start applying where's. In my mind it should be possible to short circuit a lot of that because once we get a match for a user, we can disregard that going forward. That would be how to handle it, in my mind, in the application layer.

We could do this on a per-user basis in the application layer, but the number of requests to the database would make this a bad solution.

I have tagged it as PHP as well as MySQL, not because it has to be PHP but because I do not mind offloading some parts to the application layer if that is required. It's my experience that joins do not always use indexes optimally

Edit:
To specify my question: Can someone help me provide a efficient way to pull out the number of non-deleted users that have been assigned to to active non-deleted courses?

答:
I would write it this way:

```<code>SELECT COUNT(DISTINCT p.participant_id)
FROM courses AS c
INNER JOIN participants AS p
 ON c.id = p.course_id
INNER JOIN users AS u
 ON p.participant_id = u.id
WHERE u.deleted_at IS NULL
 AND c.active = 1 AND c.deleted_at IS NULL
 AND p.participant_type = 'Eloomi\\Models\\User';
</code>```

MySQL may join the tables in another order, not the order you list the tables in the query.

I hope that courses is the first table MySQL accesses, because it's probably the smallest table. Especially after filtering by active and deleted_at. The following index will help to narrow down that filtering, so only matching rows are examined:

```<code>ALTER TABLE courses ADD KEY (active, deleted_at);
</code>```

Every index implicitly has the table's primary key (e.g. id) appended as the last column. That column being part of the index, it is used in the join to participants. So you need an index in participants that the join uses to find the corresponding rows in that table. The order of columns in the index is important.

```<code>ALTER TABLE participants ADD KEY (course_id, participant_type, participant_id);
</code>```

The participant_id is used to join to the users table. MySQL's optimizer will probably prefer to join to users by its primary key, but you also want to restrict that by deleted_at, so you might need this index:

```<code>ALTER TABLE users ADD KEY (id, deleted_at);
</code>```

And you might need to use an index hint to coax the optimizer to prefer this secondary index over the primary key index.

```<code>SELECT COUNT(DISTINCT p.participant_id)
FROM courses AS c
INNER JOIN participants AS p
 ON c.id = p.course_id
INNER JOIN users AS u USE INDEX(deleted_at)
 ON p.participant_id = u.id
WHERE u.deleted_at IS NULL
 AND c.active = 1 AND c.deleted_at IS NULL
 AND p.participant_type = 'Eloomi\\Models\\User';
</code>```

MySQL knows how to use compound indexes even if some conditions are in join clauses and other conditions are in the WHERE clause.

Caveat: I have not tested this. Choosing indexes may take several tries, and testing the EXPLAIN after each try.

Body:
I have 3 tables in a MySQL database: courses, users and participants, which contains about 30mil, 30k and 3k entries respectively.

My goal is to (efficiently) figure out the number of users that have been assigned to courses that matches our criteria. The criteria is a little more complex, but for this example we only care about users where deleted_at is null and courses where deleted_at is null and active is 1.

Simplified these are the columns:

users:

id
deleted_at

1
null

2
2022-01-01

courses:

id
active
deleted_at

1
1
null

1
1
2020-01-01

2
0
2020-01-01

participants:

id
participant_id
course_id

1
1
1

2
1
2

3
2
2

Based on the data above, the number we would get would be 1 as only user 1 is not deleted and that user assigned to some course (id 1) that is active and not deleted.

Here is a list of what I've tried.

Joining all the tables and do simple where's.

Joining using subqueries.

Pulling the correct courses and users out to the application layer (PHP), and querying participants using WHERE IN.

Pulling everything out and doing the filtering in the application layer.

Calling using EXPLAIN to add better indexes - I, admittedly, do not do this often and may not have done this well enough.

A combination of all the above.

An example of a query would be:

SELECT COUNT(DISTINCT participant_id)
FROM `participants`
INNER JOIN
  (SELECT `courses`.`id`
   FROM `courses`
   WHERE (`active` = '1')
     AND `deleted_at` IS NULL) AS `tempCourses` ON `tempCourses`.`id` = `participants`.`course_id`
WHERE `participant_type` = 'Eloomi\\Models\\User'
  AND `participant_id` in
    (SELECT `users`.`id`
     FROM `users`
     WHERE `users`.`deleted_at` IS NULL)

From what I can gather doing this will create a massive table, which only then will start applying where's. In my mind it should be possible to short circuit a lot of that because once we get a match for a user, we can disregard that going forward. That would be how to handle it, in my mind, in the application layer.

We could do this on a per-user basis in the application layer, but the number of requests to the database would make this a bad solution.

I have tagged it as PHP as well as MySQL, not because it has to be PHP but because I do not mind offloading some parts to the application layer if that is required. It's my experience that joins do not always use indexes optimally

Edit:
To specify my question: Can someone help me provide a efficient way to pull out the number of non-deleted users that have been assigned to to active non-deleted courses?

Body:
I would write it this way:

SELECT COUNT(DISTINCT p.participant_id)
FROM courses AS c
INNER JOIN participants AS p
 ON c.id = p.course_id
INNER JOIN users AS u
 ON p.participant_id = u.id
WHERE u.deleted_at IS NULL
 AND c.active = 1 AND c.deleted_at IS NULL
 AND p.participant_type = 'Eloomi\\Models\\User';

MySQL may join the tables in another order, not the order you list the tables in the query.

I hope that courses is the first table MySQL accesses, because it's probably the smallest table. Especially after filtering by active and deleted_at. The following index will help to narrow down that filtering, so only matching rows are examined:

ALTER TABLE courses ADD KEY (active, deleted_at);

Every index implicitly has the table's primary key (e.g. id) appended as the last column. That column being part of the index, it is used in the join to participants. So you need an index in participants that the join uses to find the corresponding rows in that table. The order of columns in the index is important.

ALTER TABLE participants ADD KEY (course_id, participant_type, participant_id);

The participant_id is used to join to the users table. MySQL's optimizer will probably prefer to join to users by its primary key, but you also want to restrict that by deleted_at, so you might need this index:

ALTER TABLE users ADD KEY (id, deleted_at);

And you might need to use an index hint to coax the optimizer to prefer this secondary index over the primary key index.

SELECT COUNT(DISTINCT p.participant_id)
FROM courses AS c
INNER JOIN participants AS p
 ON c.id = p.course_id
INNER JOIN users AS u USE INDEX(deleted_at)
 ON p.participant_id = u.id
WHERE u.deleted_at IS NULL
 AND c.active = 1 AND c.deleted_at IS NULL
 AND p.participant_type = 'Eloomi\\Models\\User';

MySQL knows how to use compound indexes even if some conditions are in join clauses and other conditions are in the WHERE clause.

Caveat: I have not tested this. Choosing indexes may take several tries, and testing the EXPLAIN after each try.


问:
Maximum number of subarrays having equal sum
I was asked this question in one of my interview. Given an array of integers (with both positive and negative values) we need to find the maximum number of disjoint subarrays having equal sum.

Example :

Input : [1, 2, 3]
Output : 2 {since we have at most 2 subarrays with sum = 3 i.e. [1, 2],[3]}

Input: [2 2 2 -2]
Output : 2 {two subarrays each with sum = 2 i.e. [2],[2, 2, -2]}

My Approach

First approach that came to my mind was to find the prefix sum array and then taking each element (prefix[i]) as target finding the number of subarrays with sum = prefix[i] .

But this failed in the case of negative numbers. How to handle the negative cases?

EDIT Complete array must be covered with these subarrays. That is why in example 2 we get 2 as output and not 3 ([2],[2],[2]).

答:
I assume the whole array needs to be covered with sub-arrays.

After thinking about it for some time I am pretty confident, that the following O(n^2) algorithm should be valid:

```<code>public static int maxSplitCount(int[] a) {

    int res = 0; // highest sub-array count found so far

    int sum = 0; // sum within each sub-array
    for (int i = 0; i != a.length; ++i) { // iterate over any possible front sub-array...
        sum += a[i]; // ...and determine its element-sum

        int arrayCount = 1; // count the sub-arrays with this element-sum
        int currentSum = 0; // sum in the currently traversed sub-array
        for (int j = i + 1; j != a.length; ++j) {
            currentSum += a[j];

            // if sum matches, we found the end of the currently traversed sub-array
            if (currentSum == sum) {
                arrayCount += 1;
                currentSum = 0;
            }
        }

        // tricky part (see below)
        if (currentSum > 0 || currentSum % sum != 0) {
            continue;
        }

        arrayCount += currentSum / sum;
        if (arrayCount > res) {
            res = arrayCount;
        }
    }

    return res;
}
</code>```

Up until the "tricky part", this should be the naive implementation you'd probably come up with on your first attempt. There is no issue with having negative numbers per se. They will simply reduce currentSum, requiring later elements to again increase it appropriately until eventually - by collecting enough elements - currentSum == sum. At some point (beyond the initialization) currentSum may also be 0 or even something negative. This is no problem either. Particularly, currentSum being 0 only indicates that we're currently traversing through a sub-array that itself has a leading 0-sum sub-array.

The only situation a problem occurs is when we have remaining elements at the end of the array, that together did not form a whole sub-array with element-sum sum - i. e. currentSum is not 0 after the last inner loop iteration. There starts the "tricky part" where we have to distinguish three cases. The remaining elements' sum (i. e. currentSum) is

positive. However, apparently the remaining elements themselves could not be split in a way that yielded sub-arrays with element-sum sum (otherwise that would have happened in the just finished inner for-loop already).

negative with currentSum % sum != 0. Since all elements up to the remaining elements in total have a multiple of sum as the element-sum, the entire array does not have such a multiple as total element-sum.

negative with currentSum % sum == 0.

Each for their individual reason, 1) and 2) render cases in which we cannot have an appropriate partition with the current value of sum at all. In 3) however, we have some negative "overhead" that we can perfectly even-out with some (one or more) of the previously found sub-arrays with element-sum sum each, in total forming a 0-sum sub-array. That sub-array can then be simply seen as appended to the sub-array in front of that (again with element-sum sum), building a joint sub-array still of size sum.

Let's take your second example and look at when we're in outer iteration i = 0 and have just left the inner for-loop. We have arrayCount = 3 (the three individual [2]-arrays), and currentSum = -2, now we can join the "remaining elements" (only the -2) with the last [2] array to form a 0-sum-array and append that to the second-last [2] array. We have in total lost one array to the merge that we previously counted in arrayCount. This is taken into account by arrayCount += currentSum / sum; (note that at this point currentSum is non-positive so the division is non-positive and += is actually correctly decrementing arrayCount). Note that after that line arrayCount could even be negative (or 0) if the remaining elements had a higher negative sum - like -10 (or -6) - but that only tells us, that the whole array's total element-sum had the opposite sign of the current value of sum (or is 0), which again tells us that there is no appropriate partition. In that case however, arrayCount > res just fails and we disregard that iteration.

If you're particularly attentive, you might have wondered about what happens when in some outer iteration sum = 0. This would currently cause an exception but you can easily add a workaround just before the "tricky part":

```<code>if (sum == 0) {
    if (currentSum == 0 && arrayCount > res) {
        res = arrayCount;
    }
    continue;
}
</code>```

or something equivalent. Indeed, in that case, we are in fact not able to even-out the negative "overhead" with any number of previous sum-sum arrays (since sum is 0), since - just like in case 2) above - currentSum is not a multiple of sum.

And since we're already thinking of sum = 0, what's about sum < 0? To also handle that case properly, we only have to change currentSum > 0 to currentSum != 0 && ((currentSum > 0) == (sum > 0))1 since the rest of the code already is sign-unaware regarding currentSum and sum. Go figure!

1: Certainly, at this point we can simplify some logic expressions and if-statements when also regarding the sum = 0 and sum > 0 case.

Body:
I assume the whole array needs to be covered with sub-arrays.

After thinking about it for some time I am pretty confident, that the following O(n^2) algorithm should be valid:

public static int maxSplitCount(int[] a) {

    int res = 0; // highest sub-array count found so far

    int sum = 0; // sum within each sub-array
    for (int i = 0; i != a.length; ++i) { // iterate over any possible front sub-array...
        sum += a[i]; // ...and determine its element-sum

        int arrayCount = 1; // count the sub-arrays with this element-sum
        int currentSum = 0; // sum in the currently traversed sub-array
        for (int j = i + 1; j != a.length; ++j) {
            currentSum += a[j];

            // if sum matches, we found the end of the currently traversed sub-array
            if (currentSum == sum) {
                arrayCount += 1;
                currentSum = 0;
            }
        }

        // tricky part (see below)
        if (currentSum > 0 || currentSum % sum != 0) {
            continue;
        }

        arrayCount += currentSum / sum;
        if (arrayCount > res) {
            res = arrayCount;
        }
    }

    return res;
}

Up until the "tricky part", this should be the naive implementation you'd probably come up with on your first attempt. There is no issue with having negative numbers per se. They will simply reduce currentSum, requiring later elements to again increase it appropriately until eventually - by collecting enough elements - currentSum == sum. At some point (beyond the initialization) currentSum may also be 0 or even something negative. This is no problem either. Particularly, currentSum being 0 only indicates that we're currently traversing through a sub-array that itself has a leading 0-sum sub-array.

The only situation a problem occurs is when we have remaining elements at the end of the array, that together did not form a whole sub-array with element-sum sum - i. e. currentSum is not 0 after the last inner loop iteration. There starts the "tricky part" where we have to distinguish three cases. The remaining elements' sum (i. e. currentSum) is

positive. However, apparently the remaining elements themselves could not be split in a way that yielded sub-arrays with element-sum sum (otherwise that would have happened in the just finished inner for-loop already).

negative with currentSum % sum != 0. Since all elements up to the remaining elements in total have a multiple of sum as the element-sum, the entire array does not have such a multiple as total element-sum.

negative with currentSum % sum == 0.

Each for their individual reason, 1) and 2) render cases in which we cannot have an appropriate partition with the current value of sum at all. In 3) however, we have some negative "overhead" that we can perfectly even-out with some (one or more) of the previously found sub-arrays with element-sum sum each, in total forming a 0-sum sub-array. That sub-array can then be simply seen as appended to the sub-array in front of that (again with element-sum sum), building a joint sub-array still of size sum.

Let's take your second example and look at when we're in outer iteration i = 0 and have just left the inner for-loop. We have arrayCount = 3 (the three individual [2]-arrays), and currentSum = -2, now we can join the "remaining elements" (only the -2) with the last [2] array to form a 0-sum-array and append that to the second-last [2] array. We have in total lost one array to the merge that we previously counted in arrayCount. This is taken into account by arrayCount += currentSum / sum; (note that at this point currentSum is non-positive so the division is non-positive and += is actually correctly decrementing arrayCount). Note that after that line arrayCount could even be negative (or 0) if the remaining elements had a higher negative sum - like -10 (or -6) - but that only tells us, that the whole array's total element-sum had the opposite sign of the current value of sum (or is 0), which again tells us that there is no appropriate partition. In that case however, arrayCount > res just fails and we disregard that iteration.

If you're particularly attentive, you might have wondered about what happens when in some outer iteration sum = 0. This would currently cause an exception but you can easily add a workaround just before the "tricky part":

if (sum == 0) {
    if (currentSum == 0 && arrayCount > res) {
        res = arrayCount;
    }
    continue;
}

or something equivalent. Indeed, in that case, we are in fact not able to even-out the negative "overhead" with any number of previous sum-sum arrays (since sum is 0), since - just like in case 2) above - currentSum is not a multiple of sum.

And since we're already thinking of sum = 0, what's about sum < 0? To also handle that case properly, we only have to change currentSum > 0 to currentSum != 0 && ((currentSum > 0) == (sum > 0))1 since the rest of the code already is sign-unaware regarding currentSum and sum. Go figure!

1: Certainly, at this point we can simplify some logic expressions and if-statements when also regarding the sum = 0 and sum > 0 case.


问:
How to move a React component using CSS ? No functions or classes are working
I am trying to move a button in my appbar to the right. Here is what it looks like:

I have tried 2 ways to fix this:

```<code>    return (
        <AppBar
            position="sticky">
            <Toolbar
                sx = {{background:'black', float:'right'}}
                variant="dense">
                    <CustomButton
                        text='Upload'
                        sx = {{float:'right'}}
                        endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;
</code>```

I also tried to do the same thing with a useStyles hook:

```<code>import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import { makeStyles } from '@material-ui/core/styles';
import {createMuiTheme} from '@material-ui/core/styles';
const useStyles  = makeStyles({
    root: {
        float:'right'
    }
});
const Header = () => {
    const classes = useStyles();
    return (
        <AppBar position="sticky">
            <Toolbar
                sx = {{background:'black'}}
                variant="dense">
                    <CustomButton text='Upload'
                                  className={classes.root}
                                  endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;
</code>```

But none of them have worked and the button won't move to the right.

The code of my button component is as follows:

```<code>import {Button} from '@material-ui/core';
import UploadIcon from '@mui/icons-material/Upload';

const CustomButton = ({float,text, endIcon}) => {

    return (
        <div className='CustomButton'>
            <Button style={{fontWeight: 'bold'}}
                    variant="contained"
                    size='small'
                    endIcon={endIcon}>
                {text}
            </Button>
        </div>
    )
}
export default CustomButton;
</code>```

答:
On the toolbar use following style</p>
```<code>display:flex;
justify-content:flex-end.
</code>```

Body:
I am trying to move a button in my appbar to the right. Here is what it looks like:

I have tried 2 ways to fix this:

    return (
        <AppBar
            position="sticky">
            <Toolbar
                sx = {{background:'black', float:'right'}}
                variant="dense">
                    <CustomButton
                        text='Upload'
                        sx = {{float:'right'}}
                        endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;

I also tried to do the same thing with a useStyles hook:

import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import { makeStyles } from '@material-ui/core/styles';
import {createMuiTheme} from '@material-ui/core/styles';
const useStyles  = makeStyles({
    root: {
        float:'right'
    }
});
const Header = () => {
    const classes = useStyles();
    return (
        <AppBar position="sticky">
            <Toolbar
                sx = {{background:'black'}}
                variant="dense">
                    <CustomButton text='Upload'
                                  className={classes.root}
                                  endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;

But none of them have worked and the button won't move to the right.

The code of my button component is as follows:

import {Button} from '@material-ui/core';
import UploadIcon from '@mui/icons-material/Upload';

const CustomButton = ({float,text, endIcon}) => {

    return (

            <Button style={{fontWeight: 'bold'}}
                    variant="contained"
                    size='small'
                    endIcon={endIcon}>
                {text}
            </Button>

    )
}
export default CustomButton;

Body:
On the toolbar use following style

display:flex;
justify-content:flex-end.


问:
How to access childern of a model in a query set django
I have a model for Products and a model for categories:
Each product can have multiple categories and each category can have multiple sub categories
for example:

categories:

```<code>-Digital devices:
    -laptop
    -smartphone
    -PC
</code>```

products:

```<code>Mylaptop1
    -category=laptop
Myphone2
    -category=smartphone
</code>```

i want to filter products using parent category for example when user reach this address : mysite.com/products/digital-devices i want to show both Mylaptop1 and Myphone2.
I dont have problem with filtering sub categories but how can i filter using parent category in query set.

models.py:

```<code>class Category(models.Model):

    name=models.CharField(max_length=200, db_index=True),
    slug=models.SlugField(max_length=200, unique=True, allow_unicode=True)
    parent = models.ForeignKey('self', default=None, null=True, blank=True,
                                  on_delete=models.SET_NULL,related_name="children")

class Product(models.Model):

    name=models.CharField(max_length=200, db_index=True),
    slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True),
    description=models.TextField(blank=True),
    category = models.ManyToManyField(Category, related_name='products')
</code>```

views.py

```<code>def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
photos = ProductImage.objects.all()

if category_slug:
    category = get_object_or_404(Category,slug=category_slug)

    products = products.filter(category=category) # query for sub categories
    products = products.filter(category__in=[category.children.all]) # i tried to use this query set to get products using parent category but it does not work
</code>```

So how can i access to the products that have children categories using parent category

答:
You can filter sub-category via field parent

```<code>parent_category = Category.objects.get(slug='DigitalDevices')
products = products.filter(
    category__in=Category.objects.filter(parent=parent_category)
)
</code>```

Body:
I have a model for Products and a model for categories:
Each product can have multiple categories and each category can have multiple sub categories
for example:

categories:

-Digital devices:
    -laptop
    -smartphone
    -PC

products:

Mylaptop1
    -category=laptop
Myphone2
    -category=smartphone

i want to filter products using parent category for example when user reach this address : mysite.com/products/digital-devices i want to show both Mylaptop1 and Myphone2.
I dont have problem with filtering sub categories but how can i filter using parent category in query set.

models.py:

class Category(models.Model):

    name=models.CharField(max_length=200, db_index=True),
    slug=models.SlugField(max_length=200, unique=True, allow_unicode=True)
    parent = models.ForeignKey('self', default=None, null=True, blank=True,
                                  on_delete=models.SET_NULL,related_name="children")

class Product(models.Model):

    name=models.CharField(max_length=200, db_index=True),
    slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True),
    description=models.TextField(blank=True),
    category = models.ManyToManyField(Category, related_name='products')

views.py

def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
photos = ProductImage.objects.all()

if category_slug:
    category = get_object_or_404(Category,slug=category_slug)

    products = products.filter(category=category) # query for sub categories
    products = products.filter(category__in=[category.children.all]) # i tried to use this query set to get products using parent category but it does not work

So how can i access to the products that have children categories using parent category

Body:
You can filter sub-category via field parent

parent_category = Category.objects.get(slug='DigitalDevices')
products = products.filter(
    category__in=Category.objects.filter(parent=parent_category)
)


问:
Combining DataAnnotations and IDataErrorInfo for WPF
I am writing a WPF application and I want to use Data Annotations to specify things like Required Fields, Range, etc.

My ViewModel classes use the regular INotifyPropertyChanged interface and I can validate the entire object easily enough using the C# 4 Validator, but I would also like the fields to highlight red if they do not validate properly.  I found this blog post here (http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/28/wpf-data-validation-using-net-data-annotations-part-ii.aspx) that talks about how to write your base view model to implement IDataErrorInfo and simply use the Validator, but the implementation doesn't actually compile nor can I see how it would work. The method in question is this:

```<code>    /// <summary>
    /// Validates current instance properties using Data Annotations.
    /// </summary>
    /// <param name="propertyName">This instance property to validate.</param>
    /// <returns>Relevant error string on validation failure or <see cref="System.String.Empty"/> on validation success.</returns>
    protected virtual string OnValidate(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            throw new ArgumentException("Invalid property name", propertyName);
        }

        string error = string.Empty;
        var value = GetValue(propertyName);
        var results = new List<ValidationResult>(1);
        var result = Validator.TryValidateProperty(
            value,
            new ValidationContext(this, null, null)
            {
                MemberName = propertyName
            },
            results);

        if (!result)
        {
            var validationResult = results.First();
            error = validationResult.ErrorMessage;
        }

        return error;
    }
</code>```

The problem is GetValue is not provided.  He could be talking about the GetValue that comes when you inherit DependencyObject, but the syntax still doesn't work (it expects you to pass DependencyProperty as a parameter) but I'm using regular CLR properties with OnPropertyChanged("MyProperty") being invoked on the setter.

Is there a good way to connect the validation to the IDataErrorInfo interface?

答:
Using your above code as a starting point I got this working through IDataErrorInfo.

Your problem centred around getting the value of the property when you only have the property name, reflection can help here.

```<code>public string this[string property]
{
   get
   {
      PropertyInfo propertyInfo = this.GetType().GetProperty(property);
      var results = new List<ValidationResult>();

      var result = Validator.TryValidateProperty(
                                propertyInfo.GetValue(this, null),
                                new ValidationContext(this, null, null)
                                {
                                  MemberName = property
                                },
                                results);

      if (!result)
      {
        var validationResult = results.First();
        return validationResult.ErrorMessage;
      }

      return string.Empty;
   }
}
</code>```

Body:
I am writing a WPF application and I want to use Data Annotations to specify things like Required Fields, Range, etc.

My ViewModel classes use the regular INotifyPropertyChanged interface and I can validate the entire object easily enough using the C# 4 Validator, but I would also like the fields to highlight red if they do not validate properly.  I found this blog post here (http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/28/wpf-data-validation-using-net-data-annotations-part-ii.aspx) that talks about how to write your base view model to implement IDataErrorInfo and simply use the Validator, but the implementation doesn't actually compile nor can I see how it would work. The method in question is this:

    ///
    /// Validates current instance properties using Data Annotations.
    ///
    /// <param name="propertyName">This instance property to validate.</param>
    /// <returns>Relevant error string on validation failure or <see cref="System.String.Empty"/> on validation success.</returns>
    protected virtual string OnValidate(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            throw new ArgumentException("Invalid property name", propertyName);
        }

        string error = string.Empty;
        var value = GetValue(propertyName);
        var results = new List<ValidationResult>(1);
        var result = Validator.TryValidateProperty(
            value,
            new ValidationContext(this, null, null)
            {
                MemberName = propertyName
            },
            results);

        if (!result)
        {
            var validationResult = results.First();
            error = validationResult.ErrorMessage;
        }

        return error;
    }

The problem is GetValue is not provided.  He could be talking about the GetValue that comes when you inherit DependencyObject, but the syntax still doesn't work (it expects you to pass DependencyProperty as a parameter) but I'm using regular CLR properties with OnPropertyChanged("MyProperty") being invoked on the setter.

Is there a good way to connect the validation to the IDataErrorInfo interface?

Body:
Using your above code as a starting point I got this working through IDataErrorInfo.

Your problem centred around getting the value of the property when you only have the property name, reflection can help here.

public string this[string property]
{
   get
   {
      PropertyInfo propertyInfo = this.GetType().GetProperty(property);
      var results = new List<ValidationResult>();

      var result = Validator.TryValidateProperty(
                                propertyInfo.GetValue(this, null),
                                new ValidationContext(this, null, null)
                                {
                                  MemberName = property
                                },
                                results);

      if (!result)
      {
        var validationResult = results.First();
        return validationResult.ErrorMessage;
      }

      return string.Empty;
   }
}


问:
Functions as a argument
Just started learning python and came across this

```<code>def f(g):
    return g(2)

def square(x):
    return x ** 2

print(f(square)) # which gives 4
</code>```

How does inputting square into the f function equate to 4?

答:
In python functions are first-class values, considered objects as anything else, hence you can pass them as parameters to another function.

In your case, you are "composing" f with g, which in turn has an invocation with fixed 2 inside f. In this sense, f is a function whose purpose is to feed 2 into another function, given as argument.

Knowing that g squares a number, it's easy to see how g(2) is 4, then f(g) will return 4.

Title: Functions as a argument

Body:
Just started learning python and came across this

def f(g):
    return g(2)

def square(x):
    return x ** 2

print(f(square)) # which gives 4

How does inputting square into the f function equate to 4?


问:
Displaying Angle Symbol in HTML
The HTML symbol for angle, ∠ (∠) does not work in IE 6 or 7. What are the other alternatives to display the symbol in Internet Explorer ?</p>

答:
You could use a solution that incorporates both Jamie's and Shoban's answers and adds some conditional comments:

```<code><style type="text/css">
span.ang { display: inline; }
span.ang_ie { display: none; }
</style>
<!--[if IE]>
<style type="text/css">
span.ang { display: none; }
span.ang_ie { display: inline; font-family: Symbol; }
</style>
<![endif]-->

<span class="ang">∠</span><span class="ang_ie">Ð</span>
</code>```

The above works on Windows in IE6, 7 & 8, Firefox 2 & 3, Opera 9.6 and Google Chrome 1.

It does not work in Safari for Windows 3 or 4. Safari for Windows renders a square for ∠ (and ∠). If Safari for Windows support is required, you are going to have to combine JavaScript to detect IE and Safari with  Jamie's replace with image solution.

OwnerDisplayName: Vijay Dev

ContentLicense: CC BY-SA 2.5

Title: Displaying Angle Symbol in HTML

Body:
You could use a solution that incorporates both Jamie's and Shoban's answers and adds some conditional comments:

<style type="text/css">
span.ang { display: inline; }
span.ang_ie { display: none; }
</style>
<!--[if IE]>
<style type="text/css">
span.ang { display: none; }
span.ang_ie { display: inline; font-family: Symbol; }
</style>
<![endif]-->

<span class="ang">&ang;</span><span class="ang_ie">&#208;</span>

The above works on Windows in IE6, 7 & 8, Firefox 2 & 3, Opera 9.6 and Google Chrome 1.

It does not work in Safari for Windows 3 or 4. Safari for Windows renders a square for &ang; (and &#8736;). If Safari for Windows support is required, you are going to have to combine JavaScript to detect IE and Safari with  Jamie's replace with image solution.

OwnerDisplayName: Grant Wagner


问:
Greasemonkey to inject Adfly ads
Is there any way to convert this into Greasemonkey code?

```<code><script>
var adfly_id = 517450;
var adfly_advert = 'banner';
var frequency_cap = 5;
var frequency_delay = 5;
var init_delay = 3;
</script>
<script src="http://adf.ly/js/entry.js"></script>
</code>```

It's a website entry script for adf.ly which when added to a website brings up adf.ly ads.

I want to make a script that will load adf.ly links in the browser while surfing.

Please help!
Thank You :)

答:
You'll need to inject the JS into the page.  Avoid unsafeWindow if you can.

Here's a complete Greasemonkey translation of that script:

```<code>// ==UserScript==
// @name            _adFly why?
// @include         http://YOUR_SITE/YOUR_PATH/*
// ==/UserScript==

function myCode () {
    //--- Set global variables for adFly.
    window.adfly_id         = 517450;
    window.adfly_advert     = 'banner';
    window.frequency_cap    = 5;
    window.frequency_delay  = 5;
    window.init_delay       = 3;
}

addJS_Node (null, null, myCode);
addJS_Node (null, "http://adf.ly/js/entry.js");

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ    = document.getElementsByTagName('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}
</code>```

Title: Greasemonkey to inject Adfly ads

Body:
Is there any way to convert this into Greasemonkey code?

It's a website entry script for adf.ly which when added to a website brings up adf.ly ads.

I want to make a script that will load adf.ly links in the browser while surfing.

Please help!
Thank You :)

Body:
You'll need to inject the JS into the page.  Avoid unsafeWindow if you can.

Here's a complete Greasemonkey translation of that script:

// ==UserScript==
// @name            _adFly why?
// @include         http://YOUR_SITE/YOUR_PATH/*
// ==/UserScript==

function myCode () {
    //--- Set global variables for adFly.
    window.adfly_id         = 517450;
    window.adfly_advert     = 'banner';
    window.frequency_cap    = 5;
    window.frequency_delay  = 5;
    window.init_delay       = 3;
}

addJS_Node (null, null, myCode);
addJS_Node (null, "http://adf.ly/js/entry.js");

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ    = document.getElementsByTagName('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}


问:
Are tuples, list, dictonaries, sets objects of the same class?
I'm learning python online on my own, and I was reading about iterators when this question came out.

Are all iterators objects of one unique class in python, where this class has all the lists, sets, tuple methods?

答:
Iterator is not a type. It's a protocol that different types can implement in their own way. A type is an iterator if it defines a method named __next__ that either returns some value or raises StopIteration when called. The iterator protocol is used by passing an instance of an iterator type to next, which does nothing but invoke its argument's __next__ method.

```<code># Python equivalent to the builtin:
_next_sentinal = object()
def next(obj, default=_next_sentinal):
    try:
        return obj.__next__()
    except StopIteration:
        if default is not _next_sentinal:
            return default
        raise
</code>```

An iterable is another part of the iterator protocol: a class that implements a method named __iter__ that returns a value of some type that implements __next__. The implementation of __iter__ does not have to return the same object that calls the method, or even a value of the same type as the object. (See @kaya's answer for some examples.)

The most common use of the iterator protocol is by a for loop. The code

```<code>for x in foo:
    ...
</code>```

uses foo.__iter__ to get an iterator for foo, then repeatedly calls the foo iterator's __next__ method to get values to assign to x.

Body:
Iterator is not a type. It's a protocol that different types can implement in their own way. A type is an iterator if it defines a method named __next__ that either returns some value or raises StopIteration when called. The iterator protocol is used by passing an instance of an iterator type to next, which does nothing but invoke its argument's __next__ method.

# Python equivalent to the builtin:
_next_sentinal = object()
def next(obj, default=_next_sentinal):
    try:
        return obj.__next__()
    except StopIteration:
        if default is not _next_sentinal:
            return default
        raise

An iterable is another part of the iterator protocol: a class that implements a method named __iter__ that returns a value of some type that implements __next__. The implementation of __iter__ does not have to return the same object that calls the method, or even a value of the same type as the object. (See @kaya's answer for some examples.)

The most common use of the iterator protocol is by a for loop. The code

for x in foo:
    ...

uses foo.__iter__ to get an iterator for foo, then repeatedly calls the foo iterator's __next__ method to get values to assign to x.


问:
GET request processed as HTML rather than TURBO_STREAM from within turbo_frame_tag
I am starting to work with hotwire/turbo and have set everything up.
Turbo streams are working correctly.

Within index.html.erb:

```<code><h1>Tasks</h1>
<%= turbo_stream_from "tasks" %>

<div id="tasks">
  <% @tasks.each do |task| %>
    <%= render task %>
  <% end %>
</div>
</code>```

Within _task.html.erb

```<code><%= turbo_frame_tag dom_id(task) do %>
  <%= link_to 'Edit', edit_task_path(task) %>
  <%= link_to 'Destroy', task, method: :delete, data: { confirm: 'Are you sure?' } %>
  <hr>
<% end %>
</code>```

When the destroy button is pressed as expected, rails console says:

```<code>Started DELETE "/tasks/41" for ::1 at 2021-12-14 18:40:32 +0000
Processing by TasksController#destroy as TURBO_STREAM
</code>```

But when pressing the edit button, rails console says:

```<code>Started GET "/tasks/41/edit" for ::1 at 2021-12-14 18:41:29 +0000
Processing by TasksController#edit as HTML
</code>```

This means the page loads a new page, rendering edit.html.erb rather than just updating the content within the turbo_frame_tag.

When inspecting the DOM, both the edit and destroy links are within a turbo-frame:

```<code><turbo-frame id="task_41">
  <a href="/tasks/41/edit">Edit</a>
  <a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/tasks/41">Destroy</a>
  <hr>
</turbo-frame>
</code>```

So my question is, why does the request get processed as HTML and not TURBO_STREAM ?

edit.html.erb looks like this:

```<code><h1>Editing Task</h1>
<%= turbo_frame_tag dom_id(@task) do %>
    <%= render 'form', task: @task %>
<% end %>
<%= link_to 'Show', @task %> |
<%= link_to 'Back', tasks_path %>
</code>```

Thanks very much!

答:
I have the same issue, and my application doesn't have a require("turbolinks").start() line to remove.

In addition, I feat that when removing that line, every other link_to will be processed as a turbo_stream. And at any point on the development of the application, one will need a link_to that will act as HTML.

Body:
I am starting to work with hotwire/turbo and have set everything up.
Turbo streams are working correctly.

Within index.html.erb:

Tasks

<%= turbo_stream_from "tasks" %>

  <% @tasks.each do |task| %>
    <%= render task %>
  <% end %>

Within _task.html.erb

<%= turbo_frame_tag dom_id(task) do %>
  <%= link_to 'Edit', edit_task_path(task) %>
  <%= link_to 'Destroy', task, method: :delete, data: { confirm: 'Are you sure?' } %>

<% end %>

When the destroy button is pressed as expected, rails console says:

Started DELETE "/tasks/41" for ::1 at 2021-12-14 18:40:32 +0000
Processing by TasksController#destroy as TURBO_STREAM

But when pressing the edit button, rails console says:

Started GET "/tasks/41/edit" for ::1 at 2021-12-14 18:41:29 +0000
Processing by TasksController#edit as HTML

This means the page loads a new page, rendering edit.html.erb rather than just updating the content within the turbo_frame_tag.

When inspecting the DOM, both the edit and destroy links are within a turbo-frame:

<turbo-frame id="task_41">
  Edit
  Destroy

</turbo-frame>

So my question is, why does the request get processed as HTML and not TURBO_STREAM ?

edit.html.erb looks like this:

Editing Task

<%= turbo_frame_tag dom_id(@task) do %>
    <%= render 'form', task: @task %>
<% end %>
<%= link_to 'Show', @task %> |
<%= link_to 'Back', tasks_path %>

Thanks very much!


问:
How to make my cursor behave like a pen in my sketch webpage project?
I set up a grid 16x16 which a white background now i want the divs (grid items) to change color every time i press and hold my mouse and move over them, and to stop changing color when i stop the mousedown event, like in paint. in my script:

```<code>let gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i++){
    let div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    gridContainer.append(div);
    gridArray[i] = div;
}

gridContainer.addEventListener("mousedown", draw)
gridContainer.addEventListener("mouseup",stopDraw)

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

function stopDraw(){
    gridArray.forEach(item => item.removeEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}
</code>```

The hover class is used to change the background color to blue.

I tried multiple other approaches but i always end up at the same place, the draw function not working unless i click which runs the function then it doesnt stop, it keeps running even after i leave the mouse.

Im using vanilla JS, I am still learning the basics.

Here is my code for better understanding my problem: https://codepen.io/ahmedmk11/pen/VwrmyGW

EDIT: I just realized that i didnt explain my problem in a clear way, so the draw function works properly, but my problem is that it doesnt stop working, i need in to only work when im pressing and holding only, like a pen.

答:
Using event listeners is a good approach, to keep with this I have changed your code to use an object. Using an object allows the state of the mouse to be temporarily stored. Using the "canDraw()" method we can read from the object to determine if the mouse event is still occurring. It is still occurring if the key "mousedown" is still present.

The events now just add or remove the key from "mouseEvent" object.

```<code>let gridContainer = document.getElementById('grid-container');
let gridArray = [];
let mouseEvent = {};
for(let i = 0; i < 256; i++){
    let div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    div.addEventListener("mouseover", draw);
    gridContainer.append(div);
    gridArray[i] = div;
}

gridContainer.addEventListener("mousedown", () => mouseEvent.mouseDown = true)
gridContainer.addEventListener("mouseup", () => delete mouseEvent.mouseDown)

function canDraw() {
  return mouseEvent.mouseDown;
}

function draw(e){
    if (canDraw()) {
      e.fromElement.classList.add('hover');
    }
}
</code>```

Body:
I set up a grid 16x16 which a white background now i want the divs (grid items) to change color every time i press and hold my mouse and move over them, and to stop changing color when i stop the mousedown event, like in paint. in my script:

let gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i++){
    let div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    gridContainer.append(div);
    gridArray[i] = div;
}

gridContainer.addEventListener("mousedown", draw)
gridContainer.addEventListener("mouseup",stopDraw)

function draw(){
    gridArray.forEach(item => item.addEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

function stopDraw(){
    gridArray.forEach(item => item.removeEventListener("mouseover", () => {
        (item.classList.add('hover'))
    }));
}

The hover class is used to change the background color to blue.

I tried multiple other approaches but i always end up at the same place, the draw function not working unless i click which runs the function then it doesnt stop, it keeps running even after i leave the mouse.

Im using vanilla JS, I am still learning the basics.

Here is my code for better understanding my problem: https://codepen.io/ahmedmk11/pen/VwrmyGW

EDIT: I just realized that i didnt explain my problem in a clear way, so the draw function works properly, but my problem is that it doesnt stop working, i need in to only work when im pressing and holding only, like a pen.

Body:
Using event listeners is a good approach, to keep with this I have changed your code to use an object. Using an object allows the state of the mouse to be temporarily stored. Using the "canDraw()" method we can read from the object to determine if the mouse event is still occurring. It is still occurring if the key "mousedown" is still present.

The events now just add or remove the key from "mouseEvent" object.

let gridContainer = document.getElementById('grid-container');
let gridArray = [];
let mouseEvent = {};
for(let i = 0; i < 256; i++){
    let div = document.createElement('div');
    div.setAttribute('class', 'grid-item');
    div.addEventListener("mouseover", draw);
    gridContainer.append(div);
    gridArray[i] = div;
}

gridContainer.addEventListener("mousedown", () => mouseEvent.mouseDown = true)
gridContainer.addEventListener("mouseup", () => delete mouseEvent.mouseDown)

function canDraw() {
  return mouseEvent.mouseDown;
}

function draw(e){
    if (canDraw()) {
      e.fromElement.classList.add('hover');
    }
}


问:
how do I cover a window with scalable rects in pygame
how would I go about making the rects be evenly placed throughout the grid while still being scalable. I want to cover the whole window with them and increase how many there are as you scale them down, my intention is to make it look like its zooming out.

```<code>import pygame
import sys

width, height = 750, 750
window = pygame.display.set_mode((width, height))

scale = 1
scroll_scale = .05
while True:
    graph_size = 50 * scale
    graph_count = width / graph_size
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                scale += scroll_scale
            elif event.button == 5 and scale > 0:
                scale -= scroll_scale
    window.fill((255,255,255))
    pygame.draw.rect(window, (0,255,0),(0, 0, graph_size, graph_size))
    pygame.draw.rect(window, (0,255,0),(0 + graph_size, 0, graph_size, graph_size))
    pygame.draw.rect(window, (0,255,0),(0 + graph_size * 2, 0, graph_size, graph_size))
    pygame.display.update()
</code>```

I know there must be a way to do this without drawing all of the rects separately but I just cant seem to find it

答:
Use 2 nested loops and the built-in range function:

import pygame
import sys

width, height = 750, 750
window = pygame.display.set_mode((width, height))

scale = 1
scroll_scale = .05
while True:
    graph_size = 50 * scale
    graph_count = width / graph_size
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                scale += scroll_scale
            elif event.button == 5 and scale > 0:
                scale -= scroll_scale

    window.fill((255,255,255))
    size = round(graph_size)
    for x in range(0, width + size, size):
        for y in range(0, height + size, size):
            c = (0,255,0) if (((x + y) // size) % 2) == 0 else  (127, 127, 127)
            pygame.draw.rect(window, c, (x, y, size, size))
    pygame.display.update()
```

Body:
how would I go about making the rects be evenly placed throughout the grid while still being scalable. I want to cover the whole window with them and increase how many there are as you scale them down, my intention is to make it look like its zooming out.

import pygame
import sys

width, height = 750, 750
window = pygame.display.set_mode((width, height))

scale = 1
scroll_scale = .05
while True:
    graph_size = 50 * scale
    graph_count = width / graph_size
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                scale += scroll_scale
            elif event.button == 5 and scale > 0:
                scale -= scroll_scale
    window.fill((255,255,255))
    pygame.draw.rect(window, (0,255,0),(0, 0, graph_size, graph_size))
    pygame.draw.rect(window, (0,255,0),(0 + graph_size, 0, graph_size, graph_size))
    pygame.draw.rect(window, (0,255,0),(0 + graph_size * 2, 0, graph_size, graph_size))
    pygame.display.update()

I know there must be a way to do this without drawing all of the rects separately but I just cant seem to find it


问:
formArray - Cannot find path to array of arrays
My FormGroup has this structure

```<code>asyncValidator: null
     controls: Object
       arr: FormArray
       asyncValidator: null
         controls: Array[6]
           0: FormGroup
           asyncValidator: null
           controls: Object
             name: FormControl
             pay: FormControl
             scores: FormArray
             asyncValidator: null
              controls: Array[3]
                0: FormControl
                   ...
                   value: 1
                   ...
                1: FormControl
                2: FormControl
                errors: null
                   ...
</code>```

What is the proper html syntax to access the FormControl and values of the "scores" FormArray

I've tried many combinations of the html below without success

```<code>{{myForm.value | json}}
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div formArrayName="arr" *ngFor="let a of myForm.get('arr').controls; let i = index">
    <div [formGroupName]="i" style="margin-bottom: 10px;">
      <input type="text" name="name" formControlName="name">
      <label for="pay">Pay:</label>
      <input type="text" name="pay" formControlName="pay">
      <div [formArrayName]="scores">
      <div  *ngFor="let _ of scores.controls; let g = index">
      <input type="text"  [formControlName]="g">
    </div></div></div></div>
  <button type="submit">Submit</button>
</form>
</code>```

Name and pay are properly returned.

Error reported is

```<code>ERROR
Error: Cannot find control with path: 'arr -> 0 -> '
ERROR
Error: Cannot read properties of undefined (reading 'controls')
</code>```

答:
You can try below html:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

      <input type="text" name="name" formControlName="name">
      Pay:
      <input type="text" name="pay" formControlName="pay">

      <input type="text"  [formControlName]="g">

  <button type="submit">Submit</button>
</form>
```
<p>and define appropriate getter and method to get hold of the FormArray as:</p>
<pre class="lang-ts prettyprint-override"><code>// returns the outer FormArray
get arr(): FormArray {
  return this.myForm.get('arr') as FormArray;
}

// returns the inner FormArray based on the index
scores(index: number): FormArray {
  return this.arr.at(index).get('scores') as FormArray;
}

</code>```

Body:
My FormGroup has this structure

asyncValidator: null
     controls: Object
       arr: FormArray
       asyncValidator: null
         controls: Array[6]
           0: FormGroup
           asyncValidator: null
           controls: Object
             name: FormControl
             pay: FormControl
             scores: FormArray
             asyncValidator: null
              controls: Array[3]
                0: FormControl
                   ...
                   value: 1
                   ...
                1: FormControl
                2: FormControl
                errors: null
                   ...

What is the proper html syntax to access the FormControl and values of the "scores" FormArray

I've tried many combinations of the html below without success

{{myForm.value | json}}
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

      <input type="text" name="name" formControlName="name">
      Pay:
      <input type="text" name="pay" formControlName="pay">

      <input type="text"  [formControlName]="g">

  <button type="submit">Submit</button>
</form>

Name and pay are properly returned.

Error reported is

ERROR
Error: Cannot find control with path: 'arr -> 0 -> '
ERROR
Error: Cannot read properties of undefined (reading 'controls')

Body:
You can try below html:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div formArrayName="arr" *ngFor="let a of arr.controls; let i = index">  <!-- arr getter is called -->
    <div [formGroupName]="i" style="margin-bottom: 10px;">
      <input type="text" name="name" formControlName="name">
      <label for="pay">Pay:</label>
      <input type="text" name="pay" formControlName="pay">
      <div formArrayName="scores"> <!-- Property binding is not required  -->
      <div  *ngFor="let _ of scores(i).controls; let g = index"> <!-- inner FormArray is retrieved based on index -->
      <input type="text"  [formControlName]="g">
    </div></div></div></div>
  <button type="submit">Submit</button>
</form>

and define appropriate getter and method to get hold of the FormArray as:

// returns the outer FormArray
get arr(): FormArray {
  return this.myForm.get('arr') as FormArray;
}

// returns the inner FormArray based on the index
scores(index: number): FormArray {
  return this.arr.at(index).get('scores') as FormArray;
}


问:
fluid grid problem
I have a problem with my first fluid grid layout.
This layout looks displaced(varying width) in the most browsers. It works only in firefox.(not in e.g. chrome or opera)
I don't understand why.

Thanks

<!DOCTYPE html>

    <title>Grid Test</title>

        1/1

        1/3

        1/3

        1/3

        2/3

        1/3

        1/3

        2/3

        1/2

        1/2

        1/4

        1/4

        1/4

        1/4

        2/4

        1/4

        1/4

        1/4

        2/4

        1/4

        1/4

        1/4

        1/4

        1/4

        1/4

        3/4

```

答:
You are on the right track. The reason for differing rendering has to do with pixel rounding which is a problem for all browsers, especially IE.

Check out this fiddle to see compatibility suggestions

Title: fluid grid problem


问:
error when store value in list in variable in bash
i try to run that bash code below to get the value in list and store it in variable then get basename and concatenate with it "lv-" :

```<code>lv_LST=("/usr/sap" "/sapmnt")
lv_size_as_bash=("4" "3")
((L=1))

for n in $(seq 0 $L)
do
    lv_mount = ${lv_LST[$n]};
    lv_size = ${lv_size_as_bash[$n]};
    lvname1=$(sudo basename $lv_mount);
    lvname2='lv-';
    lvname=$lvname2-$lvname1;
</code>```

but i get that error:

```<code>lv_mount: command not found

failed to run commands: exit status 127
</code>```

答:
You have extra spaces

Change

```<code>lv_mount = ${lv_LST[$n]};
lv_size = ${lv_size_as_bash[$n]};
</code>```

To

```<code>lv_mount=${lv_LST[$n]};
lv_size=${lv_size_as_bash[$n]};
</code>```

Body:
i try to run that bash code below to get the value in list and store it in variable then get basename and concatenate with it "lv-" :

lv_LST=("/usr/sap" "/sapmnt")
lv_size_as_bash=("4" "3")
((L=1))

for n in $(seq 0 $L)
do
    lv_mount = ${lv_LST[$n]};
    lv_size = ${lv_size_as_bash[$n]};
    lvname1=$(sudo basename $lv_mount);
    lvname2='lv-';
    lvname=$lvname2-$lvname1;

but i get that error:

lv_mount: command not found

failed to run commands: exit status 127

Body:
You have extra spaces

Change

lv_mount = ${lv_LST[$n]};
lv_size = ${lv_size_as_bash[$n]};

To

lv_mount=${lv_LST[$n]};
lv_size=${lv_size_as_bash[$n]};