问:
Why should I explicitly cast my JASON object as a Map<String, dynamic> in Dart?
If the dart convert package returns a json object, is there any advantage or necessity to casting the converted json to a Map<String, dynamic>? In the code below, I'm taking the response from an api and passing it to a factory that returns a Dart Place object. I'm trying to understand the benefit of casting the json as a map versus passing the result as a json object. Thanks for any insights.</p>
```<code>var parsedJason = convert.jsonDecode(response.body);
var resultObj = parsedJason['result'] as Map<String, dynamic>;
return Place.fromJson(resultObj);
</code>```

答:
As we know, the JSON result for REST API gets outputted as a Map of key: value pairs where the key is always a String and the value can be of any type i.e. dynamic in Dart.

Casting the result as Map<String, dynamic> makes sure that the resultObj variable passed as a parameter in the fromJson() method is of the correct type accepted by the method, thus making the query error prone.

Body:
If the dart convert package returns a json object, is there any advantage or necessity to casting the converted json to a Map<String, dynamic>? In the code below, I'm taking the response from an api and passing it to a factory that returns a Dart Place object. I'm trying to understand the benefit of casting the json as a map versus passing the result as a json object. Thanks for any insights.

var parsedJason = convert.jsonDecode(response.body);
var resultObj = parsedJason['result'] as Map<String, dynamic>;
return Place.fromJson(resultObj);


来源: stackexchange

问:
Why are these values sometimes undefined?
I'm fairly new to Perl and am working on a project to further my learning. It's a little console word game (translated from a python project of mine), and part of the logic requires to draw a random letter from a pool that is 98 characters long.

Running the functions individually, I've never had an issue, but when I try to loop it into a list it occasionally fails. Running with warnings on tells me that some of these are undefined, but I can't for the life of me figure out why. Here's an MRE:

package Random;
sub choice {
  shift;
  my ($str) = @_;
  my $random_index = int(rand(length($str)));
  return substr($str,$random_index,1); #fixed variable name
}
package Player;
sub new {
  my $class = shift;
  my $self = { "name" => shift, "letters" => {fillList()} };
  bless $self, $class;
  return $self;
}
sub drawCharacter {
  my $freq = "aaaaaaaaabbccddddeeeeeeeeeeeeffggghhiiiiiiiiijkllllmmnnnnnnooooooooppqrrrrrrssssttttttuuuuvvwwxyyz";
  my $choice = Random -> choice($freq);
  return $choice;
}
sub fillList {
  my @ls = ();
  for (0..6) {
    push @ls, drawCharacter();
  }
  return @ls;
}
sub getLetters {
  my ($self) = @_;
  my $arr = $self -> {letters};
  return %$arr;
}

package Main;
my @players = ();
for (0..12){
  my $player = Player -> new("Foo");
  print($player->getLetters(),"\n");
}

```

BIG EDIT: Adding the object I'm using. This is verifiably not working. Warnings:
"Use of uninitialized value in print" and "Odd number of elements in anonymous hash". This is where I think the issue lies.

The list returned by fillList sometimes is missing an item or 2, and in some circumstances even 3 or 4 items are missing. Does anybody know what's going on here? The python one hasn't failed once.

If the python analogue would be helpful, I can include that here too.

答:
The error comes from using a hash ref where you should have an array ref:

```<code>my $self = { "name" => shift, "letters" => {fillList()} };
#                                          ^          ^-- wrong brackets
</code>```

This is what the warning talks about:

```<code>Odd number of elements in anonymous hash at foo.pl line 22.
</code>```

You want to change that to:

```<code>my $self = { "name" => shift, "letters" => [fillList()] };
#                                          ^          ^--- creates array ref
</code>```

And also the line which uses this array

```<code>return %$arr;
</code>```

Where you need to change % to @.

```<code>return @$arr;
</code>```

After those fixes, the code runs without errors for me.

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to Perl and am working on a project to further my learning. It's a little console word game (translated from a python project of mine), and part of the logic requires to draw a random letter from a pool that is 98 characters long.

Running the functions individually, I've never had an issue, but when I try to loop it into a list it occasionally fails. Running with warnings on tells me that some of these are undefined, but I can't for the life of me figure out why. Here's an MRE:

package Random;
sub choice {
  shift;
  my ($str) = @_;
  my $random_index = int(rand(length($str)));
  return substr($str,$random_index,1); #fixed variable name
}
package Player;
sub new {
  my $class = shift;
  my $self = { "name" => shift, "letters" => {fillList()} };
  bless $self, $class;
  return $self;
}
sub drawCharacter {
  my $freq = "aaaaaaaaabbccddddeeeeeeeeeeeeffggghhiiiiiiiiijkllllmmnnnnnnooooooooppqrrrrrrssssttttttuuuuvvwwxyyz";
  my $choice = Random -> choice($freq);
  return $choice;
}
sub fillList {
  my @ls = ();
  for (0..6) {
    push @ls, drawCharacter();
  }
  return @ls;
}
sub getLetters {
  my ($self) = @_;
  my $arr = $self -> {letters};
  return %$arr;
}

package Main;
my @players = ();
for (0..12){
  my $player = Player -> new("Foo");
  print($player->getLetters(),"\n");
}

BIG EDIT: Adding the object I'm using. This is verifiably not working. Warnings:
"Use of uninitialized value in print" and "Odd number of elements in anonymous hash". This is where I think the issue lies.

The list returned by fillList sometimes is missing an item or 2, and in some circumstances even 3 or 4 items are missing. Does anybody know what's going on here? The python one hasn't failed once.

If the python analogue would be helpful, I can include that here too.

Body:
The error comes from using a hash ref where you should have an array ref:

my $self = { "name" => shift, "letters" => {fillList()} };
#                                          ^          ^-- wrong brackets

This is what the warning talks about:

Odd number of elements in anonymous hash at foo.pl line 22.

You want to change that to:

my $self = { "name" => shift, "letters" => [fillList()] };
#                                          ^          ^--- creates array ref

And also the line which uses this array

return %$arr;

Where you need to change % to @.

return @$arr;

After those fixes, the code runs without errors for me.


问:
PYTHON 3.9: How can I access attributes of a class being a value of a dict?
I'm writing a python script that I need to check if some automatic-generated code is consistent.

So far I'm stuck trying to compare two strings... Here's the situation

The code I'm trying to read is written in XML. The file being checked is made up like this:

(EDIT: I've been warned that the xml file is not valid written that way. This is not a problem: this file is to be used to configure a very specific embedded system and is actually written as per specification of Ada/C compiler supplier)

```<code><Channel Id="313" Name="Pizza">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Pizza"/>
    </Destination>
</Channel>

<Channel Id="123" Name="Apple_Pie">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Apple_Pie"/>
    </Destination>
</Channel>
</code>```

My goal is to check that:

for each "Channel", "Name" and "Name2" are equal.

The same "Name" does not appear in other "Channel"s

The "Id" is unique for every "Channel"

I'm not using any external library (script must run on corporate PC). I manage to collect the useful tag (I've tried printing them)

After reading my tag, I store them in a Temporary Class. If Goal 1 is satisfied, I will then check if the "Name" or the "Id" tag are already present in previously read "Channel"s, stored in a dict holding the class as value. If all goes well, I copy the temporary Class in a dict of classes.

```<code>Class MyClass():
    Id : int
    Name : str
    Name2 : str

Dict_of_classes : dict = {str:MyClass}
TmpClass = MyClass()

#here I try to check goals 2 & 3

for key in Dict_of_classes:
    if TmpClass.Id == Dict_of_classes[key].Id:
       print("error")

</code>```

thing is: Python reports that the class "MyClass" has no attribute "Id". An AttributeError exception is thrown.

I've tried so far:

Coping Dict_of_classes[key] in a new variable and then comparing: same exception as above

using  for key, value in Dict_of classes:  Python reports that he cannot iterate through a non-iterable object (my class, i think)

Any help is appreciated, thanks!

答:
My goal is to check that:

for each "Channel", "Name" and "Name2" are equal.

The same "Name" does not appear in other "Channel"s

The "Id" is unique for every "Channel"

The below should work for you

```<code>import xml.etree.ElementTree as ET

xml = '''<r>
<Channel Id="313" Name="Pizza">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Pizza"/>
    </Destination>
</Channel>

<Channel Id="123" Name="Pizza">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Apple_Pie"/>
    </Destination>
</Channel>

<Channel Id="123" Name="XYZ">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="XYZ"/>
    </Destination>
</Channel>
</r>'''

ids = set()
names = set()
root = ET.fromstring(xml)
channels = root.findall('Channel')
for c in channels:
  name1 = c.attrib['Name']
  name2 = c.find('.//Some_Tag').attrib['Name2']
  if name1 != name2:
    print(f'{name1} != {name2}')
  names.add(name1)
  ids.add(c.attrib['Id'])
if len(ids) != len(channels):
  print('We have Id duplications')
if len(names) != len(channels):
  print('We have Name duplications')
