问:
Unable to avoid mousewheel scrolling the whole page when capturing the mousewheel in youtube (Javascript)
I'm trying to get a simple Chrome plugin to skip forward and backwards in youtube when the mousewheel is scrolled vertically.
That is working fine, but unfortunately the page also scrolls up and down when I use the mousehweel. I am trying to cancel the propagation of the mousewheel event with no success.

I have tried to no avail:

e.preventDefault();

return false;

e.stopImmediatePropagation();

Here is the code, as you can see I've tried many things.
There are only two JS files:

```<code>const playerdata = {
  "www.youtube.com" : {
    "keyCodes" : [39, 37],
    //"keyCodes" : [76, 74],
    "elem" : document
  }
}

var curPlayer = playerdata[location.host]

function triggerKeydown(forward) {
    //try {
          var elem;
          var e = new Event('keydown');

          e.keyCode = forward ? curPlayer.keyCodes[0] : curPlayer.keyCodes[1];
          if (typeof curPlayer.elem == "string") {
            elem = document.querySelector(curPlayer.elem)
          } else {
            elem = curPlayer.elem
          }
          //$(window).scrollTop(); // error on $

          e.preventDefault();
          elem.dispatchEvent(e);
          //e.preventDefault();
          //e.stopImmediatePropagation();
    //} catch(ex) {
        //alert(ex); // no error
    //}
    //e.preventDefault();
    //e.stopImmediatePropagation();
    //return false;

}

document.addEventListener("wheel", function(e) {
    //e.preventDefault();
  if (e.deltaX == 0 && e.deltaZ == 0) {
    if (e.deltaY > 0) {
      //e.preventDefault();
      triggerKeydown(false);
    } else if (e.deltaY < 0) {
      //e.preventDefault();
      triggerKeydown(true);

    }
  }
});

</code>```
```<code>function injectScript(file_path, tag) {
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

injectScript(chrome.extension.getURL('video-seek-mousewheel.js'), 'body');

</code>```

答:
The problem with the wheel event is that it ain't synonymical to a scroll event. It merely means the user moved the mousewheel in a particular direction. So it is worthless to call a preventDefault() on the event as it won't be delegated to cause a movement of the browser's viewport..

What you want to achieve is just possible with a little trickery. If the user is hovering the element you want to be controllable using the mosuewheel, we 'disable' scrolling by resetting it's position using window.scrollTo(x, y)

Here's an example. Try hovering the slider and use your mouswheel:

let theSlider = document.getElementById("rangeSlider");
let scrollTop, scrollLeft;
document.addEventListener("mousewheel", function(e) {
  if (document.elementFromPoint(e.clientX, e.clientY) == theSlider) {
    if (e.deltaX == 0 && e.deltaZ == 0) {
      scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
      window.onscroll = dontScroll;
      if (e.deltaY > 0) {
        triggerKeydown(false);
      } else if (e.deltaY < 0) {

        triggerKeydown(true);
      }
    }
  } else {
    window.onscroll = scroll;
  }
});

function triggerKeydown(forward) {
  if (forward) {
    theSlider.value++;
  } else {
    theSlider.value--;
  }
  return false;
}

function scroll() {}

function dontScroll() {
  window.scrollTo(scrollLeft, scrollTop);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  max-width: 100px;
}</code>```

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.

<input type="range" id="rangeSlider" min="0" max="10">

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.

```
</div>
</div>
</p>
<h2>Workaround #2</h2>
<p>As the above solution might fail if the user moves the mousewheel too fast here's another approach. This time if the user hovers the desired element, we simply set the overflow CSS property of the root  element to hidden. This will remove the scrollbars temporarely.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let theSlider = document.getElementById("rangeSlider");
document.addEventListener("mousewheel", function(e) {
  if (document.elementFromPoint(e.clientX, e.clientY) == theSlider) {
    if (e.deltaX == 0 && e.deltaZ == 0) {
      if (e.deltaY > 0) {
        triggerKeydown(false);
      } else if (e.deltaY < 0) {
        triggerKeydown(true);
      }
    }
  }
});

theSlider.addEventListener("mouseover", function(e) {
  document.getElementsByTagName("html")[0].classList.add("noScroll");
});
theSlider.addEventListener("mouseout", function(e) {
  document.getElementsByTagName("html")[0].classList.remove("noScroll");
});

function triggerKeydown(forward) {
  if (forward) {
    theSlider.value++;
  } else {
    theSlider.value--;
  }
  return false;
}</code>```

body {
  max-width: 100px;
}

.noScroll {
  overflow-y: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.
</p>
<input type="range" id="rangeSlider" min="0" max="10">
<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.
</p></code>```

Body:
I'm trying to get a simple Chrome plugin to skip forward and backwards in youtube when the mousewheel is scrolled vertically.
That is working fine, but unfortunately the page also scrolls up and down when I use the mousehweel. I am trying to cancel the propagation of the mousewheel event with no success.

I have tried to no avail:

e.preventDefault();

return false;

e.stopImmediatePropagation();

Here is the code, as you can see I've tried many things.
There are only two JS files:

const playerdata = {
  "www.youtube.com" : {
    "keyCodes" : [39, 37],
    //"keyCodes" : [76, 74],
    "elem" : document
  }
}

var curPlayer = playerdata[location.host]

function triggerKeydown(forward) {
    //try {
          var elem;
          var e = new Event('keydown');

          e.keyCode = forward ? curPlayer.keyCodes[0] : curPlayer.keyCodes[1];
          if (typeof curPlayer.elem == "string") {
            elem = document.querySelector(curPlayer.elem)
          } else {
            elem = curPlayer.elem
          }
          //$(window).scrollTop(); // error on $

          e.preventDefault();
          elem.dispatchEvent(e);
          //e.preventDefault();
          //e.stopImmediatePropagation();
    //} catch(ex) {
        //alert(ex); // no error
    //}
    //e.preventDefault();
    //e.stopImmediatePropagation();
    //return false;

}

document.addEventListener("wheel", function(e) {
    //e.preventDefault();
  if (e.deltaX == 0 && e.deltaZ == 0) {
    if (e.deltaY > 0) {
      //e.preventDefault();
      triggerKeydown(false);
    } else if (e.deltaY < 0) {
      //e.preventDefault();
      triggerKeydown(true);

    }
  }
});