</code>```

Body:
I'm writing a python script that I need to check if some automatic-generated code is consistent.

So far I'm stuck trying to compare two strings... Here's the situation

The code I'm trying to read is written in XML. The file being checked is made up like this:

(EDIT: I've been warned that the xml file is not valid written that way. This is not a problem: this file is to be used to configure a very specific embedded system and is actually written as per specification of Ada/C compiler supplier)

<Channel Id="313" Name="Pizza">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Pizza"/>
    </Destination>
</Channel>

<Channel Id="123" Name="Apple_Pie">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Apple_Pie"/>
    </Destination>
</Channel>

My goal is to check that:

for each "Channel", "Name" and "Name2" are equal.

The same "Name" does not appear in other "Channel"s

The "Id" is unique for every "Channel"

I'm not using any external library (script must run on corporate PC). I manage to collect the useful tag (I've tried printing them)

After reading my tag, I store them in a Temporary Class. If Goal 1 is satisfied, I will then check if the "Name" or the "Id" tag are already present in previously read "Channel"s, stored in a dict holding the class as value. If all goes well, I copy the temporary Class in a dict of classes.

Class MyClass():
    Id : int
    Name : str
    Name2 : str

Dict_of_classes : dict = {str:MyClass}
TmpClass = MyClass()

#here I try to check goals 2 & 3

for key in Dict_of_classes:
    if TmpClass.Id == Dict_of_classes[key].Id:
       print("error")

thing is: Python reports that the class "MyClass" has no attribute "Id". An AttributeError exception is thrown.

I've tried so far:

Coping Dict_of_classes[key] in a new variable and then comparing: same exception as above

using  for key, value in Dict_of classes:  Python reports that he cannot iterate through a non-iterable object (my class, i think)

Any help is appreciated, thanks!

Body:
My goal is to check that:

for each "Channel", "Name" and "Name2" are equal.

The same "Name" does not appear in other "Channel"s

The "Id" is unique for every "Channel"

The below should work for you

import xml.etree.ElementTree as ET

xml = '''<r>
<Channel Id="313" Name="Pizza">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Pizza"/>
    </Destination>
</Channel>

<Channel Id="123" Name="Pizza">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="Apple_Pie"/>
    </Destination>
</Channel>

<Channel Id="123" Name="XYZ">
    <Source>
    </Source>
    <Destination>
        <Some_Tag Cola="3" FunnyName="Lasagna" Name2="XYZ"/>
    </Destination>
</Channel>
</r>'''

ids = set()
names = set()
root = ET.fromstring(xml)
channels = root.findall('Channel')
for c in channels:
  name1 = c.attrib['Name']
  name2 = c.find('.//Some_Tag').attrib['Name2']
  if name1 != name2:
    print(f'{name1} != {name2}')
  names.add(name1)
  ids.add(c.attrib['Id'])
if len(ids) != len(channels):
  print('We have Id duplications')
if len(names) != len(channels):
  print('We have Name duplications')


问:
prevent bootstrap modal from opening when a button is clicked
I have a page with several bootstrap modals with:

```<code>data-toggle="modal" data-target="#modal-12345"
</code>```

The problem is, I have an entire table row that is clickable, like

```<code><tr data-toggle="modal" data-target="#modal-12345">
</code>```

The modal content is in another hidden table row right below, followed by the next clickable row and so on. Now, this row also contains a button that will go to another page when clicked.

I need the entire row clickable so it opens the modal, except when the button to go to the other page is clicked, then I need to stop the modal from opening.

I need something like this

```<code><script>
$('.ID').on('click', '.btn', function(e) { e.stopPropagation(); })
</script>
</code>```

But targeting this:

```<code>data-toggle="modal"
</code>```

I also tried giving the TR a class of "modaltoggle" and then calling it with the javascript as .modaltoggle but that didn't work either.

答:
Remove following line from your code:

data-toggle = "modal"

Then, in your function once your validation is done, write following code:

```<code>$('#myModal').modal({
   show: 'true'
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a page with several bootstrap modals with:

data-toggle="modal" data-target="#modal-12345"

The problem is, I have an entire table row that is clickable, like

The modal content is in another hidden table row right below, followed by the next clickable row and so on. Now, this row also contains a button that will go to another page when clicked.

I need the entire row clickable so it opens the modal, except when the button to go to the other page is clicked, then I need to stop the modal from opening.

I need something like this

But targeting this:

data-toggle="modal"

I also tried giving the TR a class of "modaltoggle" and then calling it with the javascript as .modaltoggle but that didn't work either.

Body:
Remove following line from your code:

data-toggle = "modal"

Then, in your function once your validation is done, write following code:

$('#myModal').modal({
   show: 'true'
});


问:
access database from multiple kubernetes pods

I have 2 applications in 2 pods as well as a Postgres db deployed using a helm chart. The one application writes to the database and the other one uses only select operation for read. Is there any case where I can get a race condition?

2)

Is there any way to have both read and write to the above database from 2 different pods hosting different applications?

答:
If only one of the two applications will be writing to the database, there should not be any risk of a race condition.

Yes, you can define two pods for the two applications and have them both connect to the database. You could create a helm subchart for each application, define the Postgresql connection details in a ConfigMap in the parent chart, and then have each subchart's deployment load the ConfigMap as environment variables so your applications can connect to the database.


问:
Safely hooking C functions into assembly
I'm trying to put some C hooks into some code that someone else wrote in asm. I don't know much about x86 asm and I want to make sure I'm doing this safely.

So far I've got this much:

```<code>EXTERN _C_func

CALL _C_func
</code>```

And that seems to work, but I'm sure that's dangerous as-is. At the very least it could be destroying EAX, and possibly more.

So I think all I need to know is: Which registers does C destroy and how do I ensure the registers are being saved properly? Is there anything else I can do to make sure I can safely insert hooks into arbitrary locations?

I'm using Visual Studio for the C functions, if that helps.
Thank you.

UPDATE:

I looked up the "paranoid" method several people suggested and it looks like this:

```<code>pushfd
pushad
call _C_func
popad
popfd
</code>```

AD = (A)ll general registers

FD = (F)lags

(I'm not sure what the 'd' stands for, but it means 32-bit registers instead of 16-bit.)

But the most efficient method is illustrated in Kragen's answer below. (Assuming you don't need the preserve the flags. If you do, add the FD instructions.)

Also, be careful about allocating lots of stack variables in your C function as it could overrun the asm subroutine's stack space.

I think that about does it, thanks for you help everyone!

答:
You need to be aware of calling conventions. See this article for a discussion on calling conventions.

If you are paranoid about registers, you can always push all registers onto the stack before calling the function (functions shouldn't return without cleaning up, except for those registers that carry return information).

Body:
I'm trying to put some C hooks into some code that someone else wrote in asm. I don't know much about x86 asm and I want to make sure I'm doing this safely.

So far I've got this much:

EXTERN _C_func

CALL _C_func

And that seems to work, but I'm sure that's dangerous as-is. At the very least it could be destroying EAX, and possibly more.

So I think all I need to know is: Which registers does C destroy and how do I ensure the registers are being saved properly? Is there anything else I can do to make sure I can safely insert hooks into arbitrary locations?

I'm using Visual Studio for the C functions, if that helps.
Thank you.

UPDATE:

I looked up the "paranoid" method several people suggested and it looks like this:

pushfd
pushad
call _C_func
popad
popfd

AD = (A)ll general registers

FD = (F)lags

(I'm not sure what the 'd' stands for, but it means 32-bit registers instead of 16-bit.)

But the most efficient method is illustrated in Kragen's answer below. (Assuming you don't need the preserve the flags. If you do, add the FD instructions.)

Also, be careful about allocating lots of stack variables in your C function as it could overrun the asm subroutine's stack space.

I think that about does it, thanks for you help everyone!


问:
How to add values in rows and pass the result to the next column using pandas?
I have a pandas dataframe with the values as follows:

```<code>Start  end   Depart  Duration
  A     B      5           2
  B     C      5           3
  C     D      5           6
  D     E      5           4
</code>```

I want the output as shown below. I need to add rows of 'Depart' and 'Duration' to form a new column 'Arrive' and pass the result value to the next row in Depart column and then add with Duration to form a value in Arrive and repeat the process again.

I also need to verify if the column values 'Start' is same as the 'End' value in previous row.

```<code>Start  end     Depart   Arrive
  A     B        5          7
  B     C        7          10
  C     D        10         16
  D     E        16         20
</code>```

I tried something like this:

```<code>if np.where(d.Start == d.End):
    d['Arrive'] = d['Depart'] + d['Duration']
    d['Depart'] = d.Arrive.shift(1)
    print(d)
</code>```

The output is as follows. It still takes the original Depart value as 5 and adds up to give the result. Where am I going wrong?

```<code>  Start End  Depart  Duration  Arrive
0     A   B     NaN         2       7
1     B   C     7.0         3       8
2     C   D     8.0         6      11
3     D   E    11.0         4       9
</code>```

答:
Try using cumsum:

```<code>depart = df['Depart'] + df['Duration'].cumsum().shift(1).fillna(0).astype(int)
arrival = df['Depart'] + df['Duration'].cumsum()

df['Depart'] = depart
df['Arrival'] = arrival
df = df.drop('Duration', axis=1)
</code>```

Output:

```<code>>>> df
  Start end  Depart  Arrival
0     A   B       5        7
1     B   C       7       10
2     C   D      10       16
3     D   E      16       20
</code>```

Body:
I have a pandas dataframe with the values as follows:

Start  end   Depart  Duration
  A     B      5           2
  B     C      5           3
  C     D      5           6
  D     E      5           4

I want the output as shown below. I need to add rows of 'Depart' and 'Duration' to form a new column 'Arrive' and pass the result value to the next row in Depart column and then add with Duration to form a value in Arrive and repeat the process again.

I also need to verify if the column values 'Start' is same as the 'End' value in previous row.

Start  end     Depart   Arrive
  A     B        5          7
  B     C        7          10
  C     D        10         16
  D     E        16         20

I tried something like this:

if np.where(d.Start == d.End):
    d['Arrive'] = d['Depart'] + d['Duration']
    d['Depart'] = d.Arrive.shift(1)
    print(d)

The output is as follows. It still takes the original Depart value as 5 and adds up to give the result. Where am I going wrong?

  Start End  Depart  Duration  Arrive
0     A   B     NaN         2       7
1     B   C     7.0         3       8
2     C   D     8.0         6      11
3     D   E    11.0         4       9

Body:
Try using cumsum:

depart = df['Depart'] + df['Duration'].cumsum().shift(1).fillna(0).astype(int)
arrival = df['Depart'] + df['Duration'].cumsum()

df['Depart'] = depart
df['Arrival'] = arrival
df = df.drop('Duration', axis=1)

Output:

>>> df
  Start end  Depart  Arrival
0     A   B       5        7
1     B   C       7       10
2     C   D      10       16
3     D   E      16       20


问:
Selecting chapters, section and subsection with google sheets with drop down list
we have currently a large number of exercises (for math) that need to be categorized according to an existing table of contents. Each exercise has a unique number. This number should be placed into the table of contents. The depth of the toc is 3, so we have chapters, sections and subsections.

I want three drop down lists for each of the (many) exercises. The first one selects the chapter, the second the section, and the third the subsection. I can solve this with two filtered lists that depend on certain filtering of a list seperated into chapter, section, subsection. That works fine for few exercises. But, i have to make the filtered lists for each exercise seperately. That is exactly the problem. I do not want to maintain 500 lists (two per exercise)

Is there any way to hardcode this? I do not want to scroll through the many subsections each time and I need a error control. So, one should not be able to select chapter 3 and then subsection 3 from chapter 4.

EDIT: Link to Google Sheet:
https://docs.google.com/spreadsheets/d/e/2PACX-1vSsRqFlLIkpgIrw18GBDLdUEl0FFmF5hSXIe2oAXztz9N50VNiO0eCP3cAB20KOgHU4nfH6gBFCWmyT/pubhtml

答:
1. Separate the data and the dropdows

That's a best practice, because you will need to have some auxiliary cells to create the dependency

2. Create a simple data validation dropdown

Do it for the first column in a separate sheet

3. Create the auxiliary cells

Filter the second column with the values you have in the data validation to show the values adjacent to the first column

```<code>=FILTER(B2:B,A2:A=Dropdowns!$A$2)
</code>```

4. Repeat the process with as many columns you have

Here is the sample spreadsheet for you to have an idea how to implement it
https://docs.google.com/spreadsheets/d/1VPsx1hfKuZDifMgrREOvUb4xEIvbVODnKPuRDWZUOF8/edit?usp=sharing

Update

I'm working on a script, I created two functions, at the moment they're not achieving the step you want, but I'm thinking on looping the number of columns as the same way I'm doing it with the rows.

const menuSheet = 'Values';
const dataSheet = 'Data';
const wsValues = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(menuSheet);
const wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(dataSheet);
const data = wsData.getRange(2, 1, wsData.getLastRow() - 1, 3).getValues();
let firstCol = 1;
let secondCol = 2;
let thirdCol = 3;

/*
function setDropdownDependenciesTest() {
  const list = ['a', 'b']
  const cell = wsValues.getRange('C2')

  setDropdownDependencies(list, cell)

}
*/

function onEdit(e) {
  const activeCell = e.range
  let val = activeCell.getValue()
  let row = activeCell.getRow()
  let column = activeCell.getColumn()
  let wsName = activeCell.getSheet().getName()
  if (wsName === menuSheet && column === firstCol && row > 1) {
    applyFirstValidation(val, row)
  } else if (wsName == menuSheet && column === secondCol && row > 1) {
    applySecondValidation(val, row)
  }
}

function applyFirstValidation(val, row) {
  if (val === "") {
    wsValues.getRange(row, secondCol).clearContent()
    wsValues.getRange(row, secondCol).clearDataValidations()
    wsValues.getRange(row, thirdCol).clearContent()
    wsValues.getRange(row, thirdCol).clearDataValidations()
  } else {
    wsValues.getRange(row, secondCol).clearContent()
    wsValues.getRange(row, secondCol).clearDataValidations()
    wsValues.getRange(row, thirdCol).clearContent()
    wsValues.getRange(row, thirdCol).clearDataValidations()
    let filteredData = data.filter(info => {
      return info[0] === val;
    })

    let listToApply = filteredData.map(info => {
      return info[1]
    })

    let cell = wsValues.getRange(row, secondCol)
    setDropdownDependencies(listToApply, cell)
  }
}

function applySecondValidation(val, row) {
  if (val === "") {
    wsValues.getRange(row, thirdCol).clearContent()
    wsValues.getRange(row, thirdCol).clearDataValidations()
  } else {
    wsValues.getRange(row, thirdCol).clearContent()
    let firstColValue = wsValues.getRange(row, firstCol).getValue()
    let filteredData = data.filter(info => {
      return info[0] === firstColValue && info[1] === val;
    })

    let listToApply = filteredData.map(info => {
      return info[2]
    })

    let cell = wsValues.getRange(row, thirdCol)
    setDropdownDependencies(listToApply, cell)
  }
}

function setDropdownDependencies(list, cell) {

  const rule = SpreadsheetApp
    .newDataValidation()
    .requireValueInList(list)
    .setAllowInvalid(false)
    .build()

  cell.setDataValidation(rule)
}```

Body:
1. Separate the data and the dropdows

That's a best practice, because you will need to have some auxiliary cells to create the dependency

2. Create a simple data validation dropdown

Do it for the first column in a separate sheet

3. Create the auxiliary cells

Filter the second column with the values you have in the data validation to show the values adjacent to the first column

=FILTER(B2:B,A2:A=Dropdowns!$A$2)

4. Repeat the process with as many columns you have

Here is the sample spreadsheet for you to have an idea how to implement it
https://docs.google.com/spreadsheets/d/1VPsx1hfKuZDifMgrREOvUb4xEIvbVODnKPuRDWZUOF8/edit?usp=sharing

Update

I'm working on a script, I created two functions, at the moment they're not achieving the step you want, but I'm thinking on looping the number of columns as the same way I'm doing it with the rows.

const menuSheet = 'Values';
const dataSheet = 'Data';
const wsValues = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(menuSheet);
const wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(dataSheet);
const data = wsData.getRange(2, 1, wsData.getLastRow() - 1, 3).getValues();
let firstCol = 1;
let secondCol = 2;
let thirdCol = 3;

/*
function setDropdownDependenciesTest() {
  const list = ['a', 'b']
  const cell = wsValues.getRange('C2')

  setDropdownDependencies(list, cell)

}
*/

function onEdit(e) {
  const activeCell = e.range
  let val = activeCell.getValue()
  let row = activeCell.getRow()
  let column = activeCell.getColumn()
  let wsName = activeCell.getSheet().getName()
  if (wsName === menuSheet && column === firstCol && row > 1) {
    applyFirstValidation(val, row)
  } else if (wsName == menuSheet && column === secondCol && row > 1) {
    applySecondValidation(val, row)
  }
}

function applyFirstValidation(val, row) {
  if (val === "") {
    wsValues.getRange(row, secondCol).clearContent()
    wsValues.getRange(row, secondCol).clearDataValidations()
    wsValues.getRange(row, thirdCol).clearContent()
    wsValues.getRange(row, thirdCol).clearDataValidations()
  } else {
    wsValues.getRange(row, secondCol).clearContent()
    wsValues.getRange(row, secondCol).clearDataValidations()
    wsValues.getRange(row, thirdCol).clearContent()
    wsValues.getRange(row, thirdCol).clearDataValidations()
    let filteredData = data.filter(info => {
      return info[0] === val;
    })

    let listToApply = filteredData.map(info => {
      return info[1]
    })

    let cell = wsValues.getRange(row, secondCol)
    setDropdownDependencies(listToApply, cell)
  }
}

function applySecondValidation(val, row) {
  if (val === "") {
    wsValues.getRange(row, thirdCol).clearContent()
    wsValues.getRange(row, thirdCol).clearDataValidations()
  } else {
    wsValues.getRange(row, thirdCol).clearContent()
    let firstColValue = wsValues.getRange(row, firstCol).getValue()
    let filteredData = data.filter(info => {
      return info[0] === firstColValue && info[1] === val;
    })

    let listToApply = filteredData.map(info => {
      return info[2]
    })

    let cell = wsValues.getRange(row, thirdCol)
    setDropdownDependencies(listToApply, cell)
  }
}

function setDropdownDependencies(list, cell) {

  const rule = SpreadsheetApp
    .newDataValidation()
    .requireValueInList(list)
    .setAllowInvalid(false)
    .build()

  cell.setDataValidation(rule)
}


问:
file_get_contents - Connection timed out
```<code><?php
$a = file_get_contents('http://www.google.com');
echo $
</code>```

Why is the browser returning this error?

```<code>Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: Connection timed out in /home/test.php on line 2
</code>```

答:
For some reason file_get_contents() fails intermittently on some websites that support IPv6 (maybe 20% of the time, the command times-out).  Although disabling IPv6 resolves the issue, that is not the best solution as more sites move to IPv6.

I wrote a simple PHP gethtml() function that works around the issue using wget.  This will automatically use IPv6 when IPv4 is not available.  A minor drawback is that it uses an external command, but I think it is preferable to disabling IPv6.

If wget is not already installed on your distribution, you can install it as follows:

```<code>sudo apt install wget
</code>```

PHP Function Example:

```<code>$myhtml = gethtml("http://example.com");

//use instead of file_get_contents() due to inconsistent IPv6 performance
function gethtml($url){return shell_exec("wget --prefer-family=IPv4 -qO- ".$url);}
</code>```

Body:
<?php
$a = file_get_contents('http://www.google.com');
echo $

Why is the browser returning this error?

Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: Connection timed out in /home/test.php on line 2

Body:
For some reason file_get_contents() fails intermittently on some websites that support IPv6 (maybe 20% of the time, the command times-out).  Although disabling IPv6 resolves the issue, that is not the best solution as more sites move to IPv6.

I wrote a simple PHP gethtml() function that works around the issue using wget.  This will automatically use IPv6 when IPv4 is not available.  A minor drawback is that it uses an external command, but I think it is preferable to disabling IPv6.

If wget is not already installed on your distribution, you can install it as follows:

sudo apt install wget

PHP Function Example:

$myhtml = gethtml("http://example.com");

//use instead of file_get_contents() due to inconsistent IPv6 performance
function gethtml($url){return shell_exec("wget --prefer-family=IPv4 -qO- ".$url);}


问:
handling events for buttons in a graphical calculator in assembler
I'm working on making a simple calculator (+,-,*,/) in assembler.

My task is to make it in the form of a graphics program.

At this stage, I created the layout. Right now I have 4 buttons and two input fields for numbers.

I am trying to do it like this:

The user enters two numbers into the text fields.

Next, you need to click on the arithmetic operation on the button.

And in the end, the result should appear somewhere on the screen.

I don't understand how to make the event handler correctly and add the appropriate action button.

```<code>.586P
.MODEL flat, STDCALL
include grafika.inc
CSstyle EQU CS_HREDRAW+CS_VREDRAW+CS_GLOBALCLASS
BSstyle EQU BS_PUSHBUTTON+WS_VISIBLE+WS_CHILD+WS_TABSTOP
WNDstyle EQU WS_CLIPCHILDREN OR WS_OVERLAPPEDWINDOW OR \
 WS_HSCROLL OR WS_VSCROLL
EDTstyle EQU WS_VISIBLE+WS_CHILD+WS_TABSTOP+WS_BORDER
kolor EQU 000000FFh ; czerwony ; kolory: G B R
_DATA SEGMENT
hwnd DD 0
hinst DD 0
hdc DD 0
hbutt DD 0
hedt DD 0
hbrush DD 0
holdbrush DD 0
msg MSGSTRUCT <?>
wndc WNDCLASS <?>
naglow DB "Simple calculator",0
rozmN DD $ - naglow
ALIGN 4
puste DB "_____________________" ;
rozmP DD $ - puste
ALIGN 4
tytul DB "App",0
ALIGN 4
cname DB "MainClass", 0
ALIGN 4
MES1 DB "Lewy, myszy",0
ALIGN 4
tbutt DB "BUTTON", 0
ALIGN 4

tbutt2 DB "BUTTON", 0
ALIGN 4
tbutt3 DB "BUTTON", 0
ALIGN 4
tbutt4 DB "BUTTON", 0
ALIGN 4

tstart DB "add", 0
ALIGN 4

tstart2 DB "sub", 0
ALIGN 4

tstart3 DB "mul", 0
ALIGN 4

tstart4 DB "div", 0
ALIGN 4

tedt DB "EDIT", 0
ALIGN 4

tedt2 DB "EDIT", 0
ALIGN 4

tnazwaedt DB " ", 0
ALIGN 4
ttekst DB "text", 0
ALIGN 4
nagl DB "text", 0
ALIGN 4
terr DB "error!", 0
ALIGN 4
terr2 DB "error!", 0
ALIGN 4
bufor DB 128 dup(' ')
rbuf DD 128
znaczn DD 0
rt RECT <120,50,210,90>
rr DD 0
_DATA ENDS
_TEXT SEGMENT
WndProc PROC
; DWORD PTR [EBP+14h] - parametr LPARAM komunikatu
; DWORD PTR [EBP+10h] - parametr WPARAM komunikatu
; DWORD PTR [EBP+0Ch] - ID = identyfikator komunikatu
; DWORD PTR [EBP+08h] - HWND = deskryptor okna
;------------------------------------
push EBP
mov EBP, ESP
push EBX
push ESI
push EDI
cmp DWORD PTR [EBP+0Ch], WM_CREATE
jne @F
jmp wmCREATE
@@:
cmp DWORD PTR [EBP+0Ch], WM_DESTROY
jne @F
jmp wmDESTROY
@@:
cmp DWORD PTR [EBP+0CH], WM_COMMAND
jne @F
jmp wmCOMMAND
@@:
cmp DWORD PTR [EBP+0CH], WM_LBUTTONDOWN
jne @F
jmp wmLBUTTON
@@:
cmp DWORD PTR [EBP+0CH], WM_RBUTTONDOWN
jne @F
jmp wmRBUTTON
@@:
INVOKE DefWindowProcA, DWORD PTR [EBP+08h], \
 DWORD PTR [EBP+0Ch], DWORD PTR [EBP+10h], \
 DWORD PTR [EBP+14h]
jmp konWNDPROC
wmCREATE:
INVOKE CreateWindowExA, 0, OFFSET tbutt, OFFSET tstart, \
 BSstyle, 10, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX

INVOKE CreateWindowExA, 0, OFFSET tbutt2, OFFSET tstart2, \
 BSstyle, 110, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX

INVOKE CreateWindowExA, 0, OFFSET tbutt3, OFFSET tstart3, \
 BSstyle, 210, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX

INVOKE CreateWindowExA, 0, OFFSET tbutt4, OFFSET tstart4, \
 BSstyle, 310, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX
INVOKE CreateWindowExA, 0, OFFSET tedt, OFFSET tnazwaedt, EDTstyle, 110, 100, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hedt, EAX

INVOKE CreateWindowExA, 0, OFFSET tedt2, OFFSET tnazwaedt, EDTstyle, 210, 100, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hedt, EAX
INVOKE CreateSolidBrush,kolor
mov hbrush,EAX
mov EAX,0
jmp konWNDPROC
wmDESTROY:
INVOKE DeleteObject, hbrush
INVOKE PostQuitMessage, 0
mov EAX, 0
jmp konWNDPROC
wmCOMMAND:
mov EAX,hbutt
cmp EAX,DWORD PTR [EBP+14h]
je @F
jmp et1
@@:
cmp znaczn,1
je @F
mov znaczn,1
INVOKE SelectObject,hDC,hbrush
mov holdbrush,EAX
INVOKE FillRect,hDC,OFFSET rt,hbrush
mov EAX, 0
jmp konWNDPROC
@@:
mov znaczn,0
INVOKE SelectObject,hDC,holdbrush
mov hbrush,EAX
INVOKE FillRect,hDC,OFFSET rt,holdbrush
mov EAX, 0
jmp konWNDPROC
et1:
jmp konWNDPROC
wmRBUTTON:
jmp wmDESTROY
wmLBUTTON:
INVOKE SendMessageA,hedt,WM_GETTEXT,128,OFFSET bufor
mov rr,EAX
INVOKE TextOutA,hDC,110,120,OFFSET bufor,rr
mov EAX,0
jmp konWNDPROC
konWNDPROC:
pop EDI
pop ESI
pop EBX
mov ESP,EBP
pop EBP
ret 16
WndProc ENDP
main:
INVOKE GetModuleHandleA, 0
mov hinst, EAX
mov EAX, hinst
mov [wndc.clsHInstance], EAX
mov [wndc.clsStyle], CSstyle
mov [wndc.clsLpfnWndProc], OFFSET WndProc
mov [wndc.clsCbClsExtra], 0
mov [wndc.clsCbWndExtra], 0
INVOKE LoadIconA, 0, IDI_APPLICATION ; ikona
mov [wndc.clsHIcon], EAX
INVOKE LoadCursorA, 0, IDC_ARROW ; kursor
mov [wndc.clsHCursor], EAX
INVOKE GetStockObject, WHITE_BRUSH ; tło
mov [wndc.clsHbrBackground], EAX
mov [wndc.clsLpszMenuName], 0
mov DWORD PTR [wndc.clsLpszClassName], OFFSET cname
INVOKE RegisterClassA, OFFSET wndc
cmp EAX, 0
jne @F
jmp err0
@@:
INVOKE CreateWindowExA, 0, OFFSET cname, OFFSET tytul, \
 WNDstyle, 50, 50, 455, 400, 0, 0, hinst, 0
cmp EAX, 0
jne @F
jmp err2
@@:
mov hwnd, EAX
INVOKE ShowWindow, hwnd, SW_SHOWNORMAL
INVOKE GetDC,hwnd
mov hdc,EAX
INVOKE lstrlenA,OFFSET naglow
mov rozmN,EAX
INVOKE TextOutA,hDC,10,20,OFFSET naglow,rozmN
INVOKE UpdateWindow, hwnd
msgloop:
INVOKE GetMessageA, OFFSET msg, 0, 0, 0
cmp EAX, 0
jne @F
jmp etkon
@@:
cmp EAX, -1
jne @F
jmp err0
@@:
INVOKE TranslateMessage, OFFSET msg
INVOKE DispatchMessageA, OFFSET msg
jmp msgloop
err0:
INVOKE MessageBoxA,0,OFFSET terr,OFFSET nagl,0
jmp etkon
err2:
INVOKE MessageBoxA,0,OFFSET terr2,OFFSET nagl,0
jmp etkon
etkon:
INVOKE ExitProcess, [msg.msWPARAM]
_TEXT ENDS
END main

</code>```

A few more notes on my code:

I am using Visual Studio 2019 compiler

To compile the code, you need to consider the following factors:

a) For graphic assembler, you need a file in which there will be data with graphics

b) In order for the program to start in the settings, you need to set the entry point -> main

c) In the project settings, select (Build Customization -> masm(.targets, .props))

答:
In your wmCOMMAND code, once you know which button was pressed you convert the two text boxes to integer values, perform the operation, then show the result.
To differentiate between buttons you usually give each a unique ID when you create them (the confusingly named hMenu), WM_COMMAND stores it in the low word of wParam.
A couple of hints, when you create your buttons each one gets a different window handle but you are overwriting them, so wmCommand will only continue for the last button created - use hbutt,hbutt2/3/4. In the same way, one class string only is needed so you can delete tbutt2/3/4.</p>

Body:
I'm working on making a simple calculator (+,-,*,/) in assembler.

My task is to make it in the form of a graphics program.

At this stage, I created the layout. Right now I have 4 buttons and two input fields for numbers.

I am trying to do it like this:

The user enters two numbers into the text fields.

Next, you need to click on the arithmetic operation on the button.

And in the end, the result should appear somewhere on the screen.

I don't understand how to make the event handler correctly and add the appropriate action button.

.586P
.MODEL flat, STDCALL
include grafika.inc
CSstyle EQU CS_HREDRAW+CS_VREDRAW+CS_GLOBALCLASS
BSstyle EQU BS_PUSHBUTTON+WS_VISIBLE+WS_CHILD+WS_TABSTOP
WNDstyle EQU WS_CLIPCHILDREN OR WS_OVERLAPPEDWINDOW OR \
 WS_HSCROLL OR WS_VSCROLL
EDTstyle EQU WS_VISIBLE+WS_CHILD+WS_TABSTOP+WS_BORDER
kolor EQU 000000FFh ; czerwony ; kolory: G B R
_DATA SEGMENT
hwnd DD 0
hinst DD 0
hdc DD 0
hbutt DD 0
hedt DD 0
hbrush DD 0
holdbrush DD 0
msg MSGSTRUCT <?>
wndc WNDCLASS <?>
naglow DB "Simple calculator",0
rozmN DD $ - naglow
ALIGN 4
puste DB "_____________________" ;
rozmP DD $ - puste
ALIGN 4
tytul DB "App",0
ALIGN 4
cname DB "MainClass", 0
ALIGN 4
MES1 DB "Lewy, myszy",0
ALIGN 4
tbutt DB "BUTTON", 0
ALIGN 4

tbutt2 DB "BUTTON", 0
ALIGN 4
tbutt3 DB "BUTTON", 0
ALIGN 4
tbutt4 DB "BUTTON", 0
ALIGN 4

tstart DB "add", 0
ALIGN 4

tstart2 DB "sub", 0
ALIGN 4

tstart3 DB "mul", 0
ALIGN 4

tstart4 DB "div", 0
ALIGN 4

tedt DB "EDIT", 0
ALIGN 4

tedt2 DB "EDIT", 0
ALIGN 4

tnazwaedt DB " ", 0
ALIGN 4
ttekst DB "text", 0
ALIGN 4
nagl DB "text", 0
ALIGN 4
terr DB "error!", 0
ALIGN 4
terr2 DB "error!", 0
ALIGN 4
bufor DB 128 dup(' ')
rbuf DD 128
znaczn DD 0
rt RECT <120,50,210,90>
rr DD 0
_DATA ENDS
_TEXT SEGMENT
WndProc PROC
; DWORD PTR [EBP+14h] - parametr LPARAM komunikatu
; DWORD PTR [EBP+10h] - parametr WPARAM komunikatu
; DWORD PTR [EBP+0Ch] - ID = identyfikator komunikatu
; DWORD PTR [EBP+08h] - HWND = deskryptor okna
;------------------------------------
push EBP
mov EBP, ESP
push EBX
push ESI
push EDI
cmp DWORD PTR [EBP+0Ch], WM_CREATE
jne @F
jmp wmCREATE
@@:
cmp DWORD PTR [EBP+0Ch], WM_DESTROY
jne @F
jmp wmDESTROY
@@:
cmp DWORD PTR [EBP+0CH], WM_COMMAND
jne @F
jmp wmCOMMAND
@@:
cmp DWORD PTR [EBP+0CH], WM_LBUTTONDOWN
jne @F
jmp wmLBUTTON
@@:
cmp DWORD PTR [EBP+0CH], WM_RBUTTONDOWN
jne @F
jmp wmRBUTTON
@@:
INVOKE DefWindowProcA, DWORD PTR [EBP+08h], \
 DWORD PTR [EBP+0Ch], DWORD PTR [EBP+10h], \
 DWORD PTR [EBP+14h]
jmp konWNDPROC
wmCREATE:
INVOKE CreateWindowExA, 0, OFFSET tbutt, OFFSET tstart, \
 BSstyle, 10, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX

INVOKE CreateWindowExA, 0, OFFSET tbutt2, OFFSET tstart2, \
 BSstyle, 110, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX

INVOKE CreateWindowExA, 0, OFFSET tbutt3, OFFSET tstart3, \
 BSstyle, 210, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX

INVOKE CreateWindowExA, 0, OFFSET tbutt4, OFFSET tstart4, \
 BSstyle, 310, 50, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hbutt, EAX
INVOKE CreateWindowExA, 0, OFFSET tedt, OFFSET tnazwaedt, EDTstyle, 110, 100, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hedt, EAX

INVOKE CreateWindowExA, 0, OFFSET tedt2, OFFSET tnazwaedt, EDTstyle, 210, 100, 100, 40, DWORD PTR [EBP+08h], 0, hinst, 0
mov hedt, EAX
INVOKE CreateSolidBrush,kolor
mov hbrush,EAX
mov EAX,0
jmp konWNDPROC
wmDESTROY:
INVOKE DeleteObject, hbrush
INVOKE PostQuitMessage, 0
mov EAX, 0
jmp konWNDPROC
wmCOMMAND:
mov EAX,hbutt
cmp EAX,DWORD PTR [EBP+14h]
je @F
jmp et1
@@:
cmp znaczn,1
je @F
mov znaczn,1
INVOKE SelectObject,hDC,hbrush
mov holdbrush,EAX
INVOKE FillRect,hDC,OFFSET rt,hbrush
mov EAX, 0
jmp konWNDPROC
@@:
mov znaczn,0
INVOKE SelectObject,hDC,holdbrush
mov hbrush,EAX
INVOKE FillRect,hDC,OFFSET rt,holdbrush
mov EAX, 0
jmp konWNDPROC
et1:
jmp konWNDPROC
wmRBUTTON:
jmp wmDESTROY
wmLBUTTON:
INVOKE SendMessageA,hedt,WM_GETTEXT,128,OFFSET bufor
mov rr,EAX
INVOKE TextOutA,hDC,110,120,OFFSET bufor,rr
mov EAX,0
jmp konWNDPROC
konWNDPROC:
pop EDI
pop ESI
pop EBX
mov ESP,EBP
pop EBP
ret 16
WndProc ENDP
main:
INVOKE GetModuleHandleA, 0
mov hinst, EAX
mov EAX, hinst
mov [wndc.clsHInstance], EAX
mov [wndc.clsStyle], CSstyle
mov [wndc.clsLpfnWndProc], OFFSET WndProc
mov [wndc.clsCbClsExtra], 0
mov [wndc.clsCbWndExtra], 0
INVOKE LoadIconA, 0, IDI_APPLICATION ; ikona
mov [wndc.clsHIcon], EAX
INVOKE LoadCursorA, 0, IDC_ARROW ; kursor
mov [wndc.clsHCursor], EAX
INVOKE GetStockObject, WHITE_BRUSH ; tło
mov [wndc.clsHbrBackground], EAX
mov [wndc.clsLpszMenuName], 0
mov DWORD PTR [wndc.clsLpszClassName], OFFSET cname
INVOKE RegisterClassA, OFFSET wndc
cmp EAX, 0
jne @F
jmp err0
@@:
INVOKE CreateWindowExA, 0, OFFSET cname, OFFSET tytul, \
 WNDstyle, 50, 50, 455, 400, 0, 0, hinst, 0
cmp EAX, 0
jne @F
jmp err2
@@:
mov hwnd, EAX
INVOKE ShowWindow, hwnd, SW_SHOWNORMAL
INVOKE GetDC,hwnd
mov hdc,EAX
INVOKE lstrlenA,OFFSET naglow
mov rozmN,EAX
INVOKE TextOutA,hDC,10,20,OFFSET naglow,rozmN
INVOKE UpdateWindow, hwnd
msgloop:
INVOKE GetMessageA, OFFSET msg, 0, 0, 0
cmp EAX, 0
jne @F
jmp etkon
@@:
cmp EAX, -1
jne @F
jmp err0
@@:
INVOKE TranslateMessage, OFFSET msg
INVOKE DispatchMessageA, OFFSET msg
jmp msgloop
err0:
INVOKE MessageBoxA,0,OFFSET terr,OFFSET nagl,0
jmp etkon
err2:
INVOKE MessageBoxA,0,OFFSET terr2,OFFSET nagl,0
jmp etkon
etkon:
INVOKE ExitProcess, [msg.msWPARAM]
_TEXT ENDS
END main

A few more notes on my code:

I am using Visual Studio 2019 compiler

To compile the code, you need to consider the following factors:

a) For graphic assembler, you need a file in which there will be data with graphics

b) In order for the program to start in the settings, you need to set the entry point -> main

c) In the project settings, select (Build Customization -> masm(.targets, .props))


问:
detect mouse move while mouse is down
how to detect move mouse while mouse is down?
I have 2 boxes in smaller screen one of them is being off screen, so i hab=ve to grab it with mouse

I want to detect when mouse is moving right or left when I'm holding left mouse button

const box = document.querySelector('.boxes')

let mouseIsDown = false;

box.addEventListener('mousedown',()=> {
  mouseIsDown = true;

    if(mouseIsDown) {
     console.log('Nora!')

       box.classList.add('grab')

        box.addEventListener("mousemove", detectDirection);

            let exX = 0;

            function detectDirection(e) {
                console.log(e.buttons)

                if (e.buttons === 1 && exX < e.pageX) {

                    box.classList.add('move-right')

                } else if(e.buttons ===1 && exX > e.pageX) {
                    box.classList.add('move-left')
                    // console.log('left')
                }
                exX = e.pageX;
            }
    }
});

box.addEventListener('mouseup', ()=> {
    box.classList.remove('move-left')
    box.classList.remove('move-right')
    box.classList.remove('grab')

  mouseIsDown = false;

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.boxes {
  display: flex;
  width: 100%;
  transition: 1s;
  position: relative;
}

.inner-box {
  background-color: #fff;
  box-shadow: 0 1px 10px rgba(1, 1, 1, 0.1);
  border-radius: 5px;
  padding: 1.5rem 0.5rem;
  padding-left: 1rem;
  cursor: grab;
}
.box-1 {
  width: 100%;
  margin-right: 1rem;
}

.box-2 {
  position: absolute;
  left: 99%;

}

.grab {
  cursor: grabbing;
}

.move-left {
  margin-left: 30rem;
}
.move-right {
  margin-right: 48rem;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

```

but as you see it doesn't work probably it move even if I leave the left button, also it doesn't detect left and right accurately .. what I want is when the cursor is grabbing I can move the box left or right when is (cursor: grab) can't move it

答:
Make sure that all mousedown and mouseup is doing is toggling the variable mouseIsDown. Your mousemove should be an independent eventlistener. Also checked for the px for margin and update the boxes margin relative to the amount of mousemove. Also i would suggest instead of using margin to move the boxes use positions.

const box = document.querySelector('.boxes')
box.style.marginRight = "1px"
box.style.marginLeft = "1px"
let exX = 0;

let mouseIsDown = false;

box.addEventListener('mousedown',(e)=> {
  exX = e.pageX
  mouseIsDown = true;

});

window.addEventListener("mousemove", detectDirection);

window.addEventListener('mouseup', ()=> {
    box.classList.remove('grab')

  mouseIsDown = false;

});
function detectDirection(e) {
             if(mouseIsDown) {
                   box.classList.add('grab')

                if (e.buttons === 1 && exX > e.pageX) {
                    var diff = exX - e.pageX
                    box.classList.add('move-right')
                    box.style.marginRight = (parseInt(box.style.marginRight.replace('px',''))+diff)+"px"
                    box.style.marginLeft = (parseInt(box.style.marginLeft.replace('px',''))-diff)+"px"

                } else if(e.buttons ===1 && exX < e.pageX) {
                    var diff = e.pageX-exX;
                    box.classList.add('move-left')
                    box.style.marginRight = (parseInt(box.style.marginRight.replace('px',''))-diff)+"px"
                    box.style.marginLeft = (parseInt(box.style.marginLeft.replace('px',''))+diff)+"px"
                    // console.log('left')
                }
                exX = e.pageX;
            }
           }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.boxes {
  display: flex;
  width: 100%;
  transition: 1s;
  position: relative;
    margin-right: 1rem;
    margin-left: 1rem;
}

.inner-box {
  background-color: #fff;
  box-shadow: 0 1px 10px rgba(1, 1, 1, 0.1);
  border-radius: 5px;
  padding: 1.5rem 0.5rem;
  padding-left: 1rem;
  cursor: grab;
    margin-right: 1rem;
    margin-left: 1rem;
}
.box-1 {
  width: 100%;
  margin-right: 1rem;
    margin-left: 1rem;
}

.box-2 {
  position: absolute;
  left: 99%;

}

.grab {
  cursor: grabbing;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

```

Title: detect mouse move while mouse is down

Body:
how to detect move mouse while mouse is down?
I have 2 boxes in smaller screen one of them is being off screen, so i hab=ve to grab it with mouse

I want to detect when mouse is moving right or left when I'm holding left mouse button

const box = document.querySelector('.boxes')

let mouseIsDown = false;

box.addEventListener('mousedown',()=> {
  mouseIsDown = true;

    if(mouseIsDown) {
     console.log('Nora!')

       box.classList.add('grab')

        box.addEventListener("mousemove", detectDirection);

            let exX = 0;

            function detectDirection(e) {
                console.log(e.buttons)

                if (e.buttons === 1 && exX < e.pageX) {

                    box.classList.add('move-right')

                } else if(e.buttons ===1 && exX > e.pageX) {
                    box.classList.add('move-left')
                    // console.log('left')
                }
                exX = e.pageX;
            }
    }
});

box.addEventListener('mouseup', ()=> {
    box.classList.remove('move-left')
    box.classList.remove('move-right')
    box.classList.remove('grab')

  mouseIsDown = false;

});

.boxes {
  display: flex;
  width: 100%;
  transition: 1s;
  position: relative;
}

.inner-box {
  background-color: #fff;
  box-shadow: 0 1px 10px rgba(1, 1, 1, 0.1);
  border-radius: 5px;
  padding: 1.5rem 0.5rem;
  padding-left: 1rem;
  cursor: grab;
}
.box-1 {
  width: 100%;
  margin-right: 1rem;
}

.box-2 {
  position: absolute;
  left: 99%;

}

.grab {
  cursor: grabbing;
}

.move-left {
  margin-left: 30rem;
}
.move-right {
  margin-right: 48rem;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

but as you see it doesn't work probably it move even if I leave the left button, also it doesn't detect left and right accurately .. what I want is when the cursor is grabbing I can move the box left or right when is (cursor: grab) can't move it

Body:
Make sure that all mousedown and mouseup is doing is toggling the variable mouseIsDown. Your mousemove should be an independent eventlistener. Also checked for the px for margin and update the boxes margin relative to the amount of mousemove. Also i would suggest instead of using margin to move the boxes use positions.

const box = document.querySelector('.boxes')
box.style.marginRight = "1px"
box.style.marginLeft = "1px"
let exX = 0;

let mouseIsDown = false;

box.addEventListener('mousedown',(e)=> {
  exX = e.pageX
  mouseIsDown = true;

});

window.addEventListener("mousemove", detectDirection);

window.addEventListener('mouseup', ()=> {
    box.classList.remove('grab')

  mouseIsDown = false;

});
function detectDirection(e) {
             if(mouseIsDown) {
                   box.classList.add('grab')

                if (e.buttons === 1 && exX > e.pageX) {
                    var diff = exX - e.pageX
                    box.classList.add('move-right')
                    box.style.marginRight = (parseInt(box.style.marginRight.replace('px',''))+diff)+"px"
                    box.style.marginLeft = (parseInt(box.style.marginLeft.replace('px',''))-diff)+"px"

                } else if(e.buttons ===1 && exX < e.pageX) {
                    var diff = e.pageX-exX;
                    box.classList.add('move-left')
                    box.style.marginRight = (parseInt(box.style.marginRight.replace('px',''))-diff)+"px"
                    box.style.marginLeft = (parseInt(box.style.marginLeft.replace('px',''))+diff)+"px"
                    // console.log('left')
                }
                exX = e.pageX;
            }
           }

.boxes {
  display: flex;
  width: 100%;
  transition: 1s;
  position: relative;
    margin-right: 1rem;
    margin-left: 1rem;
}

.inner-box {
  background-color: #fff;
  box-shadow: 0 1px 10px rgba(1, 1, 1, 0.1);
  border-radius: 5px;
  padding: 1.5rem 0.5rem;
  padding-left: 1rem;
  cursor: grab;
    margin-right: 1rem;
    margin-left: 1rem;
}
.box-1 {
  width: 100%;
  margin-right: 1rem;
    margin-left: 1rem;
}

.box-2 {
  position: absolute;
  left: 99%;

}

.grab {
  cursor: grabbing;
}

<div class="boxes">
            <div class="inner-box box-1">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>

            </div>
            <div class="inner-box box-2">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
                </p>
            </div>

        </div>


问:
How can I stop alarms triggering inside max pyramid argument?
I have some PineScript codes executin, the alarms are sent out to my MT4 account to execute trades, alarms should only go off when a trade gets executed in tradingview. The problem is that they keep getting executed even though max pyramid has been reached and I have that condition set.
Any idea on how to stop this from happening? here's some of the code:</p>
```<code>//Strategy
maxPyramid = input.int(title="Max Pyramiding", defval=3)
Long = high > h1[1] and close > regime and rangehl > 4 and strategy.opentrades <= maxPyramid

Short = close < l1[1] and rangehl > 5 and strategy.opentrades <= maxPyramid

m_check_l = close > mid[1] and close[5] > mid[5] and close[6] > mid[6]

if Long and m_check_l and time > startDate and time < endDate
    strategy.entry('Long', strategy.long)

if ta.crossunder(close, mid)
    strategy.close('Long')
    alert(message = "close UKSUGAR long", freq = alert.freq_once_per_bar)

if Short and time > startDate and time < endDate
    strategy.entry('Short', strategy.short)

if ta.crossover(close, mid)
    strategy.close('Short')
    alert(message = "close UKSUGAR short", freq = alert.freq_once_per_bar)

//Alerts
if Long and strategy.opentrades <= maxPyramid
    alert(message = "buy UKSUGAR q=1", freq = alert.freq_once_per_bar)

if Short and strategy.opentrades <= maxPyramid
    alert(message = "sell UKSUGAR q=1", freq = alert.freq_once_per_bar)
</code>```

答:
Use the alert_message parameter of strategy.x calls.

```<code>if ta.crossunder(close, mid)
    strategy.close('Long')
    alert(message = "close UKSUGAR long", freq = alert.freq_once_per_bar)
</code>```

You have an alert() call inside an if block. What's gonna happen is, if that if condition is true, it will execute that strategy.close() and alert() call. Those are two different calls. strategy() calls will depend on your strategy settings but the alert() call will be executed anyway.

```<code>if ta.crossunder(close, mid)
    strategy.close('Long', alert_message="close UKSUGAR long")
</code>```

If you use the alert_message parameter, alert message will be triggered if that strategy call is executed.

Body:
I have some PineScript codes executin, the alarms are sent out to my MT4 account to execute trades, alarms should only go off when a trade gets executed in tradingview. The problem is that they keep getting executed even though max pyramid has been reached and I have that condition set.
Any idea on how to stop this from happening? here's some of the code:

//Strategy
maxPyramid = input.int(title="Max Pyramiding", defval=3)
Long = high > h1[1] and close > regime and rangehl > 4 and strategy.opentrades <= maxPyramid

Short = close < l1[1] and rangehl > 5 and strategy.opentrades <= maxPyramid

m_check_l = close > mid[1] and close[5] > mid[5] and close[6] > mid[6]

if Long and m_check_l and time > startDate and time < endDate
    strategy.entry('Long', strategy.long)

if ta.crossunder(close, mid)
    strategy.close('Long')
    alert(message = "close UKSUGAR long", freq = alert.freq_once_per_bar)

if Short and time > startDate and time < endDate
    strategy.entry('Short', strategy.short)

if ta.crossover(close, mid)
    strategy.close('Short')
    alert(message = "close UKSUGAR short", freq = alert.freq_once_per_bar)

//Alerts
if Long and strategy.opentrades <= maxPyramid
    alert(message = "buy UKSUGAR q=1", freq = alert.freq_once_per_bar)

if Short and strategy.opentrades <= maxPyramid
    alert(message = "sell UKSUGAR q=1", freq = alert.freq_once_per_bar)

Body:
Use the alert_message parameter of strategy.x calls.

if ta.crossunder(close, mid)
    strategy.close('Long')
    alert(message = "close UKSUGAR long", freq = alert.freq_once_per_bar)

You have an alert() call inside an if block. What's gonna happen is, if that if condition is true, it will execute that strategy.close() and alert() call. Those are two different calls. strategy() calls will depend on your strategy settings but the alert() call will be executed anyway.

if ta.crossunder(close, mid)
    strategy.close('Long', alert_message="close UKSUGAR long")

If you use the alert_message parameter, alert message will be triggered if that strategy call is executed.


问:
angular-ui-tinymce directive and image upload via file browser
With jquery we can add local images to tinymce editor like this jsfiddle following the documentation.

The module for tinymce for angular is angular-ui-tinymce. But adding local file doesn't work with that module.

My code as follows. If it works there should be a file browse button like this when I click insert/edit image.

But it doesn't appear. Other than that everything works. May be the module doesn't support that feature. Does anyone know how to add local images with this module?

in template:

```<code><textarea
    ui-tinymce="{{tinymceOptions}}"
    ng-model="tinymceValue">
</textarea>
</code>```

in controller:

```<code> $scope.tinymceOptions: {
      selector: "textarea",
      plugins: 'image',
      file_browser_callback: function(){},
      paste_as_text: true
}
</code>```

答:
This has worked for me, used @tinymce/angular - angular version 11

In component.html file

```<code><editor [id]="'editorID1'" style="margin-left: 0em" [formControlName]="'questiontext'" placeholder="Date"
       class="form-control" apiKey=" place your api key here" [init]="editorConfig">
</editor>
</code>```

It's in ts file:

```<code>  let editorConfig = {
  paste_data_images: true,

  file_picker_callback: function(callback:any, value:any, meta:any) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
      if (meta.filetype == 'image') {
         input.click();
         // jQuery('#test-upload').trigger('click');
         //   input.on('change', function(e:any) {
          input.onchange = function (e:any) {
          //jQuery('#test-upload').on('change', function(e:any) {
              var file:any = e.target.files[0];
              var reader = new FileReader();
              reader.onload = function(e: any) {
                  callback(e.target.result, {
                      alt: ''
                  });
              };
              reader.readAsDataURL(file);
          };
      }
  },

...
}
</code>```

Body:
With jquery we can add local images to tinymce editor like this jsfiddle following the documentation.

The module for tinymce for angular is angular-ui-tinymce. But adding local file doesn't work with that module.

My code as follows. If it works there should be a file browse button like this when I click insert/edit image.

But it doesn't appear. Other than that everything works. May be the module doesn't support that feature. Does anyone know how to add local images with this module?

in template:

<textarea
    ui-tinymce="{{tinymceOptions}}"
    ng-model="tinymceValue">
</textarea>

in controller:

 $scope.tinymceOptions: {
      selector: "textarea",
      plugins: 'image',
      file_browser_callback: function(){},
      paste_as_text: true
}

Body:
This has worked for me, used @tinymce/angular - angular version 11

In component.html file

<editor [id]="'editorID1'" style="margin-left: 0em" [formControlName]="'questiontext'" placeholder="Date"
       class="form-control" apiKey=" place your api key here" [init]="editorConfig">
</editor>

It's in ts file:

  let editorConfig = {
  paste_data_images: true,

  file_picker_callback: function(callback:any, value:any, meta:any) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
      if (meta.filetype == 'image') {
         input.click();
         // jQuery('#test-upload').trigger('click');
         //   input.on('change', function(e:any) {
          input.onchange = function (e:any) {
          //jQuery('#test-upload').on('change', function(e:any) {
              var file:any = e.target.files[0];
              var reader = new FileReader();
              reader.onload = function(e: any) {
                  callback(e.target.result, {
                      alt: ''
                  });
              };
              reader.readAsDataURL(file);
          };
      }
  },

...
}


问:
Unable to find Databricks spark sql avro shaded jars in any public maven repository
We are trying to create avro record with confluent schema registry. The same record we want to publish to kafka cluster.

To attach schema id to each records (magic bytes) we need to use--

to_avro(Column data, Column subject, String schemaRegistryAddress)

To automate this we need to build project in pipeline & configure databricks jobs to use that jar.

Now the problem we are facing in notebooks we are able to find a methods with 3 parameters to it.

But the same library when we are using in our build downloaded from https://mvnrepository.com/artifact/org.apache.spark/spark-avro_2.12/3.1.2 its only having 2 overloaded methods of to_avro

Is databricks having some other maven repository for its shaded jars?

NOTEBOOK output

import org.apache.spark.sql.avro.functions

println(functions.getClass().getProtectionDomain().getCodeSource().getLocation())
// file:/databricks/jars/----workspace_spark_3_1--vendor--avro--avro_2.12_deploy_shaded.jar

functions
  .getClass()
  .getMethods()
  .filter(p=>p.getName.equals("to_avro"))
  .foreach(f=>println(f.getName, f.getParameters.mkString("Array(", ", ", ")")))
// (to_avro,Array(final org.apache.spark.sql.Column data, final org.apache.spark.sql.Column subject, final java.lang.String schemaRegistryAddress, final java.lang.String jsonFormatSchema))
// (to_avro,Array(final org.apache.spark.sql.Column data, final org.apache.spark.sql.Column subject, final java.lang.String schemaRegistryAddress))
// (to_avro,Array(final org.apache.spark.sql.Column data, final java.lang.String jsonFormatSchema))
// (to_avro,Array(final org.apache.spark.sql.Column data))
```
<p><strong>LOCAL output</strong></p>
<pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.avro.functions

println(functions.getClass().getProtectionDomain().getCodeSource().getLocation())
// file:/<home-dir-path>/.gradle/caches/modules-2/files-2.1/org.apache.spark/spark-avro_2.12/3.1.2/1160ae134351328a0ed6a062183faf9a0d5b46ea/spark-avro_2.12-3.1.2.jar

functions
  .getClass()
  .getMethods()
  .filter(p=>p.getName.equals("to_avro"))
  .foreach(f=>println(f.getName, f.getParameters.mkString("Array(", ", ", ")")))
// (to_avro,Array(final org.apache.spark.sql.Column data, final java.lang.String jsonFormatSchema))
// (to_avro,Array(final org.apache.spark.sql.Column data))
</code>```

Versions

Databricks => 9.1 LTS

Apache Spark => 3.1.2

Scala => 2.12

Update from databricks support

Unfortunately we do not have a sharable jar supporting the functionalities in the DBR. There was a feature request to include this in DBConnect; however it was not implemented as we did not have enough upvote to implement the feature.

Since your use case is to automate creation of the Jar file and then submit this as Job in Databricks, we should be able to create a jar stub (dbr-avro-dummy.jar) with a dummy implementation of the to_avro() function with three parameters and use this jar as a dependency to fool the compiler of your actual Jar (for the Job).

This will avoid the compilation error while building the Jar and at run time, since its run on the Databricks environment, it will pick the actual avro Jar from the DBR

You may build the dummy Jar Stub using the package code below: (You will use the maven/sbt spark/scala dependency for the Column function)

package org.apache.spark.sql
import java.net.URL

package object avro {
  def from_avro(data: Column, key: String, schemaRegistryURL: URL): Column = {
    new Column("dummy")
  }
}
```

答:
No, these jars aren't published to any public repository. You may check if the databricks-connect provides these jars (you can get their location with databricks-connect get-jar-dir), but I really doubt in that.

Another approach is to mock it, for example, create a small library that will declare a function with specific signature, and use it for compilation only, don't include into the resulting jar.

Body:
We are trying to create avro record with confluent schema registry. The same record we want to publish to kafka cluster.

To attach schema id to each records (magic bytes) we need to use--

to_avro(Column data, Column subject, String schemaRegistryAddress)

To automate this we need to build project in pipeline & configure databricks jobs to use that jar.

Now the problem we are facing in notebooks we are able to find a methods with 3 parameters to it.

But the same library when we are using in our build downloaded from https://mvnrepository.com/artifact/org.apache.spark/spark-avro_2.12/3.1.2 its only having 2 overloaded methods of to_avro

Is databricks having some other maven repository for its shaded jars?

NOTEBOOK output

import org.apache.spark.sql.avro.functions

println(functions.getClass().getProtectionDomain().getCodeSource().getLocation())
// file:/databricks/jars/----workspace_spark_3_1--vendor--avro--avro_2.12_deploy_shaded.jar

functions
  .getClass()
  .getMethods()
  .filter(p=>p.getName.equals("to_avro"))
  .foreach(f=>println(f.getName, f.getParameters.mkString("Array(", ", ", ")")))
// (to_avro,Array(final org.apache.spark.sql.Column data, final org.apache.spark.sql.Column subject, final java.lang.String schemaRegistryAddress, final java.lang.String jsonFormatSchema))
// (to_avro,Array(final org.apache.spark.sql.Column data, final org.apache.spark.sql.Column subject, final java.lang.String schemaRegistryAddress))
// (to_avro,Array(final org.apache.spark.sql.Column data, final java.lang.String jsonFormatSchema))
// (to_avro,Array(final org.apache.spark.sql.Column data))

LOCAL output

import org.apache.spark.sql.avro.functions

println(functions.getClass().getProtectionDomain().getCodeSource().getLocation())
// file:/<home-dir-path>/.gradle/caches/modules-2/files-2.1/org.apache.spark/spark-avro_2.12/3.1.2/1160ae134351328a0ed6a062183faf9a0d5b46ea/spark-avro_2.12-3.1.2.jar

functions
  .getClass()
  .getMethods()
  .filter(p=>p.getName.equals("to_avro"))
  .foreach(f=>println(f.getName, f.getParameters.mkString("Array(", ", ", ")")))
// (to_avro,Array(final org.apache.spark.sql.Column data, final java.lang.String jsonFormatSchema))
// (to_avro,Array(final org.apache.spark.sql.Column data))

Versions

Databricks => 9.1 LTS

Apache Spark => 3.1.2

Scala => 2.12

Update from databricks support

Unfortunately we do not have a sharable jar supporting the functionalities in the DBR. There was a feature request to include this in DBConnect; however it was not implemented as we did not have enough upvote to implement the feature.

Since your use case is to automate creation of the Jar file and then submit this as Job in Databricks, we should be able to create a jar stub (dbr-avro-dummy.jar) with a dummy implementation of the to_avro() function with three parameters and use this jar as a dependency to fool the compiler of your actual Jar (for the Job).

This will avoid the compilation error while building the Jar and at run time, since its run on the Databricks environment, it will pick the actual avro Jar from the DBR

You may build the dummy Jar Stub using the package code below: (You will use the maven/sbt spark/scala dependency for the Column function)

package org.apache.spark.sql
import java.net.URL

package object avro {
  def from_avro(data: Column, key: String, schemaRegistryURL: URL): Column = {
    new Column("dummy")
  }
}


问:
C++ Move constructor not called with the compound operator += when written in one line
I followed the amazing tutorials from stackoverflow for Move and Operator overloading (e.g. What are the basic rules and idioms for operator overloading?), and the following situation is baffling me. Nothing fancy in the code, just printing when special member functions are called.

The main code:

```<code>    class B {
public:
    B() { std::cout << "B::ctor\n"; }

    ~B() { std::cout << "B::dtor\n"; }

    B(B const &b) {
        std::cout << "B::copy ctor\n";
    }

    B &operator=(B const &rhs) {
        std::cout << "B::copy assignment\n";
        return *this;
    }

    B(B &&b) {
        std::cout << "B::move ctor\n";
    }

    B &operator=(B &&rhs) {
        std::cout << "B::move assignment\n";
        return *this;
    }

    B &operator+=(B const &rhs) {
        std::cout << "B::operator+=\n";
        return *this;
    }
};

int main() {
  B b;
  std::cout << "=== b = b + b + b ===\n";
  b = b + b + b;
}
</code>```

Now, two scenarios, where in each I define the operator + differently:

```<code>B operator+(B p1, B const &p2) {
    std::cout << "B::operator+\n";
    return p1 += p2;
}
</code>```

with output for the whole program:

```<code>B::ctor
=== b = b + b + b ===
B::copy ctor
B::operator+
B::operator+=
B::copy ctor
B::operator+
B::operator+=
B::copy ctor
B::move assignment
B::dtor
B::dtor
B::dtor
B::dtor
</code>```

and the second scenario:

```<code>B operator+(B p1, B const &p2) {
    std::cout << "B::operator+\n";
    p1 += p2;
    return p1;
}
</code>```

with output:

```<code>B::ctor
=== b = b + b + b ===
B::copy ctor
B::operator+
B::operator+=
B::move ctor
B::operator+
B::operator+=
B::move ctor
B::move assignment
B::dtor
B::dtor
B::dtor
B::dtor
</code>```

How come the second scenario does give the expected result, using correctly the move semantics, but the first makes copy everywhere?

I just want to add that the second scenario is the one recommended in the tutorials I read (like the link from above), but when I tried to implement it, I intuitively wrote the first scenario and it gave me the wrong behaviour...

答:
Returning a local variable of type T from a function with with the same1 return type T is a special case.

It at least automatically moves the variable, or, if the compiler is smart enough to perform so-called NRVO, eliminates the copy/move entirely and constructs the variable directly in the right location.

Function parameters (unlike regular local variables) are not eligible for NRVO, so you always get an implicit move in (2).

This doesn't happen in (1). The compiler isn't going to analyze += to understand what it returns; this rule only works when the operand of return is a single variable.

Since += returns an lvalue reference, and you didn't std::move it, the copy constructor is called.

1 Or a type that differs only in cv-qualifiers.

Body:
I followed the amazing tutorials from stackoverflow for Move and Operator overloading (e.g. What are the basic rules and idioms for operator overloading?), and the following situation is baffling me. Nothing fancy in the code, just printing when special member functions are called.

The main code:

    class B {
public:
    B() { std::cout << "B::ctor\n"; }

    ~B() { std::cout << "B::dtor\n"; }

    B(B const &b) {
        std::cout << "B::copy ctor\n";
    }

    B &operator=(B const &rhs) {
        std::cout << "B::copy assignment\n";
        return *this;
    }

    B(B &&b) {
        std::cout << "B::move ctor\n";
    }

    B &operator=(B &&rhs) {
        std::cout << "B::move assignment\n";
        return *this;
    }

    B &operator+=(B const &rhs) {
        std::cout << "B::operator+=\n";
        return *this;
    }
};

int main() {
  B b;
  std::cout << "=== b = b + b + b ===\n";
  b = b + b + b;
}

Now, two scenarios, where in each I define the operator + differently:

B operator+(B p1, B const &p2) {
    std::cout << "B::operator+\n";
    return p1 += p2;
}

with output for the whole program:

B::ctor
=== b = b + b + b ===
B::copy ctor
B::operator+
B::operator+=
B::copy ctor
B::operator+
B::operator+=
B::copy ctor
B::move assignment
B::dtor
B::dtor
B::dtor
B::dtor

and the second scenario:

B operator+(B p1, B const &p2) {
    std::cout << "B::operator+\n";
    p1 += p2;
    return p1;
}

with output:

B::ctor
=== b = b + b + b ===
B::copy ctor
B::operator+
B::operator+=
B::move ctor
B::operator+
B::operator+=
B::move ctor
B::move assignment
B::dtor
B::dtor
B::dtor
B::dtor

How come the second scenario does give the expected result, using correctly the move semantics, but the first makes copy everywhere?

I just want to add that the second scenario is the one recommended in the tutorials I read (like the link from above), but when I tried to implement it, I intuitively wrote the first scenario and it gave me the wrong behaviour...


问:
How to set delay in Kotlin?
I just want to wait 2 or 3 seconds, I know how to do it in Java and I tried it, but no idea about kotlin

something simple like:

```<code>println("hello")
// a 2 seconds delay
println("world")
</code>```

答:
It's simple. Just use a coroutine. Like this:

```<code>fun main() = runBlocking {
    launch {
        delay(2000L)
        println("World!")
    }
    println("Hello")
}
</code>```

Don't forget to import kotlin coroutine like this:

```<code>import kotlinx.coroutines.*
</code>```

Happy coding in kotlin!!!

Title: How to set delay in Kotlin?

Body:
I just want to wait 2 or 3 seconds, I know how to do it in Java and I tried it, but no idea about kotlin

something simple like:

println("hello")
// a 2 seconds delay
println("world")

Body:
It's simple. Just use a coroutine. Like this:

fun main() = runBlocking {
    launch {
        delay(2000L)
        println("World!")
    }
    println("Hello")
}

Don't forget to import kotlin coroutine like this:

import kotlinx.coroutines.*

Happy coding in kotlin!!!


答:
you can use group by to achieve this particular result.

```<code>select region,
   data2 as [Lessors Liability Per $100 Of Limit Of Ins],
   subregion,
   data2 as [Business Personal Prop Per $100 Of Limit Of Ins],
   data2 as [Building Per $100 Of Limit Of Ins ]
from sourcetable
group by subregion, region, data2
</code>```

getting more complex just requires being aware of which data you're actually selecting, and how you're naming it.

Title: How to transpose rows into columns in and map values associated to them

Body:
Here's what I've tried:

SELECT *
FROM
    (SELECT
         dbo.LC1.[tableNumber],
         [keyhash], [Key1], [Key2], [Data2]
     FROM
         [dbo].[LC1]) AS SourceTable
PIVOT
    (AVG([Data2]) FOR [Key2]
        IN ([Doc A], [Doc B], [Doc C], [Doc D], [Doc E])
    ) AS PivotTable;

I've tried to replicate an example but I'm having no luck. Say I have a table like this:

+--------+-------------------------------------------------+----------------+-------+
| Region | Key2                                            | Subregion      | Data2 |
+--------+-------------------------------------------------+----------------+-------+
| 703    | Building Per $100 Of Limit Of Ins               | NULL           | 0.125 |
+--------+-------------------------------------------------+----------------+-------+
| 703    | Business Personal Prop Per $100 Of Limit Of Ins | NULL           | 0.125 |
+--------+-------------------------------------------------+----------------+-------+
| 703    | Lessors Liability Per $100 Of Limit Of Ins      | Fountain Hills | 0.125 |
+--------+-------------------------------------------------+----------------+-------+
| 703    | Lessors Liability Per $100 Of Limit Of Ins      | NULL           | 0.125 |
+--------+-------------------------------------------------+----------------+-------+

What I want to do is take the values in Key2 and make them columns of their own. As you can see some values repeat in the column, so they'd need to be distinct. Also, the values in the Data2 column should still line up with the corresponding Key2 values, like so:

+--------+--------------------------------------------+----------------+-------------------------------------------------+-----------------------------------+
| Region | Lessors Liability Per $100 Of Limit Of Ins | Subregion      | Business Personal Prop Per $100 Of Limit Of Ins | Building Per $100 Of Limit Of Ins |
+--------+--------------------------------------------+----------------+-------------------------------------------------+-----------------------------------+
| 703    | 0.125                                      | NULL           | 0.125                                           | 0.125                             |
+--------+--------------------------------------------+----------------+-------------------------------------------------+-----------------------------------+
| 703    | 0.125                                      | Fountain Hills | NULL                                            | NULL                              |
+--------+--------------------------------------------+----------------+-------------------------------------------------+-----------------------------------+

Body:
you can use group by to achieve this particular result.

select region,
   data2 as [Lessors Liability Per $100 Of Limit Of Ins],
   subregion,
   data2 as [Business Personal Prop Per $100 Of Limit Of Ins],
   data2 as [Building Per $100 Of Limit Of Ins ]
from sourcetable
group by subregion, region, data2

getting more complex just requires being aware of which data you're actually selecting, and how you're naming it.


问:
How to use SSL/TLS on ECS Fargate
I am trying to use SSL/TLS for Python Flask/Waitress server running the ECS Fargate. I haven't found a solution for our use case.

Here are the designs for the ECS Fargate:

Container will only interacts with backend AWS Lambda

Public IP disabled, only private ip is enabled.

No use of load balancer. The Python server is stateful and spinning a new container when requested is more cost effective.

How should I make a HTTPS request from Lambda to the ECS Fargate?

答:
Why do even need to make an HTTPS request from the lambda?

Answer to your question

Enable the security group port 443 on your ecs fargate instance and you should be able to make requests even without ssl certs as browsers only block them,

2nd thing is if for any reason you need a SSL cert on localhost you can use this library https://github.com/FiloSottile/mkcert

Title: How to use SSL/TLS on ECS Fargate


问:
Svg image element not displaying in Safari
Safari browser (I'm testing under windows) seems having problem in displaying Svg Image element.

```<code><!DOCTYPE html>
<html>
<body>

<h1>My first SVG</h1>

<img src="image.svg" />

</body>
</html>
</code>```

And here is the content of the image.svg:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
      <rect x="50" y="50" width="100" height="100" style="fill:blue"></rect>
      <rect id="foo" x="50" y="150" width="500" height="500" style="fill:green"></rect>
     <image x="50" y="10" width="200" height="200" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="></image>
</svg>
</code>```

Is there any solution or workaround to make this work in Safari?

答:
Be sure to supply your <svg> tag with a height, width, and view box like so. Safari doesn't like it when height or width is set to auto for some reason. ⤵

<svg height="16px" width="16px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path d="M60......"></path></svg>
```

Body:
Safari browser (I'm testing under windows) seems having problem in displaying Svg Image element.

<!DOCTYPE html>

My first SVG

And here is the content of the image.svg:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
      <rect x="50" y="50" width="100" height="100" style="fill:blue"></rect>
      <rect id="foo" x="50" y="150" width="500" height="500" style="fill:green"></rect>
     <image x="50" y="10" width="200" height="200" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="></image>
</svg>

Is there any solution or workaround to make this work in Safari?


问:
What are the rules for re-binding?
[NOTE: I asked this question based on an older version of Rakudo.  As explained in the accepted answer, the confusing output was the result of Rakudo bugs, which have now been resolved.  I've left the original version of the Q below for historical reference.]

Raku sometimes prohibits re-binding; both of the following lines

```<code>sub f($a) { $a := 42 }
my \var = 'foo'; var := 'not-foo';
</code>```

produce a compile-time error:

```<code>===SORRY!=== Error while compiling
Cannot use bind operator with this left-hand side
</code>```

However, Raku allows rebinding in many, many situations – including many that came as a large surprise to me.  All of the following successfully rebind; every say outputs not-foo.

my Any \a = 'foo';
say a := 'not-foo';
my Any $b := 'foo';
say $b := 'not-foo';
my @c := ('foo', 'foo');
say @c := ('not-foo', 'not-foo');
my @d is List = ('foo', 'foo');
say @d := ('not-foo', 'not-foo');
my %e := (:foo<foo>);
say %e := (:not-foo<not-foo>);

sub fn1(Any \a) { a := 'not-foo';  say a  }
fn1 'foo';
sub fn2(Any $b) { $b := 'not-foo'; say $b }
fn2 'foo';
sub fn3(@c) {  @c := ('not-foo', 'not-foo'); say @c }
fn3 ('foo', 'foo');
sub fn4(+@d) { @d := ('not-foo', 'not-foo'); say @d }
fn4 ('foo', 'foo');
sub fn5(@d is raw) { @d := ('not-foo', 'not-foo'); say @d }
fn5 ('foo', 'foo');

my ($one-foo, $two-foo) := ('foo', 'foo');
$one-foo := 'not-foo';
say $one-foo;

my \foo = 'foo';
say MY::<foo> := 'not-foo';
sub foo-fn { 'foo' }
MY::<&foo-fn> := { 'not-foo' }
say foo-fn;

my $absolutely-foo = 'foo';
sub fn6 { CALLER::<$absolutely-foo> := 'not-foo';}
fn6;
say $absolutely-foo;
```

Thus, it appears that rebinding is currently allowed to any name, regardless of the sigil or lack of sigil, if either of the following conditions are met:

The name has any explicit type constraint (including Any and the type constraints imposed by the @ or % sigils), or

The rebinding uses a qualified name.

This rebinding currently happens for both declared variables and parameters, and includes parameters that are not rw or copy.  It even, as the last example indicates, allows re-bindings in ways that (seem to?) violate lexical scope.  (That example was based on a Roast test that's annotated with the comment -- legal?, which suggests that I may at least not be alone in finding this behavior surprising!  Though the test re-binds a is dynamic variable – in some ways, the behavior above is even more surprising).

As far as I can tell, the only names that cannot be re-bound using one of these approaches are those declared as constant.

So four questions:

Am I correctly describing the current behavior? [edit: that is, do the two rules I listed above correctly describe current behavior, or does a correct description require other/additional rules?]

Is that behavior correct/intentional/in line with the spec?  (Despite the presence of S03-binding, I've found remarkably little on rebinding).

If this behavior is not intentional, what are the rules about rebinding supposed to be?

Is there any way to tell Raku "don't rebind this name to a new value, no-really-I-mean-it"?

(This question supersedes my earlier question, which I asked before I realized how easy it is to re-bind name; I'm closing it in favor of this one.  Another related question: Is there a purpose or benefit in prohibiting sigilless variables from rebinding?, which discusses some of the design tradeoffs from the assumption that sigilless variables cannot be re-bound, contrary to several of the examples above.)

答:
The inconsistent behavior I asked about in the question was a result of a Rakudo bug – Rakudo was allowing rebinding in some situations where it should not have been.  This bug was resolved in Rakudo/Rakudo#4536.

After this resolution, the rules for rebinding are:

Sigilless "variables" cannot be rebound  (and can't be reassigned, so they aren't really "variables")

Variables with a sigil generally can be rebound, subject to the exception below.

If a sigiled variable is part of a Signature, then it cannot be rebound unless it is declared to be rebindable via the is copy or is rw traits.

This applies to a function's Signature (thus sub f($a) { $a := 42 } is illegal)

It also applies to Signatures that are destructured as part of variable declaration with :=.  E.g., in my ($var1, $var2) := ('foo', 'bar'), the right-hand side is a Signature and thus $var1 and $var2 cannot be rebound.

Applying these rules means that all of the following rebindings (which were allowed when the question was asked) are now forbidden:

my Any \a = 'foo';
say a := 'not-foo';

sub fn1(Any \a) { a := 'not-foo';  say a  }
fn1 'foo';
sub fn2(Any $b) { $b := 'not-foo'; say $b }
fn2 'foo';
sub fn3(@c) {  @c := ('not-foo', 'not-foo'); say @c }
fn3 ('foo', 'foo');
sub fn4(+@d) { @d := ('not-foo', 'not-foo'); say @d }
fn4 ('foo', 'foo');
sub fn5(@d is raw) { @d := ('not-foo', 'not-foo'); say @d }
fn5 ('foo', 'foo');

my ($one-foo, $two-foo) := ('foo', 'foo');
$one-foo := 'not-foo';
say $one-foo;
```
<p>Conversely, applying these rules means that some of the other rebindings shown in the question are (correctly) allowed:</p>
<pre class="lang-raku prettyprint-override"><code>my Any $b := 'foo';
say $b := 'not-foo';
my @c := ('foo', 'foo');
say @c := ('not-foo', 'not-foo');
my @d is List = ('foo', 'foo');
say @d := ('not-foo', 'not-foo');
my %e := (:foo<foo>);
say %e := (:not-foo<not-foo>);
</code>```

Finally, some of the examples shown in the question involved modifying the contents of a (pseudo) package.  This allows rebindings that would otherwise be forbidden by the rules above:

my \foo = 'foo';
say MY::<foo> := 'not-foo';
sub foo-fn { 'foo' }
MY::<&foo-fn> := { 'not-foo' }
say foo-fn;

my $absolutely-foo = 'foo';
sub fn6 { CALLER::<$absolutely-foo> := 'not-foo';}
fn6;
say $absolutely-foo;
```

However, just as with using the Metaobject Protocol to access private methods/attributes, using pseudo packages to break Raku's normal rules should be an extreme last resort and does not enjoy the same stability guarantees as other aspects of Raku.

Title: What are the rules for re-binding?

Body:
[NOTE: I asked this question based on an older version of Rakudo.  As explained in the accepted answer, the confusing output was the result of Rakudo bugs, which have now been resolved.  I've left the original version of the Q below for historical reference.]

Raku sometimes prohibits re-binding; both of the following lines

sub f($a) { $a := 42 }
my \var = 'foo'; var := 'not-foo';

produce a compile-time error:

===SORRY!=== Error while compiling
Cannot use bind operator with this left-hand side

However, Raku allows rebinding in many, many situations – including many that came as a large surprise to me.  All of the following successfully rebind; every say outputs not-foo.

my Any \a = 'foo';
say a := 'not-foo';
my Any $b := 'foo';
say $b := 'not-foo';
my @c := ('foo', 'foo');
say @c := ('not-foo', 'not-foo');
my @d is List = ('foo', 'foo');
say @d := ('not-foo', 'not-foo');
my %e := (:foo<foo>);
say %e := (:not-foo<not-foo>);

sub fn1(Any \a) { a := 'not-foo';  say a  }
fn1 'foo';
sub fn2(Any $b) { $b := 'not-foo'; say $b }
fn2 'foo';
sub fn3(@c) {  @c := ('not-foo', 'not-foo'); say @c }
fn3 ('foo', 'foo');
sub fn4(+@d) { @d := ('not-foo', 'not-foo'); say @d }
fn4 ('foo', 'foo');
sub fn5(@d is raw) { @d := ('not-foo', 'not-foo'); say @d }
fn5 ('foo', 'foo');

my ($one-foo, $two-foo) := ('foo', 'foo');
$one-foo := 'not-foo';
say $one-foo;

my \foo = 'foo';
say MY::<foo> := 'not-foo';
sub foo-fn { 'foo' }
MY::<&foo-fn> := { 'not-foo' }
say foo-fn;

my $absolutely-foo = 'foo';
sub fn6 { CALLER::<$absolutely-foo> := 'not-foo';}
fn6;
say $absolutely-foo;

Thus, it appears that rebinding is currently allowed to any name, regardless of the sigil or lack of sigil, if either of the following conditions are met:

The name has any explicit type constraint (including Any and the type constraints imposed by the @ or % sigils), or

The rebinding uses a qualified name.

This rebinding currently happens for both declared variables and parameters, and includes parameters that are not rw or copy.  It even, as the last example indicates, allows re-bindings in ways that (seem to?) violate lexical scope.  (That example was based on a Roast test that's annotated with the comment -- legal?, which suggests that I may at least not be alone in finding this behavior surprising!  Though the test re-binds a is dynamic variable – in some ways, the behavior above is even more surprising).

As far as I can tell, the only names that cannot be re-bound using one of these approaches are those declared as constant.

So four questions:

Am I correctly describing the current behavior? [edit: that is, do the two rules I listed above correctly describe current behavior, or does a correct description require other/additional rules?]

Is that behavior correct/intentional/in line with the spec?  (Despite the presence of S03-binding, I've found remarkably little on rebinding).

If this behavior is not intentional, what are the rules about rebinding supposed to be?

Is there any way to tell Raku "don't rebind this name to a new value, no-really-I-mean-it"?

(This question supersedes my earlier question, which I asked before I realized how easy it is to re-bind name; I'm closing it in favor of this one.  Another related question: Is there a purpose or benefit in prohibiting sigilless variables from rebinding?, which discusses some of the design tradeoffs from the assumption that sigilless variables cannot be re-bound, contrary to several of the examples above.)

Body:
The inconsistent behavior I asked about in the question was a result of a Rakudo bug – Rakudo was allowing rebinding in some situations where it should not have been.  This bug was resolved in Rakudo/Rakudo#4536.

After this resolution, the rules for rebinding are:

Sigilless "variables" cannot be rebound  (and can't be reassigned, so they aren't really "variables")

Variables with a sigil generally can be rebound, subject to the exception below.

If a sigiled variable is part of a Signature, then it cannot be rebound unless it is declared to be rebindable via the is copy or is rw traits.

This applies to a function's Signature (thus sub f($a) { $a := 42 } is illegal)

It also applies to Signatures that are destructured as part of variable declaration with :=.  E.g., in my ($var1, $var2) := ('foo', 'bar'), the right-hand side is a Signature and thus $var1 and $var2 cannot be rebound.

Applying these rules means that all of the following rebindings (which were allowed when the question was asked) are now forbidden:

my Any \a = 'foo';
say a := 'not-foo';

sub fn1(Any \a) { a := 'not-foo';  say a  }
fn1 'foo';
sub fn2(Any $b) { $b := 'not-foo'; say $b }
fn2 'foo';
sub fn3(@c) {  @c := ('not-foo', 'not-foo'); say @c }
fn3 ('foo', 'foo');
sub fn4(+@d) { @d := ('not-foo', 'not-foo'); say @d }
fn4 ('foo', 'foo');
sub fn5(@d is raw) { @d := ('not-foo', 'not-foo'); say @d }
fn5 ('foo', 'foo');

my ($one-foo, $two-foo) := ('foo', 'foo');
$one-foo := 'not-foo';
say $one-foo;

Conversely, applying these rules means that some of the other rebindings shown in the question are (correctly) allowed:

my Any $b := 'foo';
say $b := 'not-foo';
my @c := ('foo', 'foo');
say @c := ('not-foo', 'not-foo');
my @d is List = ('foo', 'foo');
say @d := ('not-foo', 'not-foo');
my %e := (:foo<foo>);
say %e := (:not-foo<not-foo>);

Finally, some of the examples shown in the question involved modifying the contents of a (pseudo) package.  This allows rebindings that would otherwise be forbidden by the rules above:

my \foo = 'foo';
say MY::<foo> := 'not-foo';
sub foo-fn { 'foo' }
MY::<&foo-fn> := { 'not-foo' }
say foo-fn;

my $absolutely-foo = 'foo';
sub fn6 { CALLER::<$absolutely-foo> := 'not-foo';}
fn6;
say $absolutely-foo;

However, just as with using the Metaobject Protocol to access private methods/attributes, using pseudo packages to break Raku's normal rules should be an extreme last resort and does not enjoy the same stability guarantees as other aspects of Raku.


问:
Mysql InnoDB views are becoming slow and Not Using Where Clause
Our Views with 500K rows are becoming terrible since they can not use the Indexing on underlying tables. The where clause on View has no effect on view creation. Is this true that view is created before the Mysql Where clause is applied as in Sql server?
Do we have a way to speed up Our view queries with Where clause and Joins?

One of the issues you have with the MySQL view is that MySQL does not "push" the predicate from the outer query down into the view query. here

```<code>select * from reportview_23 where id = 100;
</code>```

答: You could get into some query limitation inside the view, that prevent view to merge the precidate... Like using LIMIT, DISTINCT, sub-query columns...</p>

Body:
Our Views with 500K rows are becoming terrible since they can not use the Indexing on underlying tables. The where clause on View has no effect on view creation. Is this true that view is created before the Mysql Where clause is applied as in Sql server?
Do we have a way to speed up Our view queries with Where clause and Joins?

One of the issues you have with the MySQL view is that MySQL does not "push" the predicate from the outer query down into the view query. here

select * from reportview_23 where id = 100;