function injectScript(file_path, tag) {
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

injectScript(chrome.extension.getURL('video-seek-mousewheel.js'), 'body');

Body:
The problem with the wheel event is that it ain't synonymical to a scroll event. It merely means the user moved the mousewheel in a particular direction. So it is worthless to call a preventDefault() on the event as it won't be delegated to cause a movement of the browser's viewport..

What you want to achieve is just possible with a little trickery. If the user is hovering the element you want to be controllable using the mosuewheel, we 'disable' scrolling by resetting it's position using window.scrollTo(x, y)

Here's an example. Try hovering the slider and use your mouswheel:

let theSlider = document.getElementById("rangeSlider");
let scrollTop, scrollLeft;
document.addEventListener("mousewheel", function(e) {
  if (document.elementFromPoint(e.clientX, e.clientY) == theSlider) {
    if (e.deltaX == 0 && e.deltaZ == 0) {
      scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
      window.onscroll = dontScroll;
      if (e.deltaY > 0) {
        triggerKeydown(false);
      } else if (e.deltaY < 0) {

        triggerKeydown(true);
      }
    }
  } else {
    window.onscroll = scroll;
  }
});

function triggerKeydown(forward) {
  if (forward) {
    theSlider.value++;
  } else {
    theSlider.value--;
  }
  return false;
}

function scroll() {}

function dontScroll() {
  window.scrollTo(scrollLeft, scrollTop);

}

body {
  max-width: 100px;
}

<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.
</p>
<input type="range" id="rangeSlider" min="0" max="10">
<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.
</p>

Workaround #2

As the above solution might fail if the user moves the mousewheel too fast here's another approach. This time if the user hovers the desired element, we simply set the overflow CSS property of the root  element to hidden. This will remove the scrollbars temporarely.

let theSlider = document.getElementById("rangeSlider");
document.addEventListener("mousewheel", function(e) {
  if (document.elementFromPoint(e.clientX, e.clientY) == theSlider) {
    if (e.deltaX == 0 && e.deltaZ == 0) {
      if (e.deltaY > 0) {
        triggerKeydown(false);
      } else if (e.deltaY < 0) {
        triggerKeydown(true);
      }
    }
  }
});

theSlider.addEventListener("mouseover", function(e) {
  document.getElementsByTagName("html")[0].classList.add("noScroll");
});
theSlider.addEventListener("mouseout", function(e) {
  document.getElementsByTagName("html")[0].classList.remove("noScroll");
});

function triggerKeydown(forward) {
  if (forward) {
    theSlider.value++;
  } else {
    theSlider.value--;
  }
  return false;
}

body {
  max-width: 100px;
}

.noScroll {
  overflow-y: hidden;
}

<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.
</p>
<input type="range" id="rangeSlider" min="0" max="10">
<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet.
</p>


来源: stackexchange

问:
How to collapse/expand view based on dynamic content and maximum size restriction?
I have to support iOS 13 in SwiftUI and I have to implement a view like on the image.

When the user taps on the read more button, the view expands to show all the content. There is no read more button if the view can accommodate all the content.

How can I dynamically change the height when expanding/collapsing this view?

The api returns an array of text or list objects with styling information. I loop through them in a VStack{ ForEach { ... } } when I am building the general information view. I've attached the simplified code here for reference.

With the code below, this is what I have so far, when I collapse the view (limit the maxHeight), I get this:

See how the outer VStack (gray color) gets correctly resized, but the GeneralInformationView stays huge. I tried clipping it, but then it only shows the center of the text.

class ViewState: ObservableObject {
    @Published var isExpanded: Bool = false
    @Published var fullHeight: CGFloat = 0
}

struct ContentView: View {

    @ObservedObject var state: ViewState = ViewState()

    let maximumHeight: CGFloat = 200

    var showReadMoreButton: Bool {
        if state.isExpanded {
            return true
        } else {
            return state.fullHeight > maximumHeight
        }
    }

    var calculatedHeight: CGFloat {
        if !state.isExpanded && state.fullHeight > maximumHeight {
           return maximumHeight
       } else {
           return state.fullHeight
       }
    }

    var body: some View {
        VStack(spacing: 0) {
            GeneralInformationView()
                .background(GeometryReader { geometry in
                    Color.clear.preference(
                        key: HeightPreferenceKey.self,
                        value: geometry.size.height
                    )
                })
                .background(Color(.white))
                .frame(maxHeight: calculatedHeight)

            if showReadMoreButton {
                ReadMoreButton().environmentObject(state)
            }
        }
        .padding(.all, 16)
        .frame(maxWidth: .infinity, maxHeight: calculatedHeight + (showReadMoreButton ? 60 : 0) // 60 is the read more button size
        .onPreferenceChange(HeightPreferenceKey.self) {
            state.fullHeight = $0
        }
        .background(Color(.gray))
    }

    struct HeightPreferenceKey: PreferenceKey {
        static let defaultValue: CGFloat = 0

        static func reduce(value: inout CGFloat,
                           nextValue: () -> CGFloat) {
            value = max(value, nextValue())
        }
    }
}

struct GeneralInformationView: View {
    var body: some View {
        VStack(spacing: 8) {

            Text("I am a title and I could be of any length.")
                .fixedSize(horizontal: false, vertical: true)
                .frame(maxWidth: .infinity, alignment: .leading)

            Text("""
                I am a text view but actually a list with bulletpoints!
                - I can be of any size
                - I am received by API
                - I must not be trunkated!
                - If I don't fit into the outer view when collapsed,
                    then I should just be clipped, from the top of course
            """)
                .fixedSize(horizontal: false, vertical: true)
                .frame(maxWidth: .infinity, alignment: .leading)
                .multilineTextAlignment(.leading)

            Text("I am another text here.")
                .fixedSize(horizontal: false, vertical: true)
                .frame(maxWidth: .infinity, alignment: .leading)

            Text("I am a text and I could be of any length.")
                .fixedSize(horizontal: false, vertical: true)
                .frame(maxWidth: .infinity, alignment: .leading)

            Text("I am a text and I could be of any length.")
                .fixedSize(horizontal: false, vertical: true)
                .frame(maxWidth: .infinity, alignment: .leading)

            Text("I am a text and I could be of any length.")
                .fixedSize(horizontal: false, vertical: true)
                .frame(maxWidth: .infinity, alignment: .leading)
        }
    }
}

struct ReadMoreButton: View {

    @EnvironmentObject var state: ViewState

    var body: some View {
        Button(action: {
            state.isExpanded.toggle()
        }, label: {
            HStack {
                Text(state.isExpanded ? "Collapse" : "Read More")
            }
            .frame(maxWidth: .infinity, minHeight: 60, maxHeight: 60, alignment: .center)
                        .foregroundColor(Color(.red))
                        .background(Color(.white))
            }).overlay(Rectangle()
                        .foregroundColor(.clear)
                        .background(LinearGradient(
                            gradient: Gradient(colors: [.white.opacity(0),
(state.isExpanded ? .white.opacity(0) : .white.opacity(1))]),

                            startPoint: .top,
                            endPoint: .bottom))
                        .frame(height: 25)
                        .alignmentGuide(.top) { $0[.top] + 25 },
                     alignment: .top)
    }
}

```

答:
If it could help someone, I found a solution with the help of this answer.
Wrapping the GeneralInformationView() into a disabled ScrollView, and using minHeight instead of maxHeight in the frame modifier seemed to do the trick!</p>
```<code> var body: some View {
    VStack(spacing: 0) {
            ScrollView { // Here adding a ScrollView
                GeneralInformationView()
                    .background(GeometryReader { geometry in
                        Color.clear.preference(
                            key: HeightPreferenceKey.self,
                            value: geometry.size.height
                        )
                    })
                    .background(Color(.white))
                    .frame(minHeight: calculatedHeight) // Here using minHeight instead of maxHeight
            }
            .disabled(true) // Which is disabled

        if showReadMoreButton {
            ReadMoreButton().environmentObject(state)
        }

    }
// The rest is the same
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If it could help someone, I found a solution with the help of this answer.
Wrapping the GeneralInformationView() into a disabled ScrollView, and using minHeight instead of maxHeight in the frame modifier seemed to do the trick!

 var body: some View {
    VStack(spacing: 0) {
            ScrollView { // Here adding a ScrollView
                GeneralInformationView()
                    .background(GeometryReader { geometry in
                        Color.clear.preference(
                            key: HeightPreferenceKey.self,
                            value: geometry.size.height
                        )
                    })
                    .background(Color(.white))
                    .frame(minHeight: calculatedHeight) // Here using minHeight instead of maxHeight
            }
            .disabled(true) // Which is disabled

        if showReadMoreButton {
            ReadMoreButton().environmentObject(state)
        }

    }
// The rest is the same


问:
Fill matrix with two numbers in a spiral
In the middle of matrix is number x. Matrix is filled with x in a spiral, while the rest is filled with y.

Example:

```<code>int x=4, y=6, v=7, s=9;
</code>```

OUTPUT:

```<code>6 6 6 6 6 6 6 6 4
4 4 4 4 4 4 4 6 4
4 6 6 6 6 6 4 6 4
4 6 4 4 x 6 4 6 4
4 6 4 6 6 6 4 6 4
4 6 4 4 4 4 4 6 4
4 6 6 6 6 6 6 6 4
</code>```

Note: In the output instead of the letter x program should print 4, but I wrote x to make it easier for understanding task.

Spiral filling looks like --> this

```<code>#include <stdio.h>
int main() {
  int v = 7, s = 9, x = 4, y = 6, mat[7][9], i, j, l, k;
  for (i = 0; i < v; i++)
    for (j = 0; j < s; j++)
      mat[i][j] = y;
  for (i = 0; i < v; i++) {
    for (j = 0; j < s; j++) {
      // spiral goes here
      // mat[i][j] = x;
    }
  }
  for (i = 0; i < v; i++) {
    for (j = 0; j < s; j++)
      printf("%4d", mat[i][j]);
    printf("\n");
  }
  return 0;
}
</code>```

EDIT: After applying suggestions, now the whole matrix is filled with y. How to make it fill spiral with x?

答:
In the first iteration of the inner loop if (i == v / 2 && j == s / 2) is always false so you keep doing:

```<code>        mat[l][k--] = x;  // Decrement k
        mat[l++][j] = y;  // Increment l
</code>```

Now add the inner-loop:

```<code>                        ------ Increment k
                        |

    for (k = j; k < s; k++) {
      //if (i == v / 2 && j == s / 2)  // Always false when i is zero
      //  mat[i][j] = x;
      //else
      {
        mat[l][k--] = x;  // Decrement k
        mat[l++][j] = y;  // Increment l
      }
    }
</code>```

So you decrement k and the increment k in the for loop. In other words - k doesn't change and you have an endless loop. In that endless loop you keep incrementing l and use it as array index. That will access the array out of bounds and crash your program.

Body:
In the middle of matrix is number x. Matrix is filled with x in a spiral, while the rest is filled with y.

Example:

int x=4, y=6, v=7, s=9;

OUTPUT:

6 6 6 6 6 6 6 6 4
4 4 4 4 4 4 4 6 4
4 6 6 6 6 6 4 6 4
4 6 4 4 x 6 4 6 4
4 6 4 6 6 6 4 6 4
4 6 4 4 4 4 4 6 4
4 6 6 6 6 6 6 6 4

Note: In the output instead of the letter x program should print 4, but I wrote x to make it easier for understanding task.

Spiral filling looks like --> this

#include <stdio.h>
int main() {
  int v = 7, s = 9, x = 4, y = 6, mat[7][9], i, j, l, k;
  for (i = 0; i < v; i++)
    for (j = 0; j < s; j++)
      mat[i][j] = y;
  for (i = 0; i < v; i++) {
    for (j = 0; j < s; j++) {
      // spiral goes here
      // mat[i][j] = x;
    }
  }
  for (i = 0; i < v; i++) {
    for (j = 0; j < s; j++)
      printf("%4d", mat[i][j]);
    printf("\n");
  }
  return 0;
}

EDIT: After applying suggestions, now the whole matrix is filled with y. How to make it fill spiral with x?

Body:
In the first iteration of the inner loop if (i == v / 2 && j == s / 2) is always false so you keep doing:

        mat[l][k--] = x;  // Decrement k
        mat[l++][j] = y;  // Increment l

Now add the inner-loop:

                        ------ Increment k
                        |

    for (k = j; k < s; k++) {
      //if (i == v / 2 && j == s / 2)  // Always false when i is zero
      //  mat[i][j] = x;
      //else
      {
        mat[l][k--] = x;  // Decrement k
        mat[l++][j] = y;  // Increment l
      }
    }

So you decrement k and the increment k in the for loop. In other words - k doesn't change and you have an endless loop. In that endless loop you keep incrementing l and use it as array index. That will access the array out of bounds and crash your program.


问:
crash the program by implementing a TextWatcher class
when I call addTextChangedListener() method for editText and I implement TextWatcher class and override 3 methods beforTextChanged() onTextChanged() afterTextChanged().
the program does not give any errors but the program fails whit the implementation of the TextWatcher class and when run the app this message is displayed:
"unfortunately, My Application1 has stopped"

this is code:

```<code> package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG= "MainActivity";
    Button btn1, btn2;
    ImageView imageView;
    EditText editText;
    CheckBox checkBox;
    Switch aSwitch;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.firstButton);
        btn2=findViewById(R.id.secondButton);
        imageView=findViewById(R.id.imageView);
        editText.findViewById(R.id.editText);
        checkBox.findViewById(R.id.checkBox);
        aSwitch.findViewById(R.id.swiClick);

        btn1.setText(R.string.btn);
        btn1.setTextColor(getResources().getColor(R.color.purple_700));
        btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "click btn1");
            }
        });

        btn2.setOnClickListener(this);

        imageView.setScaleType(ImageView.ScaleType.FIT_START);

        Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();

        editText.addTextChangedListener(this);

    }
    @Override
    public void onClick(View v) {
        Log.d(TAG, "click btn2");
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Toast.makeText(this, editText.getText(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}
</code>```

in run part show these message:

```<code>  Install successfully finished in 1 s 492 ms.
$ adb shell am start -n "com.example.myapplication1/com.example.myapplication1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 1833 on device '-google_nexus_5-192.168.81.101:5555'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/com.example.myapplication1-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication1, PID: 1833
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at com.example.myapplication1.MainActivity.onCreate(MainActivity.java:36)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 1833 SIG: 9
</code>```

wheres problem?

答:
change your code to this:

```<code> package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG= "MainActivity";
    Button btn1, btn2;
    ImageView imageView;
    EditText editText;
    CheckBox checkBox;
    Switch aSwitch;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.firstButton);
        btn2=findViewById(R.id.secondButton);
        imageView=findViewById(R.id.imageView);
        editText=findViewById(R.id.editText);
        checkBox=findViewById(R.id.checkBox);
        aSwitch=findViewById(R.id.swiClick);

        btn1.setText(R.string.btn);
        btn1.setTextColor(getResources().getColor(R.color.purple_700));
        btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "click btn1");
            }
        });

        btn2.setOnClickListener(this);

        imageView.setScaleType(ImageView.ScaleType.FIT_START);

        Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();

        editText.addTextChangedListener(this);

    }
    @Override
    public void onClick(View v) {
        Log.d(TAG, "click btn2");
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Toast.makeText(this, editText.getText(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}
</code>```

Body:
when I call addTextChangedListener() method for editText and I implement TextWatcher class and override 3 methods beforTextChanged() onTextChanged() afterTextChanged().
the program does not give any errors but the program fails whit the implementation of the TextWatcher class and when run the app this message is displayed:
"unfortunately, My Application1 has stopped"

this is code:

 package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG= "MainActivity";
    Button btn1, btn2;
    ImageView imageView;
    EditText editText;
    CheckBox checkBox;
    Switch aSwitch;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.firstButton);
        btn2=findViewById(R.id.secondButton);
        imageView=findViewById(R.id.imageView);
        editText.findViewById(R.id.editText);
        checkBox.findViewById(R.id.checkBox);
        aSwitch.findViewById(R.id.swiClick);

        btn1.setText(R.string.btn);
        btn1.setTextColor(getResources().getColor(R.color.purple_700));
        btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "click btn1");
            }
        });

        btn2.setOnClickListener(this);

        imageView.setScaleType(ImageView.ScaleType.FIT_START);

        Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();

        editText.addTextChangedListener(this);

    }
    @Override
    public void onClick(View v) {
        Log.d(TAG, "click btn2");
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Toast.makeText(this, editText.getText(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}

in run part show these message:

  Install successfully finished in 1 s 492 ms.
$ adb shell am start -n "com.example.myapplication1/com.example.myapplication1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 1833 on device '-google_nexus_5-192.168.81.101:5555'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/com.example.myapplication1-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication1, PID: 1833
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at com.example.myapplication1.MainActivity.onCreate(MainActivity.java:36)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 1833 SIG: 9

wheres problem?

Body:
change your code to this:

 package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG= "MainActivity";
    Button btn1, btn2;
    ImageView imageView;
    EditText editText;
    CheckBox checkBox;
    Switch aSwitch;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.firstButton);
        btn2=findViewById(R.id.secondButton);
        imageView=findViewById(R.id.imageView);
        editText=findViewById(R.id.editText);
        checkBox=findViewById(R.id.checkBox);
        aSwitch=findViewById(R.id.swiClick);

        btn1.setText(R.string.btn);
        btn1.setTextColor(getResources().getColor(R.color.purple_700));
        btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "click btn1");
            }
        });

        btn2.setOnClickListener(this);

        imageView.setScaleType(ImageView.ScaleType.FIT_START);

        Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();

        editText.addTextChangedListener(this);

    }
    @Override
    public void onClick(View v) {
        Log.d(TAG, "click btn2");
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Toast.makeText(this, editText.getText(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}


问:
Android Studio - Open DatePickerDialog from an AppCompatDialog
i want to open a DatePickerDialog from an AppCompatDialog.

```<code>private fun pickDate() {
    etProduktDatum.setOnClickListener {
        getDateTimeCalendar()

        DatePickerDialog(this,this,year,month,day).show()
    }

}
</code>```

When i try to create it, android studio complains that there is a Type mismatch on the first parameter of DatePickerDialog:

Type mismatch.
Required: Contex
Found: EinkaufslisteProduktgekauftDialog

This is my Dialog:

```<code>class EinkaufslisteProduktGekauftDialog (context: Context, var produkt : Produkt?, var addDialogListener: AddDialogListener) : AppCompatDialog(context), DatePickerDialog.OnDateSetListener{

var day = 0
var month = 0
var year = 0

var savedday = 0
var savedmonth = 0
var savedyear = 0
</code>```

答:
You can take the context of the activity where ever you are in. You don't want the context of your dialog. Or you call this.getContext (I don't know the kotlin way there).

DatePickerDialog(this.context,this,year,month,day).show()

Body:
i want to open a DatePickerDialog from an AppCompatDialog.

private fun pickDate() {
    etProduktDatum.setOnClickListener {
        getDateTimeCalendar()

        DatePickerDialog(this,this,year,month,day).show()
    }

}

When i try to create it, android studio complains that there is a Type mismatch on the first parameter of DatePickerDialog:

Type mismatch.
Required: Contex
Found: EinkaufslisteProduktgekauftDialog

This is my Dialog:

class EinkaufslisteProduktGekauftDialog (context: Context, var produkt : Produkt?, var addDialogListener: AddDialogListener) : AppCompatDialog(context), DatePickerDialog.OnDateSetListener{

var day = 0
var month = 0
var year = 0

var savedday = 0
var savedmonth = 0
var savedyear = 0


问:
How can I create a column containing the maximum across columns in SQL Server
I have a table CHA with many columns. There are two sets of 5 columns containing numeric data. I am looking to aggregate this data.

Select for the table below:

```<code>SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
              DMD1, DMD0, DMD2, DMD3, DMD4, DRC1, DRC0, DRC2, DRC3, DRC4, CHG0
FROM            Reporter.CHA
</code>```

I am looking to add some aggregate functions DMD_Min, DMD_Max, etc.

I have the following syntax for the new value, but I keep getting an error.

```<code>(SELECT MIN(MIN_DMD) FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
</code>```

Can anyone proved a better method for finding the row by row aggregate across columns?

Edit:

The error I am seeing in SQL server is:

Error in FROM clause: near 'Values'

Error in FROM clause: near ')'

Unable to parse query text.

This happens when I try to update the query from the select statement above to add in the DMD_MIN column as below:

```<code>SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL,
JobTitle, [Function], MGR, MonthNum, DMD1, DMD0, DMD2, DMD3, DMD4,
DRC1, DRC0, DRC2, DRC3, DRC4, CHG0,
(SELECT MIN(MIN_DMD) FROM (VALUES
(DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
FROM            Reporter.Compare_HA_Unpivot
</code>```

答:
To Larnu's point, your table design is bad and it's leading you to write painful tedious sql statements. Instead consider as a half-way between complete-redesign and tedious-sql something like:

```<code>SELECT Project_Num, JobTitle, [Function], DMDtype, Min(DMD), Max(DMD)
FROM
    (
        SELECT Project_Num, JobTitle, [Function], 'DMD0' as DMDType, DMD0 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD1', DMD1 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD2', DMD2 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD3', DMD3 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD4', DMD5 FROM Reporter.Cha
) sub
GROUP BY Project_Num, JobTitle, [Function], DMDtype;
</code>```

If you want the min and max across all DMD columns, then just remove dmdtype from your GROUP BY and SELECT. Ultimately, consider changing your table to look the resultset from that UNION subquery.

Body:
I have a table CHA with many columns. There are two sets of 5 columns containing numeric data. I am looking to aggregate this data.

Select for the table below:

SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
              DMD1, DMD0, DMD2, DMD3, DMD4, DRC1, DRC0, DRC2, DRC3, DRC4, CHG0
FROM            Reporter.CHA

I am looking to add some aggregate functions DMD_Min, DMD_Max, etc.

I have the following syntax for the new value, but I keep getting an error.

(SELECT MIN(MIN_DMD) FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD

Can anyone proved a better method for finding the row by row aggregate across columns?

Edit:

The error I am seeing in SQL server is:

Error in FROM clause: near 'Values'

Error in FROM clause: near ')'

Unable to parse query text.

This happens when I try to update the query from the select statement above to add in the DMD_MIN column as below:

SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL,
JobTitle, [Function], MGR, MonthNum, DMD1, DMD0, DMD2, DMD3, DMD4,
DRC1, DRC0, DRC2, DRC3, DRC4, CHG0,
(SELECT MIN(MIN_DMD) FROM (VALUES
(DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
FROM            Reporter.Compare_HA_Unpivot

Body:
To Larnu's point, your table design is bad and it's leading you to write painful tedious sql statements. Instead consider as a half-way between complete-redesign and tedious-sql something like:

SELECT Project_Num, JobTitle, [Function], DMDtype, Min(DMD), Max(DMD)
FROM
    (
        SELECT Project_Num, JobTitle, [Function], 'DMD0' as DMDType, DMD0 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD1', DMD1 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD2', DMD2 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD3', DMD3 FROM Reporter.Cha
        UNION ALL
        SELECT Project_Num, JobTitle, [Function], 'DMD4', DMD5 FROM Reporter.Cha
) sub
GROUP BY Project_Num, JobTitle, [Function], DMDtype;

If you want the min and max across all DMD columns, then just remove dmdtype from your GROUP BY and SELECT. Ultimately, consider changing your table to look the resultset from that UNION subquery.


问:
How do I sort a query object in ColdFusion 7?
I have a query object, with, say, fifteen rows returned. For all intents and purposes, I can't modify the SQL which generates the query object, but I need to sort this query object by column. Is there a way to do this in ColdFusion 7 without resorting to an external library?

Edit: I should add: I've run a query on this query object, and done an ORDER BY clause in this query of the query. Is there another way of doing this?

答:
Please check the next url

http://www.coldfusioncookbook.com/entries/How-do-I-resort-a-query.html

```<code><cfquery name="original" datasource="foo" >
  select name, age, rank
  from people
  order by age asc
</cfquery>

<!--- Resort by name --->
<cfquery name="newQuery" dbtype="query">
  select name, age, rank
  from original
  order by name asc
</cfquery>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Please check the next url

http://www.coldfusioncookbook.com/entries/How-do-I-resort-a-query.html

<cfquery name="original" datasource="foo" >
  select name, age, rank
  from people
  order by age asc
</cfquery>

<!--- Resort by name --->
<cfquery name="newQuery" dbtype="query">
  select name, age, rank
  from original
  order by name asc
</cfquery>

ContentLicense: CC BY-SA 3.0


问:
Getting a 404 error at random times when trying run a search endpoint on Spotify's API using Spotipy?
Just for simplicity, say I want to search Beyonce 1000 times

```<code>artist_name_list = []
for i in np.arange (0, 1000, 1):
  searchResults = sp.search("beyonce",1,0,"artist")
  artist = searchResults['artists']['items'][0]
  artist_name = artist['name']
  artist_name_list.append(artist_name)
</code>```

When I run this, I get a 404 error at seemingly random points, which I can tell because the len(artist_name_list) differs every time I run it.

```<code>HTTP Error for GET to https://api.spotify.com/v1/search with Params: {'q': 'beyonce', 'limit': 1, 'offset': 0, 'type': 'artist', 'market': None} returned 404 due to None
</code>```

Could someone help understand what's going on? It seemed to run earlier in the day.

Thank you!

答:
The only thing I can think of is that you're hitting some limitation on the API usage, maybe try inserting a pause between API requests, e.g. using time.sleep:

import time
time.sleep(5) # waits for 5 seconds
```

Body:
Just for simplicity, say I want to search Beyonce 1000 times

artist_name_list = []
for i in np.arange (0, 1000, 1):
  searchResults = sp.search("beyonce",1,0,"artist")
  artist = searchResults['artists']['items'][0]
  artist_name = artist['name']
  artist_name_list.append(artist_name)

When I run this, I get a 404 error at seemingly random points, which I can tell because the len(artist_name_list) differs every time I run it.

HTTP Error for GET to https://api.spotify.com/v1/search with Params: {'q': 'beyonce', 'limit': 1, 'offset': 0, 'type': 'artist', 'market': None} returned 404 due to None

Could someone help understand what's going on? It seemed to run earlier in the day.

Thank you!


问:
How to customize Dropdown Button and items in flutter?
Today I tried to design a dropdown button with customized items in it where I can select all items or deselect all items with one click. But I didn't understand the approach how to do it. So please help me guys how to approach the required design and below I placed my design and required design.

and here is my code

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

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  String dropdownvalue = 'Apple';

  var items =  ['Apple','Banana','Grapes','Orange','watermelon','Pineapple'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDownList Example"),
      ),
      body: Container(
        padding: EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("DropDownButton"),
                Container(
                  height: 40,
                  padding: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                        color: Colors.grey, style: BorderStyle.solid, width: 0.80),
                  ),
                  child: DropdownButtonHideUnderline(
                    child: DropdownButton(
                      elevation: 0,
                      value: dropdownvalue,

                      icon: Icon(Icons.keyboard_arrow_down),

                      items:items.map((String items) {
                        return DropdownMenuItem(
                            value: items,
                            child: Text(items)
                        );
                      }
                      ).toList(),

                      onChanged: (String? newValue){
                        setState(() {
                          dropdownvalue = newValue!;
                        });
                      },

                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
You can use dropdown_button2 package for this:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String dropdownvalue = 'Apple';
  var items = [
    'Apple',
    'Banana',
    'Grapes',
    'Orange',
    'watermelon',
    'Pineapple'
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDownList Example"),
      ),
      body: Container(
        padding: EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("DropDownButton"),
                Container(
                    height: 40,
                    padding: EdgeInsets.all(5.0),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30.0),
                      border: Border.all(color: Colors.grey, style: BorderStyle.solid, width: 0.80),
                    ),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton2(
                        hint: Text(
                          'Select Item',
                          style: TextStyle(
                            fontSize: 14,
                            color: Theme.of(context).hintColor,
                          ),
                        ),
                        items: items
                            .map((item) => DropdownMenuItem<String>(
                                  value: item,
                                  child: Text(
                                    item,
                                    style: const TextStyle(
                                      fontSize: 14,
                                    ),
                                  ),
                                ))
                            .toList(),
                        value: dropdownvalue,
                        onChanged: (String? newValue) {
                          setState(() {
                            dropdownvalue = newValue!;
                          });
                        },
                        buttonHeight: 40,
                        buttonWidth: 140,
                        itemHeight: 40,
                      ),
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

final result:

Body:
Today I tried to design a dropdown button with customized items in it where I can select all items or deselect all items with one click. But I didn't understand the approach how to do it. So please help me guys how to approach the required design and below I placed my design and required design.

and here is my code

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  String dropdownvalue = 'Apple';

  var items =  ['Apple','Banana','Grapes','Orange','watermelon','Pineapple'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDownList Example"),
      ),
      body: Container(
        padding: EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("DropDownButton"),
                Container(
                  height: 40,
                  padding: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                        color: Colors.grey, style: BorderStyle.solid, width: 0.80),
                  ),
                  child: DropdownButtonHideUnderline(
                    child: DropdownButton(
                      elevation: 0,
                      value: dropdownvalue,

                      icon: Icon(Icons.keyboard_arrow_down),

                      items:items.map((String items) {
                        return DropdownMenuItem(
                            value: items,
                            child: Text(items)
                        );
                      }
                      ).toList(),

                      onChanged: (String? newValue){
                        setState(() {
                          dropdownvalue = newValue!;
                        });
                      },

                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Body:
You can use dropdown_button2 package for this:

import 'package:flutter/material.dart';
import 'package:dropdown_button2/dropdown_button2.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String dropdownvalue = 'Apple';
  var items = [
    'Apple',
    'Banana',
    'Grapes',
    'Orange',
    'watermelon',
    'Pineapple'
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DropDownList Example"),
      ),
      body: Container(
        padding: EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("DropDownButton"),
                Container(
                    height: 40,
                    padding: EdgeInsets.all(5.0),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30.0),
                      border: Border.all(color: Colors.grey, style: BorderStyle.solid, width: 0.80),
                    ),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton2(
                        hint: Text(
                          'Select Item',
                          style: TextStyle(
                            fontSize: 14,
                            color: Theme.of(context).hintColor,
                          ),
                        ),
                        items: items
                            .map((item) => DropdownMenuItem<String>(
                                  value: item,
                                  child: Text(
                                    item,
                                    style: const TextStyle(
                                      fontSize: 14,
                                    ),
                                  ),
                                ))
                            .toList(),
                        value: dropdownvalue,
                        onChanged: (String? newValue) {
                          setState(() {
                            dropdownvalue = newValue!;
                          });
                        },
                        buttonHeight: 40,
                        buttonWidth: 140,
                        itemHeight: 40,
                      ),
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

final result:


问:
Symfony,NelmioApiDoc,Swagger,OpenApi: Annotate a class with jsonSerialized model
I created a little example:

class Response
{
    /**
     * @OA\Property(ref=@Model(type=EncodedModel::class))
     */
    public RuntimeClass $filters;
}
class RuntimeClass implements JsonSerializable
{
    public int $field;
    public function jsonSerialize()
    {
        $model = new EncodedModel();
        $model->field = "$this->field";
        return $model;
    }
}
class EncodedModel {
    public string $field;
}
```
<p>I have an endpoint which response is of model <code>Response::class</code>.<br />
<code>Response</code> class has a field $filters of type <code>RuntimeClass</code> BUT when json encoded, due to JsonSerializable implemented function, it is displayed as a class <code>EncodedModel</code>.</p>
<p>My goal is to obtain in the generated api doc, that the field Response->filters is of type <code>EncodedModel</code> and not <code>RuntimeClass</code>.</p>
<p>I have annotated the field directly with <code>@OA\Property(ref=@Model(type=EncodedModel::class))</code> and it does the trick but i don't like it so much.<br />
As i see it, it is a <code>RuntimeClass</code> class responsability tell that json encoded results as a <code>EncodedModel</code> class and not a <code>RuntimeClass</code> class. Otherwise everytime i use <code>RuntimeClass</code> as a model field i have to remember to annotate it.</p>
<p>What i was hoping is that annotating the class like this would do the trick as well once for all, but it doesn't :/</p>
<pre class="lang-php prettyprint-override"><code>/**
 * @Model(type=EncodedModel::class)
 */
class RuntimeClass implements JsonSerializable
...
</code>```

Anyone know if it is possible some way?

Thank you

----------------------- EDIT

Sorry i solved myself, i was about at the solution, just wrong annotation:

/**
 * @OA\Schema(ref=@Model(type=EncodedModel::class))
 */
class RuntimeClass implements JsonSerializable
...
```

Thank you anyway

Body:
I created a little example:

class Response
{
    /**
     * @OA\Property(ref=@Model(type=EncodedModel::class))
     */
    public RuntimeClass $filters;
}
class RuntimeClass implements JsonSerializable
{
    public int $field;
    public function jsonSerialize()
    {
        $model = new EncodedModel();
        $model->field = "$this->field";
        return $model;
    }
}
class EncodedModel {
    public string $field;
}

I have an endpoint which response is of model Response::class.

Response class has a field $filters of type RuntimeClass BUT when json encoded, due to JsonSerializable implemented function, it is displayed as a class EncodedModel.

My goal is to obtain in the generated api doc, that the field Response->filters is of type EncodedModel and not RuntimeClass.

I have annotated the field directly with @OA\Property(ref=@Model(type=EncodedModel::class)) and it does the trick but i don't like it so much.

As i see it, it is a RuntimeClass class responsability tell that json encoded results as a EncodedModel class and not a RuntimeClass class. Otherwise everytime i use RuntimeClass as a model field i have to remember to annotate it.

What i was hoping is that annotating the class like this would do the trick as well once for all, but it doesn't :/

/**
 * @Model(type=EncodedModel::class)
 */
class RuntimeClass implements JsonSerializable
...

Anyone know if it is possible some way?

Thank you

----------------------- EDIT

Sorry i solved myself, i was about at the solution, just wrong annotation:

/**
 * @OA\Schema(ref=@Model(type=EncodedModel::class))
 */
class RuntimeClass implements JsonSerializable
...

Thank you anyway


问:
Connect to Kafka does not work when called by the openfaas service
Connect to Kafka normally via Java without using openfaas. (Successful)

Connect to Kafka does not work when called by the openfaas service.

When running a function as service created by openfaas, it cannot connect to Kafka. (Kafka is running on Docker)

```<code>docker-compose.yml :

version: '2'
services:
  zookeeper:
    container_name: zookeeper
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - 22181:2181

kafka:
    container_name: kafka
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,PLAINTEXT_HOST://0.0.0.0:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
</code>```
```<code>Error:
Connection to node -1 (localhost/127.0.0.1:29092) could not be established. Broker may not be available.
</code>```
```<code>String topic = "Request";
String KAFKA_BROKERS = "localhost:9092";

Properties props = new Properties();
            props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_BROKERS);
            props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
            props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName());

producer = new KafkaProducer(props);
</code>```

答:
Java also runs on Docker

localhost refers to that Java container, which is not a Kafka service.

Make sure your containers run in the same Docker network, then you need to reach external services using their container names, e.g. "kafka:9092", assuming that is what the container hostname is.

You will also need to make sure KAFKA_LISTENERS=PLAINTEXT://0.0.0.0:9092

Body:
Connect to Kafka normally via Java without using openfaas. (Successful)

Connect to Kafka does not work when called by the openfaas service.

When running a function as service created by openfaas, it cannot connect to Kafka. (Kafka is running on Docker)

docker-compose.yml :

version: '2'
services:
  zookeeper:
    container_name: zookeeper
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - 22181:2181

kafka:
    container_name: kafka
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,PLAINTEXT_HOST://0.0.0.0:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

Error:
Connection to node -1 (localhost/127.0.0.1:29092) could not be established. Broker may not be available.

String topic = "Request";
String KAFKA_BROKERS = "localhost:9092";

Properties props = new Properties();
            props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_BROKERS);
            props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
            props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName());

producer = new KafkaProducer(props);


问:
Encryption and Decryption in Java and Javascript (Nodejs)
I encrypt a text in Java and want to decrypt in Javascript and vice versa, my Java code looks like this

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec k = new SecretKeySpec(this.key.getBytes(), "AES");
c.init(Cipher.ENCRYPT_MODE, k);

byte[] encryptedData = c.doFinal(this.value.getBytes());
byte[] iv = c.getIV();

sb.append(new String(Base64.getEncoder().encode(iv)));
sb.append(';');
sb.append(new String(Base64.getEncoder().encode(encryptedData)));
// send sb.toString() to the other end
```
<p>I tried node-forge and elliptic for decryption in Nodejs, in node-forge I have an error complaining about tag which I don't have, can someone provide a solution in Nodejs.</p>
<p>Javascript Code</p>
<pre class="lang-js prettyprint-override"><code>function convertFromMxBase64(FormatEncryptedString) {
    const speratorIndex = FormatEncryptedString.indexOf(';');
    const encryptedBase64 = mxFormatEncryptedString.substr(speratorIndex + 1);
    const ivBase64 = mxFormatEncryptedString.substr(0, speratorIndex);

    return {
        iv: forge.util.createBuffer(forge.util.decode64(ivBase64), 'utf8'),
        payload: forge.util.createBuffer(forge.util.decode64(encryptedBase64), 'utf8')
    };
}

function decrypt() {

    let { iv, payload } = convertFromMxBase64(mxCombi);

    const key = forge.util.createBuffer(theKey, 'utf8');

    var cipher = forge.cipher.createDecipher("AES-GCM", key); // forge.rc2.createDecryptionCipher(key);
    cipher.start({ iv });
    cipher.update(payload);
    cipher.finish();
    var encrypted = cipher.output;
    // outputs encrypted hex
    console.log(encrypted.toHex());
}
</code>```

答:
The GCM mode uses by definition a tag which is needed for the authenticity/integrity check.

The tag issue on the NodeJS side is caused by not taking the authentication tag into account. On the Java side this is not necessary because the SunJCE provider does this automatically by appending the tag to the ciphertext: Therefore, the last 16 bytes of the result are the tag. On the NodeJS side, in contrast, ciphertext and tag are handled detached, so that both parts must be explicitly separated, e.g.:

var ciphertext = forge.util.createBuffer(payload.data.substring(0, payload.length() - 16));
var tag = forge.util.createBuffer(payload.data.substring(payload.length() - 16));
```
<p>Tag and ciphertext must be passed to the <code>cipher</code> instance as follows:</p>
<pre class="lang-js prettyprint-override"><code>cipher.start({ iv:iv, tag:tag }); // apply tag
cipher.update(ciphertext); // apply ciphertext
</code>```

Another bug is that the UTF-8 encoding is used when creating iv and payload. This is wrong, the data must be passed as binary string, i.e. 'utf8' must either be replaced by 'binary' or removed completely.

iv: forge.util.createBuffer(forge.util.decode64(ivBase64)),
payload: forge.util.createBuffer(forge.util.decode64(encryptedBase64))
```

Also, in getBytes() of the Java code an encoding should be specified, e.g. getBytes(StandardCharsets.UTF_8). If this is not done, a platform-dependent default encoding is used, which means that different encodings can be applied depending on the environment.

With these changes, decryption works on the NodeJS side.

Body:
I encrypt a text in Java and want to decrypt in Javascript and vice versa, my Java code looks like this

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec k = new SecretKeySpec(this.key.getBytes(), "AES");
c.init(Cipher.ENCRYPT_MODE, k);

byte[] encryptedData = c.doFinal(this.value.getBytes());
byte[] iv = c.getIV();

sb.append(new String(Base64.getEncoder().encode(iv)));
sb.append(';');
sb.append(new String(Base64.getEncoder().encode(encryptedData)));
// send sb.toString() to the other end

I tried node-forge and elliptic for decryption in Nodejs, in node-forge I have an error complaining about tag which I don't have, can someone provide a solution in Nodejs.

Javascript Code

function convertFromMxBase64(FormatEncryptedString) {
    const speratorIndex = FormatEncryptedString.indexOf(';');
    const encryptedBase64 = mxFormatEncryptedString.substr(speratorIndex + 1);
    const ivBase64 = mxFormatEncryptedString.substr(0, speratorIndex);

    return {
        iv: forge.util.createBuffer(forge.util.decode64(ivBase64), 'utf8'),
        payload: forge.util.createBuffer(forge.util.decode64(encryptedBase64), 'utf8')
    };
}

function decrypt() {

    let { iv, payload } = convertFromMxBase64(mxCombi);

    const key = forge.util.createBuffer(theKey, 'utf8');

    var cipher = forge.cipher.createDecipher("AES-GCM", key); // forge.rc2.createDecryptionCipher(key);
    cipher.start({ iv });
    cipher.update(payload);
    cipher.finish();
    var encrypted = cipher.output;
    // outputs encrypted hex
    console.log(encrypted.toHex());
}

Body:
The GCM mode uses by definition a tag which is needed for the authenticity/integrity check.

The tag issue on the NodeJS side is caused by not taking the authentication tag into account. On the Java side this is not necessary because the SunJCE provider does this automatically by appending the tag to the ciphertext: Therefore, the last 16 bytes of the result are the tag. On the NodeJS side, in contrast, ciphertext and tag are handled detached, so that both parts must be explicitly separated, e.g.:

var ciphertext = forge.util.createBuffer(payload.data.substring(0, payload.length() - 16));
var tag = forge.util.createBuffer(payload.data.substring(payload.length() - 16));

Tag and ciphertext must be passed to the cipher instance as follows:

cipher.start({ iv:iv, tag:tag }); // apply tag
cipher.update(ciphertext); // apply ciphertext

Another bug is that the UTF-8 encoding is used when creating iv and payload. This is wrong, the data must be passed as binary string, i.e. 'utf8' must either be replaced by 'binary' or removed completely.

iv: forge.util.createBuffer(forge.util.decode64(ivBase64)),
payload: forge.util.createBuffer(forge.util.decode64(encryptedBase64))

Also, in getBytes() of the Java code an encoding should be specified, e.g. getBytes(StandardCharsets.UTF_8). If this is not done, a platform-dependent default encoding is used, which means that different encodings can be applied depending on the environment.

With these changes, decryption works on the NodeJS side.


问:
Is there a way to stop the "Source" block from generating agents after a specific time in AnyLogic?
Utilizing a source generating agents on an Interarrival time basis, I would like to stop the source block from generating agents after a certain amount of time passing so that the model can continue to process the agents.

答:
Sure. If it is a inter-arrival source block, make it use a variable as the interrarrival time, of type double:

Then, create an event that triggers once only, after your specific time. Make it change the variable to 0 as below. Make SURE to trigger it not at time 0 (as in the screen but when you need it!):

NOTE: Do not set myRate = 0;. Instead, set it to infinity` to actually have no more arrivals.


问:
How to get user name instead of SID during WMI logcollection
I'm looking for a possible solution to convert a Windows user SID to a username.

I am running WQL queries against some local namespace and would like to know if there are any possibilities to get a username instead SID like an event viewer. I am using WBEMTest for testing.

Screenshot for reference.

答: SELECT * FROM Win32_AccountSID should get you a list you can match the SID to the name.


问:
Should I use AWS Glue or Spark on EMR for processing binary data to parquet format
I have a work requirement of reading binary data from sensors and produce parquet output results for Analytics.

For storage I have chosen s3 and Dynamodb.

For processing engine I’m confused on how to choose between AWS EMR or AWS Glue.

Data processing code base will be maintained in python coupled with Spark.

Please post your suggestion on choosing between AWS EMR or AWS Glue.

答:
It's an opinion based question and now you have AWS EMR Serverless.

AWS Glue is 1) more managed and thus with restrictions, and 2) imho issues with crawling for schema changes to consider, 3) own interpretation of dataframes 4) and less run-time configuration and 5) less options for serverless scalability. There seems to a few bugs etc. that keep on popping up.

AWS EMR is 1) an AWS platform easy enough to configure, 2) with the AWS flavour of what they think the best way of running Spark is, 3) some limitations in terms of subsequently scaling down resources when using dynamic scaling out, 4) a platform that uses Spark so there will be a bigger pool of persons to hire, 5) allowing bootstrapping of software not standardly supplied, and selection of standard software, such as, say, HBase.

So, comparable to an extent. And divergent in other ways; AWS Glue is ETL/ELT, AWS EMR is that with more capabilities.


问:
Brownie: CompilerError: File outside of allowed directories
I'm trying to import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" to my contract but i encountered this error. CompilerError: solc returned the following errors:

contracts/Lottery.sol:4:1: ParserError: Source "C:/Users/Алексей/.brownie/packages/smartcontractkit/chainlink-brownie contracts@1.1.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" not found: File outside of allowed directories.
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
^--------------------------------------------------------------------------^

This is my contract (Lottery.sol):

```<code>    // SPDX-License-Identifier: MIT
    pragma solidity ^0.6.6;

    import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

    contract Lottery {

        address payable[] public players;
        uint256 public usdEnterFee;
        AggregatorV3Interface internal ethUsdPriceFeed;

        constructor(address _priceFeedAddress) public {
            usdEnterFee = 50 * (10 ** 18);
            ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
        }

        function enter() public payable {
            players.push(msg.sender);
        }

        function getEnterFee() public view returns(uint256) {

        }

        function startLottery() public {

        }

        function endLottery() public {

        }

    }
</code>```

This is brownie-config.yaml:

```<code>    dependencies:
      - smartcontractkit/chainlink-brownie-contracts@1.1.1
    compiler:
      solc:
        remappings:
          - '@chainlink=smartcontractkit/chainlink-brownie contracts@1.1.1'
</code>```

Error:
enter image description here

答:
it doesn't find aggregatorV3interface.sol

Have you installed it?

try pip3 install @chainlink/contracts or npm install @chainlink/contracts

if you already done it, check if it is in the right path

Body:
I'm trying to import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" to my contract but i encountered this error. CompilerError: solc returned the following errors:

contracts/Lottery.sol:4:1: ParserError: Source "C:/Users/Алексей/.brownie/packages/smartcontractkit/chainlink-brownie contracts@1.1.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" not found: File outside of allowed directories.
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
^--------------------------------------------------------------------------^

This is my contract (Lottery.sol):

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.6.6;

    import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

    contract Lottery {

        address payable[] public players;
        uint256 public usdEnterFee;
        AggregatorV3Interface internal ethUsdPriceFeed;

        constructor(address _priceFeedAddress) public {
            usdEnterFee = 50 * (10 ** 18);
            ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
        }

        function enter() public payable {
            players.push(msg.sender);
        }

        function getEnterFee() public view returns(uint256) {

        }

        function startLottery() public {

        }

        function endLottery() public {

        }

    }

This is brownie-config.yaml:

    dependencies:
      - smartcontractkit/chainlink-brownie-contracts@1.1.1
    compiler:
      solc:
        remappings:
          - '@chainlink=smartcontractkit/chainlink-brownie contracts@1.1.1'

Error:
enter image description here


问:
How to make my CodeChef solution code faster?
I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:

Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?

Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.

Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.

Sample Input:

```<code>3
5 3
10 10
4 8
</code>```

Sample Output:

```<code>2
20
8
</code>```

My code is as follows:

```<code>#include <iostream>
using namespace std;

int main()
{
    unsigned int t,B,M;
    cin>>t;
    while(t--)
    {
        cin>>M>>B;
        if(B==M)
        {
            cout<<B+M<<endl;
        }
        else
        {
            for(int i=1;B!=M;i++)
            {
                if(B>M)
                B=B-M;
                else
                M=M-B;
            }
            cout<<M+B<<endl;
        }
    }
    return 0;
}
</code>```

答:
After realizing that your code was correct, I wondered where could be any algorithmic improvement. And I realized that eating as many chocolate from the peer as one has was in fact close to a modulo operation. If both number are close, a minus operation could be slightly faster than a modulo one, but if one number is high, while the other is 1, you immediately get it instead of looping a great number of times...

The key to prevent stupid errors is to realize that if a modulo is 0, that means that the high number is a multiple of the small one and we must stop immediately writing twice the lower value.

And care should be taken that if one of the initial counts are 0, the total number will never change.

So the outer loop should become:

```<code>    if(B==M || B == 0 || M == 0)
    {
        cout<<B+M<<"\0";
    }
    else {
        for (;;) {
            if (M < B) {
                B = B % M;
                if (B == 0) {
                    cout << M * 2 << '\n';
                    break;
                }
            }
            else {
                M = M % B;
                if (M == 0) {
                    cout << B * 2 << '\n';
                    break;
                }
            }
        }
    }
    ...
</code>```

Note: no infinite loop is possible here because a modulo ensures that  for example is M > B > 0' after M = M % Byou will haveB > M >= 0and as the case== 0` is explicitely handled the number of loops cannot be higher than the lower number.

Body:
I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:

Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?

Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.

Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.

Sample Input:

3
5 3
10 10
4 8

Sample Output:

2
20
8

My code is as follows:

#include <iostream>
using namespace std;

int main()
{
    unsigned int t,B,M;
    cin>>t;
    while(t--)
    {
        cin>>M>>B;
        if(B==M)
        {
            cout<<B+M<<endl;
        }
        else
        {
            for(int i=1;B!=M;i++)
            {
                if(B>M)
                B=B-M;
                else
                M=M-B;
            }
            cout<<M+B<<endl;
        }
    }
    return 0;
}

Body:
After realizing that your code was correct, I wondered where could be any algorithmic improvement. And I realized that eating as many chocolate from the peer as one has was in fact close to a modulo operation. If both number are close, a minus operation could be slightly faster than a modulo one, but if one number is high, while the other is 1, you immediately get it instead of looping a great number of times...

The key to prevent stupid errors is to realize that if a modulo is 0, that means that the high number is a multiple of the small one and we must stop immediately writing twice the lower value.

And care should be taken that if one of the initial counts are 0, the total number will never change.

So the outer loop should become:

    if(B==M || B == 0 || M == 0)
    {
        cout<<B+M<<"\0";
    }
    else {
        for (;;) {
            if (M < B) {
                B = B % M;
                if (B == 0) {
                    cout << M * 2 << '\n';
                    break;
                }
            }
            else {
                M = M % B;
                if (M == 0) {
                    cout << B * 2 << '\n';
                    break;
                }
            }
        }
    }
    ...

Note: no infinite loop is possible here because a modulo ensures that  for example is M > B > 0' after M = M % Byou will haveB > M >= 0and as the case== 0` is explicitely handled the number of loops cannot be higher than the lower number.


问:
Distance measurements unit in 2d image points (python)
I used Python + Numpy to calculate the distance perpendicular to a point to a line defined by two points in a two-dimensional image (the coordinates of each point are the location of the point in the two-dimensional matrix of pixels.)

    p1, p2, p3 # as the points

    # calculating the distance of p3 to the line constructed out of the p1 and p2
    # distance formula using the cross product approach
    d = numpy.linalg.norm(np.cross(p2-p1, p1-p3))/numpy.linalg.norm(p2-p1)
```

The question is :

What is the output measurement unit of distances that is calculated in this way?

Is the distance d calculated in 'pixel'?

If the answer is yes,
How can I convert it to the millimeter and other measurement units?

答:
If the points come from an actual image, the distance is in "pixels" (In actuality, the distance is in whatever arbitrary unit you assign to values of your p1, p2, p3 - math doesn't care, for Python it's just a number) - but not the ones on your screen. If you have an 2x2 image and tell it to show up fullscreen, you will obviously get 1 of those virtual pixels take thousands of actual pixels on your display.
If you take 4k image and try to display on a 640x480 monitor, you will obviously have to  combine few virtual pixels to determine what color you need to show.
In the same vein, you cannot convert that to other measurement units without setting some arbitrary conversion dependant on your exact setup.

Body:
I used Python + Numpy to calculate the distance perpendicular to a point to a line defined by two points in a two-dimensional image (the coordinates of each point are the location of the point in the two-dimensional matrix of pixels.)

    p1, p2, p3 # as the points

    # calculating the distance of p3 to the line constructed out of the p1 and p2
    # distance formula using the cross product approach
    d = numpy.linalg.norm(np.cross(p2-p1, p1-p3))/numpy.linalg.norm(p2-p1)

The question is :

What is the output measurement unit of distances that is calculated in this way?

Is the distance d calculated in 'pixel'?

If the answer is yes,
How can I convert it to the millimeter and other measurement units?


问:
Customize DataTable structure to a List
I intend to transpose the datatable DT_in so that the columns indv1, ... should be the rows and POS as the columns. So for each indv, there would be a named column from the POS rows, which contains the corresponding values (1,2 and 0). I actually could manage this part through tidyr::pivot function. The problem is, I need to do the whole job for each group of IDs in column ID. So the output will be a list so that for each group of IDs in ID as the first element of the list, the transposed table will be a sublist.

```<code>> DT_in
CHR      POS          ID         indv1  indv2  indv3
1   31439_T_A   ENSG00000232325     1    1    2
1   31504_G_A   ENSG00000242474     2    1    1
1   34713_A_C   ENSG00000242474     1    0    1
1   34918_C_T   ENSG00000242474     1    0    1
1   35119_G_A   ENSG00000239715     0    0    1
</code>```

what I tried:

```<code>DT_in %>%
  group_by(ID) %>%
  pivot_longer(
  cols = starts_with("indv")
)

View(DT_in)
  CHR POS       ID              name  value
 <dbl> <chr>     <chr>           <chr> <dbl>
 1     1 31439_T_A ENSG00000232325 indv1     1
 2     1 31439_T_A ENSG00000232325 indv2     1
 3     1 31439_T_A ENSG00000232325 indv3     2
 4     1 31504_G_A ENSG00000242474 indv1     2
 5     1 31504_G_A ENSG00000242474 indv2     1
 6     1 31504_G_A ENSG00000242474 indv3     1
 7     1 34713_A_C ENSG00000242474 indv1     1
 8     1 34713_A_C ENSG00000242474 indv2     0
 9     1 34713_A_C ENSG00000242474 indv3     1
10     1 34918_C_T ENSG00000242474 indv1     1
11     1 34918_C_T ENSG00000242474 indv2     0
12     1 34918_C_T ENSG00000242474 indv3     1
13     1 35119_G_A ENSG00000239715 indv1     0
14     1 35119_G_A ENSG00000239715 indv2     0
15     1 35119_G_A ENSG00000239715 indv3     1

pivot_wider(pivot, names_from = POS, values_from = value)

Error: Internal error in `compact_rep()`: Negative `n` in `compact_rep()`.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In nrow * ncol : NAs produced by integer overflow
</code>```

The error shown up when I wanted to do the job without building the list and also because the number of rows in the column POS are not the same for each IDs in the ID column. That's why I believe it should be done as a list.

UPDATE:
Desired output:

```<code>> DF_OUT1
CHR        ID       name    31439_T_A
 1 ENSG00000232325 indv1     1
 1 ENSG00000232325 indv2     1
 1 ENSG00000232325 indv3     2

> DF_OUT2
CHR        ID       name    31504_G_A     34713_A_C    34918_C_T
 1 ENSG00000242474 indv1     2                 1           1
 1 ENSG00000242474 indv2     1                 0           0
 1 ENSG00000242474 indv3     1                 1           1

> DF_OUT3
CHR        ID       name    35119_G_A
 1 ENSG00000239715 indv1     0
 1 ENSG00000239715 indv2     0
 1 ENSG00000239715 indv3     1
</code>```

As it is seen, I need the outputs to be stored for each IDs separetly either through a loop that gives separate dataframes or in a list of elements named by each unique IDs.

答:
The split function spits a data.frame into a list based on a function or variable. We can take your data.frame, pivot it into long form, split it into a list of dataframes based on ID, then pivot each of them wide again using lapply to get a list of data.frames:

```<code>library(tidyverse)
df %>%
    pivot_longer(starts_with('indv')) %>%
    split(.$ID) %>%
    lapply(., function(x) pivot_wider(x, names_from = 'POS'))

$ENSG00000232325
# A tibble: 3 × 4
    CHR ID              name  `31439_T_A`
  <int> <chr>           <chr>       <int>
1     1 ENSG00000232325 indv1           1
2     1 ENSG00000232325 indv2           1
3     1 ENSG00000232325 indv3           2

$ENSG00000239715
# A tibble: 3 × 4
    CHR ID              name  `35119_G_A`
  <int> <chr>           <chr>       <int>
1     1 ENSG00000239715 indv1           0
2     1 ENSG00000239715 indv2           0
3     1 ENSG00000239715 indv3           1

$ENSG00000242474
# A tibble: 3 × 6
    CHR ID              name  `31504_G_A` `34713_A_C` `34918_C_T`
  <int> <chr>           <chr>       <int>       <int>       <int>
1     1 ENSG00000242474 indv1           2           1           1
2     1 ENSG00000242474 indv2           1           0           0
3     1 ENSG00000242474 indv3           1           1           1

</code>```

For a bit of extra context, here's an explanation for why we need to refer to the ID column as .$ID in split when using the pipe: Why dot in base::split(.$cyl)?

Title: Customize DataTable structure to a List

Body:
I intend to transpose the datatable DT_in so that the columns indv1, ... should be the rows and POS as the columns. So for each indv, there would be a named column from the POS rows, which contains the corresponding values (1,2 and 0). I actually could manage this part through tidyr::pivot function. The problem is, I need to do the whole job for each group of IDs in column ID. So the output will be a list so that for each group of IDs in ID as the first element of the list, the transposed table will be a sublist.

> DT_in
CHR      POS          ID         indv1  indv2  indv3
1   31439_T_A   ENSG00000232325     1    1    2
1   31504_G_A   ENSG00000242474     2    1    1
1   34713_A_C   ENSG00000242474     1    0    1
1   34918_C_T   ENSG00000242474     1    0    1
1   35119_G_A   ENSG00000239715     0    0    1

what I tried:

DT_in %>%
  group_by(ID) %>%
  pivot_longer(
  cols = starts_with("indv")
)

View(DT_in)
  CHR POS       ID              name  value
 <dbl> <chr>     <chr>           <chr> <dbl>
 1     1 31439_T_A ENSG00000232325 indv1     1
 2     1 31439_T_A ENSG00000232325 indv2     1
 3     1 31439_T_A ENSG00000232325 indv3     2
 4     1 31504_G_A ENSG00000242474 indv1     2
 5     1 31504_G_A ENSG00000242474 indv2     1
 6     1 31504_G_A ENSG00000242474 indv3     1
 7     1 34713_A_C ENSG00000242474 indv1     1
 8     1 34713_A_C ENSG00000242474 indv2     0
 9     1 34713_A_C ENSG00000242474 indv3     1
10     1 34918_C_T ENSG00000242474 indv1     1
11     1 34918_C_T ENSG00000242474 indv2     0
12     1 34918_C_T ENSG00000242474 indv3     1
13     1 35119_G_A ENSG00000239715 indv1     0
14     1 35119_G_A ENSG00000239715 indv2     0
15     1 35119_G_A ENSG00000239715 indv3     1

pivot_wider(pivot, names_from = POS, values_from = value)

Error: Internal error in `compact_rep()`: Negative `n` in `compact_rep()`.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In nrow * ncol : NAs produced by integer overflow

The error shown up when I wanted to do the job without building the list and also because the number of rows in the column POS are not the same for each IDs in the ID column. That's why I believe it should be done as a list.

UPDATE:
Desired output:

> DF_OUT1
CHR        ID       name    31439_T_A
 1 ENSG00000232325 indv1     1
 1 ENSG00000232325 indv2     1
 1 ENSG00000232325 indv3     2

> DF_OUT2
CHR        ID       name    31504_G_A     34713_A_C    34918_C_T
 1 ENSG00000242474 indv1     2                 1           1
 1 ENSG00000242474 indv2     1                 0           0
 1 ENSG00000242474 indv3     1                 1           1

> DF_OUT3
CHR        ID       name    35119_G_A
 1 ENSG00000239715 indv1     0
 1 ENSG00000239715 indv2     0
 1 ENSG00000239715 indv3     1

As it is seen, I need the outputs to be stored for each IDs separetly either through a loop that gives separate dataframes or in a list of elements named by each unique IDs.

Body:
The split function spits a data.frame into a list based on a function or variable. We can take your data.frame, pivot it into long form, split it into a list of dataframes based on ID, then pivot each of them wide again using lapply to get a list of data.frames:

library(tidyverse)
df %>%
    pivot_longer(starts_with('indv')) %>%
    split(.$ID) %>%
    lapply(., function(x) pivot_wider(x, names_from = 'POS'))

$ENSG00000232325
# A tibble: 3 × 4
    CHR ID              name  `31439_T_A`
  <int> <chr>           <chr>       <int>
1     1 ENSG00000232325 indv1           1
2     1 ENSG00000232325 indv2           1
3     1 ENSG00000232325 indv3           2

$ENSG00000239715
# A tibble: 3 × 4
    CHR ID              name  `35119_G_A`
  <int> <chr>           <chr>       <int>
1     1 ENSG00000239715 indv1           0
2     1 ENSG00000239715 indv2           0
3     1 ENSG00000239715 indv3           1

$ENSG00000242474
# A tibble: 3 × 6
    CHR ID              name  `31504_G_A` `34713_A_C` `34918_C_T`
  <int> <chr>           <chr>       <int>       <int>       <int>
1     1 ENSG00000242474 indv1           2           1           1
2     1 ENSG00000242474 indv2           1           0           0
3     1 ENSG00000242474 indv3           1           1           1

For a bit of extra context, here's an explanation for why we need to refer to the ID column as .$ID in split when using the pipe: Why dot in base::split(.$cyl)?


问:
How to declare array size at runtime without using dynamic memory allocation
Can I declare an array of size n at runtime without using dynamic memory allocation (malloc etc.) in c?</p>

答:
By definition declaring a memory area of variable size at runtime is dynamic memory allocation, even if you don't use malloc.

As Gerhardh said, you can use VLAs with some limitation. However you should use it with care as it may lead to stack overflow. See for example here.

There is also a library to allocate dynamic memory on the stack (look for alloca). Its benefit is that you don't need any heap on your system to use it but it's not standard (AFAIK) and also to be used with care.

If you want to avoid heap dynamic allocation, it is probably because you are using a system with limited ressources. In this case, the stack is probably limited too and then you should consider defining statically allocated variables to avoid stack overflow.