问:
How to install Go in alpine linux
I am trying to install Go inside an Alpine Docker image. For that I downloaded tar file from here inside my alpine docker image, untar it using following command:

tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz

exported PATH to have go binary as:

export PATH=$PATH:/usr/local/go/bin

However, when I say go version  then it says that sh: go: not found. I am quite new to alpine. Does anyone know, what I am missing here?

Steps to reproduce-

```<code>$ docker run -it alpine sh
$ wget https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz
$ tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
$ go version
</code>```

答:
I found the best way to get golang up running in alpine linux is to install it from source. This is also way followed in the official alpine go docker images.

```<code>FROM alpine:3.12

ARG GOLANG_VERSION=1.14.3

#we need the go version installed from apk to bootstrap the custom version built from source
RUN apk update && apk add go gcc bash musl-dev openssl-dev ca-certificates && update-ca-certificates

RUN wget https://dl.google.com/go/go$GOLANG_VERSION.src.tar.gz && tar -C /usr/local -xzf go$GOLANG_VERSION.src.tar.gz

RUN cd /usr/local/go/src && ./make.bash

ENV PATH=$PATH:/usr/local/go/bin

RUN rm go$GOLANG_VERSION.src.tar.gz

#we delete the apk installed version to avoid conflict
RUN apk del go

RUN go version

</code>```

Title: How to install Go in alpine linux

Body:
I am trying to install Go inside an Alpine Docker image. For that I downloaded tar file from here inside my alpine docker image, untar it using following command:

tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz

exported PATH to have go binary as:

export PATH=$PATH:/usr/local/go/bin

However, when I say go version  then it says that sh: go: not found. I am quite new to alpine. Does anyone know, what I am missing here?

Steps to reproduce-

$ docker run -it alpine sh
$ wget https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz
$ tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
$ go version

Body:
I found the best way to get golang up running in alpine linux is to install it from source. This is also way followed in the official alpine go docker images.

FROM alpine:3.12

ARG GOLANG_VERSION=1.14.3

#we need the go version installed from apk to bootstrap the custom version built from source
RUN apk update && apk add go gcc bash musl-dev openssl-dev ca-certificates && update-ca-certificates

RUN wget https://dl.google.com/go/go$GOLANG_VERSION.src.tar.gz && tar -C /usr/local -xzf go$GOLANG_VERSION.src.tar.gz

RUN cd /usr/local/go/src && ./make.bash

ENV PATH=$PATH:/usr/local/go/bin

RUN rm go$GOLANG_VERSION.src.tar.gz

#we delete the apk installed version to avoid conflict
RUN apk del go

RUN go version


来源: stackexchange

问:
Power Efficient Software Coding
In a typical handheld/portable embedded system device Battery life is a major concern in design of H/W, S/W and the features the device can support. From the Software programming perspective, one is aware of MIPS, Memory(Data and Program) optimized code.
I am aware of the H/W Deep sleep mode, Standby mode that are used to clock the hardware at lower Cycles or turn of the clock entirel to some unused circutis to save power, but i am looking for some ideas from that point of view:

Wherein my code is running and it needs to keep executing, given this how  can I write the code "power" efficiently so as to consume minimum watts?

Are there any special programming constructs, data structures, control structures which i should look at to achieve minimum power consumption for a given functionality.

Are there any s/w high level design considerations which one should keep in mind at time of code structure design, or during low level design to make the code as power efficient(Least power consuming) as possible?

答:
If you have low priority intermittent operations, don't use specific timers to wake up to deal with them, but deal with when processing other events.

Use logic to avoid stupid scenarios where your app might go to sleep for 10 ms and then have to wake up again for the next event.  For the kind of platform mentioned it shouldn't matter if both events are processed at the same time.
Having your own timer & callback mechanism might be appropriate for this kind of decision making.  The trade off is in code complexity and maintenance vs. likely power savings.

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

Title: Power Efficient Software Coding

LastEditorDisplayName: Tim

OwnerDisplayName: itj


问:
How can I move controls into a dynamically added usercontrol into page?
I have a usercontrol that move dynamically on the CreateChildControls method some web controls.
When using this control into a page like :

```<code><myControls:MyUserControl runat="server" ID="myUserControl" />
</code>```

It works flawlessly.

But if I want to add that userControl dynamically into a page like :

```<code><asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:PlaceHolder runat="server" ID="plhControls" />
    </ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="btnAdd" OnClick="btnAdd_Click" />
</code>```

.cs

```<code>protected void btnAdd_Click(object sender, EventArgs e)
{
    MyUserControl myUserControl =(MyUserControl)LoadControl("~/Controls/MyUserControl.ascx");
    myUserControl.ID = "test";
    plhControls.Controls.Add(myUserControl );
}
</code>```

It crashes inside my CreateChildControls with error : The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

The exact line is when I add the webControls to the placeholder inside my UserControl :

```<code>plhContent.Controls.Add(myWebControl);
</code>```

So I don't understand why in this case I cannot move a web control inside the CreateChildControls event when I add my UserControl dynamically.

答:
The controls have to be initialised and brought up to speed with the rest of the controls as far as the "page lifecycle" is concerned. Have a look at the Page.LoadControl method, and see if it's possible to create your control earlier on.

The method we sometimes use involves using a postback parameter from the page. Don't forget that you will need to re-add your control to the form fot every postback, as it will not get created for you

Body:
I have a usercontrol that move dynamically on the CreateChildControls method some web controls.
When using this control into a page like :

<myControls:MyUserControl runat="server" ID="myUserControl" />

It works flawlessly.

But if I want to add that userControl dynamically into a page like :

<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:PlaceHolder runat="server" ID="plhControls" />
    </ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="btnAdd" OnClick="btnAdd_Click" />

.cs

protected void btnAdd_Click(object sender, EventArgs e)
{
    MyUserControl myUserControl =(MyUserControl)LoadControl("~/Controls/MyUserControl.ascx");
    myUserControl.ID = "test";
    plhControls.Controls.Add(myUserControl );
}

It crashes inside my CreateChildControls with error : The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

The exact line is when I add the webControls to the placeholder inside my UserControl :

plhContent.Controls.Add(myWebControl);

So I don't understand why in this case I cannot move a web control inside the CreateChildControls event when I add my UserControl dynamically.


问:
multi package makefile example for go
I'm trying to setup a multi package go project something like

./main.go

./subpackage1/sub1_1.go

./subpackage1/sub1_2.go

./subpackage2/sub2_1.go

./subpackage2/sub2_2.go

where main.go imports both subpackage1 and subpackage2. And subpackage2 imports subpackage1.

Ive been looking around for go makefile examples but I can't find anything that supports this kind of set-up. Any idea?

答:
Check out https://github.com/banthar/Go-SDL which is an actively maintained multi-package go project using Makefiles.

I notice some of these the answers use the obsolete Make.$(GOARCH) include. So hopefully the above link will be stabler than trying to stay on top of Google's changing API in an answer here.

Title: multi package makefile example for go

ContentLicense: CC BY-SA 3.0


问:
c++ function to find the sum of four minimum maximum elements in an array not working
I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.

here is my code:

```<code>void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}
</code>```

this code gives the correct output for maxsum but the minsum is wrong in all the testcases.
please help me find the error in the code
Thanks in advance.

答:
if you considering complexity then as Daniel mentioned you can do that using O(N log N) but you can do that using O(N) where N is the length of the array.

Here is the code segment

```<code>void minMaxSum(vector<int> arr){
 int l1, l2, l3, l4; // large element;
 int s1, s2, s3, s4; // smallest element

 l1 = l2 = l3 = l4 = INT_MIN;
 s1 = s2 = s3 = s4 = INT_MAX;

for(auto i:arr){
    if(i>=l1){
          l4 = l3;
          l3 = l2;
          l2 = l1;
          l1 = i;}
    else if(i>=l2){
          l4 = l3;
          l3 = l2;
          l2 = i;}
    else if(i>=l3){
          l4 = l3;
          l3 = i;}
    else if(i>=l4)
          l4 = i;
}
for(auto i:arr){
    if(i<=s1){
      s4 = s3;
      s3 = s2;
      s2 = s1;
          s1 = i;}
    else if(i<=s2){
          s4 = s3;
          s3 = s2;
          s2 = i;}
    else if(i<=s3){
          s4 = s3;
          s3 = i;}
    else if(i<=s4)
          s4 = i;
}
int minsum = s1 + s2 + s3 + s4;
int maxsum = l1 + l2 + l3 + l4;
cout << maxsum << " " << minsum << endl;
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.

here is my code:

void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}

this code gives the correct output for maxsum but the minsum is wrong in all the testcases.
please help me find the error in the code
Thanks in advance.

Body:
if you considering complexity then as Daniel mentioned you can do that using O(N log N) but you can do that using O(N) where N is the length of the array.

Here is the code segment

void minMaxSum(vector<int> arr){
 int l1, l2, l3, l4; // large element;
 int s1, s2, s3, s4; // smallest element

 l1 = l2 = l3 = l4 = INT_MIN;
 s1 = s2 = s3 = s4 = INT_MAX;

for(auto i:arr){
    if(i>=l1){
          l4 = l3;
          l3 = l2;
          l2 = l1;
          l1 = i;}
    else if(i>=l2){
          l4 = l3;
          l3 = l2;
          l2 = i;}
    else if(i>=l3){
          l4 = l3;
          l3 = i;}
    else if(i>=l4)
          l4 = i;
}
for(auto i:arr){
    if(i<=s1){
      s4 = s3;
      s3 = s2;
      s2 = s1;
          s1 = i;}
    else if(i<=s2){
          s4 = s3;
          s3 = s2;
          s2 = i;}
    else if(i<=s3){
          s4 = s3;
          s3 = i;}
    else if(i<=s4)
          s4 = i;
}
int minsum = s1 + s2 + s3 + s4;
int maxsum = l1 + l2 + l3 + l4;
cout << maxsum << " " << minsum << endl;
}


问:
Angular Material & Flex: How set max width for whole app?
I want to set the width of the app content so that when screen sizes changes, the content stays in the middle and there are whitespace on left and right side. I am using Angular Material & Angular Flex. I have observed this is a common design in various websites including stack overflow. Pardon me if this is a common question and I'm unable to find it.

Here is an example:
I want the app content to be within the lines.

答:
Best way to do it is using flex. It will define how much a flexbox item should grow or not.
A example of the usage is as the following:

```<code>fxFlex="grow shrink initial"
fxFlex="0 1 80" <- Will not grow | will shrink 1:1 | initial value of 80%
fxFlex="0 1 1250px" <- Will not grow | will shrink to 1:1 | initial value of 1250px
</code>```

For more please read this documentation

Body:
Best way to do it is using flex. It will define how much a flexbox item should grow or not.
A example of the usage is as the following:

fxFlex="grow shrink initial"
fxFlex="0 1 80" <- Will not grow | will shrink 1:1 | initial value of 80%
fxFlex="0 1 1250px" <- Will not grow | will shrink to 1:1 | initial value of 1250px

For more please read this documentation


问:
Adding contextMenu to a Button within a List prevents default Button functionality
I'm trying to create a list with actions that occur both on tap/click and support a context menu.

Buttons do support contextMenu when outside the list (#1), but when inside the list (#2), taps are no longer recognized, though the contextMenu still works. Is this intentional?

```<code>struct ContextMenu: View {
    @State var on = false

    var button: some View {
        Button(action: { self.on.toggle() }) {
            Text("Toggle")
        }
    }

    var body: some View {
        VStack {
            Text(on ? "on" : "off")

            // #1: works for both tap and context
            button.contextMenu {
                button
            }

            // #2: tap on button no longer works
            List {
                button.contextMenu {
                    button
                }
            }
        }
    }
}
</code>```

I have also tried adding .buttonStyle(BorderlessButtonStyle() to the Button. This enables tapping, but only of the text, not the entire row.

答:
Actually this is a question to Apple... meanwhile here is a possible solution. Tested with Xcode 11.4

```<code>List {
    button
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
        .contentShape(Rectangle())
        .contextMenu {
            button
        }.onTapGesture {
            self.on.toggle()
        }
}
</code>```

if you want highlight on row tap then it needs to apply custom ButtonStyle. For example you can consider solution in Custom Button in SwiftUI List

Body:
I'm trying to create a list with actions that occur both on tap/click and support a context menu.

Buttons do support contextMenu when outside the list (#1), but when inside the list (#2), taps are no longer recognized, though the contextMenu still works. Is this intentional?

struct ContextMenu: View {
    @State var on = false

    var button: some View {
        Button(action: { self.on.toggle() }) {
            Text("Toggle")
        }
    }

    var body: some View {
        VStack {
            Text(on ? "on" : "off")

            // #1: works for both tap and context
            button.contextMenu {
                button
            }

            // #2: tap on button no longer works
            List {
                button.contextMenu {
                    button
                }
            }
        }
    }
}

I have also tried adding .buttonStyle(BorderlessButtonStyle() to the Button. This enables tapping, but only of the text, not the entire row.

Body:
Actually this is a question to Apple... meanwhile here is a possible solution. Tested with Xcode 11.4

List {
    button
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
        .contentShape(Rectangle())
        .contextMenu {
            button
        }.onTapGesture {
            self.on.toggle()
        }
}

if you want highlight on row tap then it needs to apply custom ButtonStyle. For example you can consider solution in Custom Button in SwiftUI List


问:
Is tzinfo-data needed if the application will run only on Linux docker containers
Is tzinfo-data needed if the application will run only on Linux docker containers. Should the following need to be added to the Gemfile

Windows does not include zoneinfo files, so bundle the tzinfo-data gem

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

答:
When you create a new rails app, you get this message:

Basically, you can just remove gem tzifono-data from your Gemfile if you are running anything except windows, and run bundle update.

The tzinfo-data gem is not needed on Linux.

Here's a detailed answer https://github.com/tzinfo/tzinfo-data/issues/13#issuecomment-287174435


问:
Trouble inserting React object into sequelize/MySQL database
My front end and backend are connected but it is not inputting the values into my MySQL database from a React form.  When I console log the response I get from my React app it logs

```<code>{name: "han solo", email: "han@virginia.edu", message: "fsbfbsf"}
</code>```

but my database logs the results as

```<code>{id: 4, updatedAt: "2020-05-28T03:11:31.983Z", createdAt: "2020-05-28T03:11:31.983Z"}
</code>```

My database model is:

```<code>module.exports = function(sequelize, DataTypes) {
  var Messages = sequelize.define("Messages", {
    name: DataTypes.STRING,
    email: DataTypes.STRING,
    message: DataTypes.STRING
  });
  return Messages;
};
</code>```

My post route is:

```<code> // POST route for saving a new Message
  app.post("/api/messages", function(req, res) {
    console.log(req.body);
    db.Messages.create({
      name: req.body.name,
      email: req.body.email,
      message: req.body.message
    }).then(function(dbMessages) {
      // We have access to the new Message as an argument inside of the callback function
      res.json(dbMessages);
    });
  });
</code>```

My handleFormSubmit function on my front end is:

```<code>handleFormSubmit = e => {
    e.preventDefault();

    if (
      this.state.name === "" ||
      this.state.email === "" ||
      this.state.message === ""
    ) {
      this.setState({
        formError: true
      });
      return false;
    } else {
      this.setState({
        formError: false
      });
      const obj = {
        name: this.state.name,
        email: this.state.email,
        message: this.state.message
      };
      console.log(obj);
      axios
        .post(url, {obj})
        .then(res => console.log(res.data))
        .catch(error => this.setState({ error: error.message }));

      this.setState({
        name: "",
        email: "",
        message: ""
      });
    }
  };
</code>```

It seems like the default values are inserting but not the input values from the React Form, but the form values console log as an object

答:
Figured it out. I had to bind the values to state, and I was declaring obj as {obj} instead of obj. Corrections are below</p>

```<code> constructor(props) {
    super(props);
    this.getName = this.getName.bind(this);
    this.getEmail = this.getEmail.bind(this);
    this.getMessage = this.getMessage.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);

 axios
    .post(url, obj)
    .then(res => console.log(res.data))
    .catch(error => this.setState({ error: error.message }));
</code>```

Body:
My front end and backend are connected but it is not inputting the values into my MySQL database from a React form.  When I console log the response I get from my React app it logs

{name: "han solo", email: "han@virginia.edu", message: "fsbfbsf"}

but my database logs the results as

{id: 4, updatedAt: "2020-05-28T03:11:31.983Z", createdAt: "2020-05-28T03:11:31.983Z"}

My database model is:

module.exports = function(sequelize, DataTypes) {
  var Messages = sequelize.define("Messages", {
    name: DataTypes.STRING,
    email: DataTypes.STRING,
    message: DataTypes.STRING
  });
  return Messages;
};

My post route is:

 // POST route for saving a new Message
  app.post("/api/messages", function(req, res) {
    console.log(req.body);
    db.Messages.create({
      name: req.body.name,
      email: req.body.email,
      message: req.body.message
    }).then(function(dbMessages) {
      // We have access to the new Message as an argument inside of the callback function
      res.json(dbMessages);
    });
  });

My handleFormSubmit function on my front end is:

handleFormSubmit = e => {
    e.preventDefault();

    if (
      this.state.name === "" ||
      this.state.email === "" ||
      this.state.message === ""
    ) {
      this.setState({
        formError: true
      });
      return false;
    } else {
      this.setState({
        formError: false
      });
      const obj = {
        name: this.state.name,
        email: this.state.email,
        message: this.state.message
      };
      console.log(obj);
      axios
        .post(url, {obj})
        .then(res => console.log(res.data))
        .catch(error => this.setState({ error: error.message }));

      this.setState({
        name: "",
        email: "",
        message: ""
      });
    }
  };

It seems like the default values are inserting but not the input values from the React Form, but the form values console log as an object

Body:
Figured it out. I had to bind the values to state, and I was declaring obj as {obj} instead of obj. Corrections are below

 constructor(props) {
    super(props);
    this.getName = this.getName.bind(this);
    this.getEmail = this.getEmail.bind(this);
    this.getMessage = this.getMessage.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);

 axios
    .post(url, obj)
    .then(res => console.log(res.data))
    .catch(error => this.setState({ error: error.message }));


问:
How can I modify my <textarea> html value based on user input
I have a html textarea element in my page where user gives comma separate values. for example below.

A-48402,AA,SBAFL,AA+,USD,,

From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below

```<code>var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');
</code>```

Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.

```<code>row_values.push('Y');
</code>```

It is reflecting in debugger.

But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit.  How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?

```<code>String Data = request.getParameter('mbs_inst_data');
</code>```

This data is populated with the same blank values.

答:
You can use it like this.

```<code><p id="demo">Visit Microsoft! ,,</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var str = document.getElementById("demo").innerHTML;
  var res = str.replace(/,,$/, ',Y');
  document.getElementById("demo").innerHTML = res;
}
</script>
</code>```

Output

```<code>Visit Microsoft! ,Y
</code>```

I guess this would help you.

Body:
I have a html textarea element in my page where user gives comma separate values. for example below.

A-48402,AA,SBAFL,AA+,USD,,

From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below

var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');

Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.

row_values.push('Y');

It is reflecting in debugger.

But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit.  How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?

String Data = request.getParameter('mbs_inst_data');

This data is populated with the same blank values.

Body:
You can use it like this.

<p id="demo">Visit Microsoft! ,,</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var str = document.getElementById("demo").innerHTML;
  var res = str.replace(/,,$/, ',Y');
  document.getElementById("demo").innerHTML = res;
}
</script>

Output

Visit Microsoft! ,Y

I guess this would help you.


问:
Crystal Report direct saving as PDF, instead of viewing
I want to make a report from ASP.Net, in Crystal Report. I want, when user click on print, it should simply show a browser dialog of Save,Open,Save as, and PDF should be saved, or Crystal Report print preview should appear, I don't want to display report first in Viewer then click on button to get print or PDF, I want simply from clicking on asp button, I have all the idea of parameters and know how to make report, my question is just to not to show viewer and take report from asp button in a form of PDF or print preview dialog to print. I have used the Export method of .Net for Crystal Report, but it does not work.</p>

答:
You can generate a PDF by Using a Crystal Report and piece of code....

First: Generate a Crystal Report as per your requirements.

Second: Use the below code to generate the PDF:

Place the following name spaces at the top of the code page

```<code>Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
</code>```

Variable Declaration

```<code>Dim CrReport As New CrystalReport1() // Report Name
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()
Dim CrFormatTypeOptions as New PdfRtfWordFormatOptions()
</code>```

Set the destination path and file name

```<code>CrDiskFileDestinationOptions.DiskFileName = "c:\RichText.pdf"
</code>```

Specify a page range (optional)

```<code>crFormatTypeOptions.FirstPageNumber = 1 // Start Page in the Report
crFormatTypeOptions.LastPageNumber = 3 // End Page in the Report
crFormatTypeOptions.UsePageRange = True
</code>```

Set export options

```<code>CrExportOptions = crReport.ExportOptions

With CrExportOptions

// Set the destination to a disk file
.ExportDestinationType = ExportDestinationType.DiskFile

// Set the format to PDF
.ExportFormatType = ExportFormatType.PortableDocFormat

// Set the destination options to DiskFileDestinationOptions object
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = crFormatTypeOptions

End With
</code>```

Trap any errors that occur on export

```<code>Try
    // Export the report
    CrReport.Export()
Catch err As Exception
    MessageBox.Show(err.ToString())
End Try
</code>```

Thats it.... Now you are ready to create a PDF of the Report.

Body:
You can generate a PDF by Using a Crystal Report and piece of code....

First: Generate a Crystal Report as per your requirements.

Second: Use the below code to generate the PDF:

Place the following name spaces at the top of the code page

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Variable Declaration

Dim CrReport As New CrystalReport1() // Report Name
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()
Dim CrFormatTypeOptions as New PdfRtfWordFormatOptions()

Set the destination path and file name

CrDiskFileDestinationOptions.DiskFileName = "c:\RichText.pdf"

Specify a page range (optional)

crFormatTypeOptions.FirstPageNumber = 1 // Start Page in the Report
crFormatTypeOptions.LastPageNumber = 3 // End Page in the Report
crFormatTypeOptions.UsePageRange = True

Set export options

CrExportOptions = crReport.ExportOptions

With CrExportOptions

// Set the destination to a disk file
.ExportDestinationType = ExportDestinationType.DiskFile

// Set the format to PDF
.ExportFormatType = ExportFormatType.PortableDocFormat

// Set the destination options to DiskFileDestinationOptions object
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = crFormatTypeOptions

End With

Trap any errors that occur on export

Try
    // Export the report
    CrReport.Export()
Catch err As Exception
    MessageBox.Show(err.ToString())
End Try

Thats it.... Now you are ready to create a PDF of the Report.


问:
how to check a radio button by clicking on a table row?
I am working on a data table which will be filled with Json data and I want to make the entire row clickable and when I click on the line, the radio button associated with it must be checked and return the value of the radio button

var elements= document.getElementsByTagName('tr');
for(var i=0; i<elements.length;i++)
{

  (elements)[i].addEventListener("click", function(){

   const rbs = document.querySelectorAll('input[name="choice"]');
            let selectedValue;
            for (const rb of rbs) {
                if (rb.checked) {
                    selectedValue = rb.value;
                    break;
                }
            }
            alert(selectedValue);

});
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr:hover{
background-color:gray;
cursor:pointer;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Firstname
        Lastname
        Email

        <input type="radio" value="Jhon doe" name="name"/>
        John
        Doe
        john@example.com

      <input type="radio" value="mary Moe" name="name" />
        Mary
        Moe
        mary@example.com

      <input type="radio" value="July dooley" name="name" />
        July
        Dooley
        july@example.com

```

答:
You can simplify this considerably using jQuery which you seem to already be including

$('tr').click(function(e) {
    $(this).find(':radio').prop('checked', true);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr:hover {
  background-color: gray;
  cursor: pointer;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Firstname
      Lastname
      Email

      <input type="radio" value="Jhon doe" name="name" />
      John
      Doe
      john@example.com

      <input type="radio" value="mary Moe" name="name" />
      Mary
      Moe
      mary@example.com

      <input type="radio" value="July dooley" name="name" />
      July
      Dooley
      july@example.com

```

Body:
I am working on a data table which will be filled with Json data and I want to make the entire row clickable and when I click on the line, the radio button associated with it must be checked and return the value of the radio button

var elements= document.getElementsByTagName('tr');
for(var i=0; i<elements.length;i++)
{

  (elements)[i].addEventListener("click", function(){

   const rbs = document.querySelectorAll('input[name="choice"]');
            let selectedValue;
            for (const rb of rbs) {
                if (rb.checked) {
                    selectedValue = rb.value;
                    break;
                }
            }
            alert(selectedValue);

});
}

tr:hover{
background-color:gray;
cursor:pointer;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Firstname
        Lastname
        Email

        <input type="radio" value="Jhon doe" name="name"/>
        John
        Doe
        john@example.com

      <input type="radio" value="mary Moe" name="name" />
        Mary
        Moe
        mary@example.com

      <input type="radio" value="July dooley" name="name" />
        July
        Dooley
        july@example.com

Body:
You can simplify this considerably using jQuery which you seem to already be including

$('tr').click(function(e) {
    $(this).find(':radio').prop('checked', true);
})

tr:hover {
  background-color: gray;
  cursor: pointer;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
  <thead>
    <tr>
      <th></th>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="radio" value="Jhon doe" name="name" /></td>
      <td>John</td>
      <td>Doe</td>
      <td>john@example.com</td>
    </tr>
    <tr>
      <td><input type="radio" value="mary Moe" name="name" /></td>
      <td>Mary</td>
      <td>Moe</td>
      <td>mary@example.com</td>
    </tr>
    <tr>
      <td><input type="radio" value="July dooley" name="name" /></td>
      <td>July</td>
      <td>Dooley</td>
      <td>july@example.com</td>
    </tr>
  </tbody>
</table>


问:
Why is the toolbar not showing when I tap on the textfield?
I would like to implement a done toolbar above the numpad keyboard when the textfield is tapped however the toolbar is not showing up for some reason.

The following code sample has been used:

```<code>extension UITextField{

    @IBInspectable var doneAccessory: Bool{
        get{
            return self.doneAccessory
        }
        set (hasDone) {
            if hasDone{
                addDoneButtonOnKeyboard()
            }
        }
    }

    func addDoneButtonOnKeyboard()
    {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        self.inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction()
    {
        self.resignFirstResponder()
    }
}
</code>```

答:
Make sure in your storyboard, TextField's property inspector doneAccessory property is set to ON

and O/P looks like

Body:
I would like to implement a done toolbar above the numpad keyboard when the textfield is tapped however the toolbar is not showing up for some reason.

The following code sample has been used:

extension UITextField{

    @IBInspectable var doneAccessory: Bool{
        get{
            return self.doneAccessory
        }
        set (hasDone) {
            if hasDone{
                addDoneButtonOnKeyboard()
            }
        }
    }

    func addDoneButtonOnKeyboard()
    {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        self.inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction()
    {
        self.resignFirstResponder()
    }
}


问:
Structured Streaming with multiple Sink's for a single Source
We are creating a Spark Structured Streaming application where there is a Single Source and Multiple Sink's (Kafka & HDFS). We are on a Spark 2.3.1 cluster hence using foreachBatch on a DataStreamWriter is out of our reach. Hence I opted for the multiple Stream Writer approach as being advocated here and multiple other places. Unfortunately only one of that Stream is working for all batches and the other remains dormant. What am I missing here to solve my problem?

  val spark = SparkSession
      .builder
      .appName("Spark-Structured-Streaming")
      .enableHiveSupport()
      .getOrCreate()

  val lines = spark.readStream
    .format("socket")
    .option("host", "localhost")
    .option("port", 9999)
    .load()

  val words: Dataset[String] = lines.as[String]
    .flatMap(_.split(" "))
    .map(_.concat(Random.nextInt(10).toString))

  /** THIS DOESN'T STREAM TO HDFS (This work's only when the below one is commented) **/
  words.writeStream
    .format("parquet")
    .option("path", "path/to/destination/dir")
    .option("checkpointLocation", "some_location_1")
    .start()

  /** THIS WORK'S **/
  words.writeStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    .option("topic", "updates")
    .option("checkpointLocation", "some_location_2")
    .start()

  spark.streams.awaitAnyTermination()
```

<p>I only see data published to Kafka but I don't see data written to HDFS. Only when I comment out Kafka publishing stream the dormant one come's to life.</p>

<p>UPDATE:
a similar easily reproducible script with simple Sink's</p>

<pre class="lang-scala prettyprint-override"><code>def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder.appName("Spark-Structured-Streaming").master("local[4]").getOrCreate()

    val lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()

    import spark.implicits._

    val words: Dataset[String] = lines.as[String].flatMap(_.split(" ")).map(_.concat(Random.nextInt(10).toString))

    words.writeStream.queryName("query1").format("console").start()

    words.writeStream.queryName("query2").foreach(new ForeachWriter[String] {
        override def open(partitionId: Long, version: Long): Boolean = true

        override def process(value: String): Unit = {
          println(value)
        }

        override def close(errorOrNull: Throwable): Unit = {}
      })
      .start()

    spark.streams.awaitAnyTermination()
  }
</code>```

LOGS: for an input of A B C

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
20/05/30 12:17:37 INFO SparkContext: Running Spark version 2.3.1
20/05/30 12:17:38 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
20/05/30 12:17:38 INFO SparkContext: Submitted application: Spark-Structured-Streaming
20/05/30 12:17:38 INFO SecurityManager: Changing view acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing view acls groups to:
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls groups to:
20/05/30 12:17:38 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(z001v7w); groups with view permissions: Set(); users  with modify permissions: Set(z001v7w); groups with modify permissions: Set()
20/05/30 12:17:38 INFO Utils: Successfully started service 'sparkDriver' on port 49262.
20/05/30 12:17:39 INFO SparkEnv: Registering MapOutputTracker
20/05/30 12:17:39 INFO SparkEnv: Registering BlockManagerMaster
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
20/05/30 12:17:39 INFO DiskBlockManager: Created local directory at /private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/blockmgr-80dcbdff-eb1c-49e5-a33b-47a897735d31
20/05/30 12:17:39 INFO MemoryStore: MemoryStore started with capacity 2004.6 MB
20/05/30 12:17:39 INFO SparkEnv: Registering OutputCommitCoordinator
20/05/30 12:17:39 INFO Utils: Successfully started service 'SparkUI' on port 4040.
20/05/30 12:17:39 INFO SparkUI: Bound SparkUI to 127.0.0.1, and started at http://localhost:4040
20/05/30 12:17:39 INFO Executor: Starting executor ID driver on host localhost
20/05/30 12:17:39 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 49263.
20/05/30 12:17:39 INFO NettyBlockTransferService: Server created on localhost:49263
20/05/30 12:17:39 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
20/05/30 12:17:39 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Registering block manager localhost:49263 with 2004.6 MB RAM, BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:40 INFO SharedState: Setting hive.metastore.warehouse.dir ('null') to the value of spark.sql.warehouse.dir ('file:/Users/****/spark-warehouse/').
20/05/30 12:17:40 INFO SharedState: Warehouse path is 'file:/****/spark-warehouse/'.
20/05/30 12:17:40 INFO StateStoreCoordinatorRef: Registered StateStoreCoordinator endpoint
20/05/30 12:17:40 WARN TextSocketSourceProvider: The socket source should not be used for production applications! It does not support recovery.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query1 [id = a5714e40-553f-4d21-9115-9c0d9ffe950b, runId = 8d206486-36d8-4319-ad3d-fa5cb00a79ca]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-5f818bb9-b347-432f-8c43-07fccec0e9e8 to store the query checkpoint.
20/05/30 12:17:43 WARN ClosureCleaner: Expected a closure; got com.tgt.sign.POCTestMain$$anon$1
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "a5714e40-553f-4d21-9115-9c0d9ffe950b",
  "runId" : "8d206486-36d8-4319-ad3d-fa5cb00a79ca",
  "name" : "query1",
  "timestamp" : "2020-05-30T17:17:43.915Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 10
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "org.apache.spark.sql.execution.streaming.ConsoleSinkProvider@5e761dda"
  }
}
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query2 [id = 776c6082-920a-4406-913f-c1b2eda5f12d, runId = 7d066ebb-fe7b-454c-98c5-2ed05a8c0bda]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-7a3485d8-9973-43a7-8a35-4a5dd0745719 to store the query checkpoint.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "776c6082-920a-4406-913f-c1b2eda5f12d",
  "runId" : "7d066ebb-fe7b-454c-98c5-2ed05a8c0bda",
  "name" : "query2",
  "timestamp" : "2020-05-30T17:17:43.991Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 1
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "ForeachSink"
  }
}
20/05/30 12:17:49 INFO MicroBatchExecution: Committed offsets for batch 0. Metadata OffsetSeqMetadata(0,1590859069597,Map(spark.sql.shuffle.partitions -> 200, spark.sql.streaming.stateStore.providerClass -> org.apache.spark.sql.execution.streaming.state.HDFSBackedStateStoreProvider))
20/05/30 12:17:50 INFO CodeGenerator: Code generated in 474.062005 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 58.908865 ms
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Start processing data source writer: org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266. The input RDD has 4 partitions.
20/05/30 12:17:51 INFO SparkContext: Starting job: start at POCTestMain.scala:147
20/05/30 12:17:51 INFO DAGScheduler: Got job 0 (start at POCTestMain.scala:147) with 4 output partitions
20/05/30 12:17:51 INFO DAGScheduler: Final stage: ResultStage 0 (start at POCTestMain.scala:147)
20/05/30 12:17:51 INFO DAGScheduler: Parents of final stage: List()
20/05/30 12:17:51 INFO DAGScheduler: Missing parents: List()
20/05/30 12:17:51 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147), which has no missing parents
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 12.0 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 5.3 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:49263 (size: 5.3 KB, free: 2004.6 MB)
20/05/30 12:17:51 INFO SparkContext: Created broadcast 0 from broadcast at DAGScheduler.scala:1039
20/05/30 12:17:51 INFO DAGScheduler: Submitting 4 missing tasks from ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147) (first 15 tasks are for partitions Vector(0, 1, 2, 3))
20/05/30 12:17:51 INFO TaskSchedulerImpl: Adding task set 0.0 with 4 tasks
20/05/30 12:17:51 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, executor driver, partition 0, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 1.0 in stage 0.0 (TID 1, localhost, executor driver, partition 1, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 2.0 in stage 0.0 (TID 2, localhost, executor driver, partition 2, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 3.0 in stage 0.0 (TID 3, localhost, executor driver, partition 3, PROCESS_LOCAL, 7995 bytes)
20/05/30 12:17:51 INFO Executor: Running task 3.0 in stage 0.0 (TID 3)
20/05/30 12:17:51 INFO Executor: Running task 0.0 in stage 0.0 (TID 0)
20/05/30 12:17:51 INFO Executor: Running task 1.0 in stage 0.0 (TID 1)
20/05/30 12:17:51 INFO Executor: Running task 2.0 in stage 0.0 (TID 2)
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 25.371124 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 12.870672 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 committed.
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 14.157876 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 committed.
20/05/30 12:17:51 INFO Executor: Finished task 2.0 in stage 0.0 (TID 2). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 1.0 in stage 0.0 (TID 1). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 3.0 in stage 0.0 (TID 3). 2297 bytes result sent to driver
20/05/30 12:17:51 INFO TaskSetManager: Finished task 2.0 in stage 0.0 (TID 2) in 227 ms on localhost (executor driver) (1/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 256 ms on localhost (executor driver) (2/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 233 ms on localhost (executor driver) (3/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 3.0 in stage 0.0 (TID 3) in 232 ms on localhost (executor driver) (4/4)
20/05/30 12:17:51 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/05/30 12:17:51 INFO DAGScheduler: ResultStage 0 (start at POCTestMain.scala:147) finished in 0.557 s
20/05/30 12:17:51 INFO DAGScheduler: Job 0 finished: start at POCTestMain.scala:147, took 0.616436 s
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Data source writer org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266 is committing.
-------------------------------------------
Batch: 0
-------------------------------------------
+-----+
|value|
+-----+
|   A8|
|   B9|
|   C4|
+-----+
</code>```

答:
Now I understood your problem. You are using socket as input source & starting two threads for consuming & writing into sinks.

In socket (netcat) once data is consumed from the socket it will not be available, for example

query1 started first it will read data from socket & write to sink.

query2 there is no data to read from socket so it will simply sit idle.

In spark document mentioned - The socket source should not be used for production applications it does not support recovery

Instead of socket try to stream files & check if it is working as expected or not.

Body:
We are creating a Spark Structured Streaming application where there is a Single Source and Multiple Sink's (Kafka & HDFS). We are on a Spark 2.3.1 cluster hence using foreachBatch on a DataStreamWriter is out of our reach. Hence I opted for the multiple Stream Writer approach as being advocated here and multiple other places. Unfortunately only one of that Stream is working for all batches and the other remains dormant. What am I missing here to solve my problem?

  val spark = SparkSession
      .builder
      .appName("Spark-Structured-Streaming")
      .enableHiveSupport()
      .getOrCreate()

  val lines = spark.readStream
    .format("socket")
    .option("host", "localhost")
    .option("port", 9999)
    .load()

  val words: Dataset[String] = lines.as[String]
    .flatMap(_.split(" "))
    .map(_.concat(Random.nextInt(10).toString))

  /** THIS DOESN'T STREAM TO HDFS (This work's only when the below one is commented) **/
  words.writeStream
    .format("parquet")
    .option("path", "path/to/destination/dir")
    .option("checkpointLocation", "some_location_1")
    .start()

  /** THIS WORK'S **/
  words.writeStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    .option("topic", "updates")
    .option("checkpointLocation", "some_location_2")
    .start()

  spark.streams.awaitAnyTermination()

I only see data published to Kafka but I don't see data written to HDFS. Only when I comment out Kafka publishing stream the dormant one come's to life.

UPDATE:
a similar easily reproducible script with simple Sink's

def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder.appName("Spark-Structured-Streaming").master("local[4]").getOrCreate()

    val lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()

    import spark.implicits._

    val words: Dataset[String] = lines.as[String].flatMap(_.split(" ")).map(_.concat(Random.nextInt(10).toString))

    words.writeStream.queryName("query1").format("console").start()

    words.writeStream.queryName("query2").foreach(new ForeachWriter[String] {
        override def open(partitionId: Long, version: Long): Boolean = true

        override def process(value: String): Unit = {
          println(value)
        }

        override def close(errorOrNull: Throwable): Unit = {}
      })
      .start()

    spark.streams.awaitAnyTermination()
  }

LOGS: for an input of A B C

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
20/05/30 12:17:37 INFO SparkContext: Running Spark version 2.3.1
20/05/30 12:17:38 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
20/05/30 12:17:38 INFO SparkContext: Submitted application: Spark-Structured-Streaming
20/05/30 12:17:38 INFO SecurityManager: Changing view acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing view acls groups to:
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls groups to:
20/05/30 12:17:38 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(z001v7w); groups with view permissions: Set(); users  with modify permissions: Set(z001v7w); groups with modify permissions: Set()
20/05/30 12:17:38 INFO Utils: Successfully started service 'sparkDriver' on port 49262.
20/05/30 12:17:39 INFO SparkEnv: Registering MapOutputTracker
20/05/30 12:17:39 INFO SparkEnv: Registering BlockManagerMaster
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
20/05/30 12:17:39 INFO DiskBlockManager: Created local directory at /private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/blockmgr-80dcbdff-eb1c-49e5-a33b-47a897735d31
20/05/30 12:17:39 INFO MemoryStore: MemoryStore started with capacity 2004.6 MB
20/05/30 12:17:39 INFO SparkEnv: Registering OutputCommitCoordinator
20/05/30 12:17:39 INFO Utils: Successfully started service 'SparkUI' on port 4040.
20/05/30 12:17:39 INFO SparkUI: Bound SparkUI to 127.0.0.1, and started at http://localhost:4040
20/05/30 12:17:39 INFO Executor: Starting executor ID driver on host localhost
20/05/30 12:17:39 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 49263.
20/05/30 12:17:39 INFO NettyBlockTransferService: Server created on localhost:49263
20/05/30 12:17:39 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
20/05/30 12:17:39 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Registering block manager localhost:49263 with 2004.6 MB RAM, BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:40 INFO SharedState: Setting hive.metastore.warehouse.dir ('null') to the value of spark.sql.warehouse.dir ('file:/Users/****/spark-warehouse/').
20/05/30 12:17:40 INFO SharedState: Warehouse path is 'file:/****/spark-warehouse/'.
20/05/30 12:17:40 INFO StateStoreCoordinatorRef: Registered StateStoreCoordinator endpoint
20/05/30 12:17:40 WARN TextSocketSourceProvider: The socket source should not be used for production applications! It does not support recovery.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query1 [id = a5714e40-553f-4d21-9115-9c0d9ffe950b, runId = 8d206486-36d8-4319-ad3d-fa5cb00a79ca]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-5f818bb9-b347-432f-8c43-07fccec0e9e8 to store the query checkpoint.
20/05/30 12:17:43 WARN ClosureCleaner: Expected a closure; got com.tgt.sign.POCTestMain$$anon$1
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "a5714e40-553f-4d21-9115-9c0d9ffe950b",
  "runId" : "8d206486-36d8-4319-ad3d-fa5cb00a79ca",
  "name" : "query1",
  "timestamp" : "2020-05-30T17:17:43.915Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 10
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "org.apache.spark.sql.execution.streaming.ConsoleSinkProvider@5e761dda"
  }
}
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query2 [id = 776c6082-920a-4406-913f-c1b2eda5f12d, runId = 7d066ebb-fe7b-454c-98c5-2ed05a8c0bda]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-7a3485d8-9973-43a7-8a35-4a5dd0745719 to store the query checkpoint.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "776c6082-920a-4406-913f-c1b2eda5f12d",
  "runId" : "7d066ebb-fe7b-454c-98c5-2ed05a8c0bda",
  "name" : "query2",
  "timestamp" : "2020-05-30T17:17:43.991Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 1
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "ForeachSink"
  }
}
20/05/30 12:17:49 INFO MicroBatchExecution: Committed offsets for batch 0. Metadata OffsetSeqMetadata(0,1590859069597,Map(spark.sql.shuffle.partitions -> 200, spark.sql.streaming.stateStore.providerClass -> org.apache.spark.sql.execution.streaming.state.HDFSBackedStateStoreProvider))
20/05/30 12:17:50 INFO CodeGenerator: Code generated in 474.062005 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 58.908865 ms
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Start processing data source writer: org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266. The input RDD has 4 partitions.
20/05/30 12:17:51 INFO SparkContext: Starting job: start at POCTestMain.scala:147
20/05/30 12:17:51 INFO DAGScheduler: Got job 0 (start at POCTestMain.scala:147) with 4 output partitions
20/05/30 12:17:51 INFO DAGScheduler: Final stage: ResultStage 0 (start at POCTestMain.scala:147)
20/05/30 12:17:51 INFO DAGScheduler: Parents of final stage: List()
20/05/30 12:17:51 INFO DAGScheduler: Missing parents: List()
20/05/30 12:17:51 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147), which has no missing parents
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 12.0 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 5.3 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:49263 (size: 5.3 KB, free: 2004.6 MB)
20/05/30 12:17:51 INFO SparkContext: Created broadcast 0 from broadcast at DAGScheduler.scala:1039
20/05/30 12:17:51 INFO DAGScheduler: Submitting 4 missing tasks from ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147) (first 15 tasks are for partitions Vector(0, 1, 2, 3))
20/05/30 12:17:51 INFO TaskSchedulerImpl: Adding task set 0.0 with 4 tasks
20/05/30 12:17:51 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, executor driver, partition 0, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 1.0 in stage 0.0 (TID 1, localhost, executor driver, partition 1, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 2.0 in stage 0.0 (TID 2, localhost, executor driver, partition 2, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 3.0 in stage 0.0 (TID 3, localhost, executor driver, partition 3, PROCESS_LOCAL, 7995 bytes)
20/05/30 12:17:51 INFO Executor: Running task 3.0 in stage 0.0 (TID 3)
20/05/30 12:17:51 INFO Executor: Running task 0.0 in stage 0.0 (TID 0)
20/05/30 12:17:51 INFO Executor: Running task 1.0 in stage 0.0 (TID 1)
20/05/30 12:17:51 INFO Executor: Running task 2.0 in stage 0.0 (TID 2)
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 25.371124 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 12.870672 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 committed.
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 14.157876 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 committed.
20/05/30 12:17:51 INFO Executor: Finished task 2.0 in stage 0.0 (TID 2). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 1.0 in stage 0.0 (TID 1). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 3.0 in stage 0.0 (TID 3). 2297 bytes result sent to driver
20/05/30 12:17:51 INFO TaskSetManager: Finished task 2.0 in stage 0.0 (TID 2) in 227 ms on localhost (executor driver) (1/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 256 ms on localhost (executor driver) (2/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 233 ms on localhost (executor driver) (3/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 3.0 in stage 0.0 (TID 3) in 232 ms on localhost (executor driver) (4/4)
20/05/30 12:17:51 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/05/30 12:17:51 INFO DAGScheduler: ResultStage 0 (start at POCTestMain.scala:147) finished in 0.557 s
20/05/30 12:17:51 INFO DAGScheduler: Job 0 finished: start at POCTestMain.scala:147, took 0.616436 s
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Data source writer org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266 is committing.
-------------------------------------------
Batch: 0
-------------------------------------------
+-----+
|value|
+-----+
|   A8|
|   B9|
|   C4|
+-----+


问:
Eliminating auto zooming in mobile safari textarea widget?
I developed a web app for the iPhone which has a page with a textarea widget.  When I begin editing the contents of this textarea widget Safari zooms in and makes the text really, really big.  Now I can't see the document anymore, just a little postage stamp sized piece of it.

Are there any properties I can set which will keep mobile Safari from doint this?  I just want the textarea font to stay the same size when I edit its text.  Thanks.

答:
You would need to set your textarea font-size to 16px and have an initial-scale of 1.0.

But if your app is not really designed for the iPhone, that is, if it’s essentially a normal web page that users should be able to scale, then you should probably just become okay with it. The worst thing to do to your users is show them 6pt text they can’t zoom, you know? Some of them won’t have perfect vision.

See also: Apple's list of all Safari/iOS special meta tags.


问:
How to get unique values from table() function in R
I have a data frame which 31 columns. In column of Year (named "Anos"), I have rows which years are repeated and when I use table(df$Anos), I get frequency of years. I need only years with 12 observations (12 months).

Example:

freq_years <- table(df$Anos)
freq_years
Result:
2009 2010 2011 2012 2013 2014 2015 2017 2018 2019 2020
  10   12   12    3   11    6    8   12   12   12    5

How to get automatically in a new variable only years with freq = 12? (maybe like 2010,2011,2018,2019)

答:
We can create a logical vector and subset the names of the table output

```<code>names(freq_years)[freq_years == 12]
</code>```

Body:
We can create a logical vector and subset the names of the table output

names(freq_years)[freq_years == 12]


问:
Consistent hashing domino effect
I'm trying to figure out how a system like Cassandra which uses consistent hashing handles cascading node failures. I know there's this concept of virtual nodes and keys are mapped to virtual nodes. Virtual nodes are in turn mapped to actual physical nodes, the idea being that each physical nodes gets an equal share of the keyspace. My question is the following: what happens when a physical node goes down? All the virtual nodes that are on this physical node will need to be moved over to another physical node. Wont this lead to a domino effect which could overload other nodes in the cluster? How do real life systems handle cases like this?</p>

答:
When node goes down, there is no automatic movement of the token ranges. If node is completely down, token range rebalance should be triggered manually by removing the node, or assassinating it.  </p>

<p>When node that is responsible for some token ranges is going down, its replicas continue to serve the traffic. </p>

Title: Consistent hashing domino effect

Body:
When node goes down, there is no automatic movement of the token ranges. If node is completely down, token range rebalance should be triggered manually by removing the node, or assassinating it.

When node that is responsible for some token ranges is going down, its replicas continue to serve the traffic.


问:
How does Vector in Java Collection work
How does Vector in Java Collection work internally so that it can accept any type of Objects</p>

答:
Vector has initial capacity is 10.

we can define capacityincrement for Vector, if we didn't define capacityIncrement , in that case, Vector grow() will be double.

All methods are synchronized, so thread safety is there.

Returns an enumeration of the components of this vector

Performance is slow compare to ArrayList

Title: How does Vector in Java Collection work


问:
Microsoft graph notification when new channel created in teams
I would like to receive a webhook notification when a new channel is created in a group in microsoft teams.

I already implemented receiving notifications when user is added to a group through teams (using this API - https://learn.microsoft.com/en-us/graph/api/resources/subscription?view=graph-rest-1.0). Unfortunately, it seems like group subscription is not triggered when a new channel is added.

Is there any other subscription I can use? Thank you in advance.

答:
Subscribing to channel events is not supported today by Microsoft graph. You can upvote the following idea to help prioritize efforts and also be notified whenever progress is made.

https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests/suggestions/37288522-microsoft-teams-create-channel-with-a-webhook


问:
How to use @Autowired annotation two or more different Component class for same service?
For example, have a class like as follows.
First XService service in class A is not null but second XService service in AmountValidator is null.I get NullPointerException I try to create bean new it works and then I get same exception when call AmountValidateService outsideRestService in XService.
How can I  use XService everywhere that I use @Autowired annotation.

My main class:

```<code>@Service
 class A extends AbstractA implements  IA {
 @Autowired
 XService service; //first autowired definition. code go to check() method. service not null now.

public doSometing(){
    validator.check();
    service.methodA();
    super.AbstractMethod();
  }
}
</code>```

Validator class used in class A :

```<code> class Validator<T> implements IValidator<T> {
         public void check(){
             rule.check(); // rule have a implements IValidator eg: amountValidator, dateValidator class
          }
        }
</code>```

AmountValidator added to rule in class Validator.

```<code>@Component
class AmountValidator implements IValidator<T>{
@Autowired
XService service; // code comes here service is null. same service class mentioned above class A.

@Override
public void check(){
     service.validateAmount(); // nullPointerException.
  }
}
</code>```

My main Service

```<code>@Component
class XService {
@Autowired
AmountValidateService outsideRestService;

public validateAmount(){
    outsideRestService.validate(); // nullPointer when create XService with the `New` keyword
  }
}
</code>```

答: You have an error cause you are trying to create components/beans/services yourself. As i mentioned in comment when you create components yourself it - @Autowired doesn't work - thats you've got NPE

Body:
For example, have a class like as follows.
First XService service in class A is not null but second XService service in AmountValidator is null.I get NullPointerException I try to create bean new it works and then I get same exception when call AmountValidateService outsideRestService in XService.
How can I  use XService everywhere that I use @Autowired annotation.

My main class:

@Service
 class A extends AbstractA implements  IA {
 @Autowired
 XService service; //first autowired definition. code go to check() method. service not null now.

public doSometing(){
    validator.check();
    service.methodA();
    super.AbstractMethod();
  }
}

Validator class used in class A :

 class Validator<T> implements IValidator<T> {
         public void check(){
             rule.check(); // rule have a implements IValidator eg: amountValidator, dateValidator class
          }
        }

AmountValidator added to rule in class Validator.

@Component
class AmountValidator implements IValidator<T>{
@Autowired
XService service; // code comes here service is null. same service class mentioned above class A.

@Override
public void check(){
     service.validateAmount(); // nullPointerException.
  }
}

My main Service

@Component
class XService {
@Autowired
AmountValidateService outsideRestService;

public validateAmount(){
    outsideRestService.validate(); // nullPointer when create XService with the `New` keyword
  }
}


问:
knockout data-bind date NaN/NaN/NaN
I just tried to make a span with formatted date under foreach using knockout

I have this script

```<code>    Date.prototype.toFormattedDate = function () {
        var dd = this.getDate();
        if (dd < 10) dd = '0' + dd;
        var mm = this.getMonth() + 1;
        if (mm < 10) mm = '0' + mm;
        var yyyy = this.getFullYear();
        /* change format here */
        return String(dd + "/" + mm + "/" + yyyy);
    };
</code>```

and in html i try this

```<code><span class="form-control" data-bind="text: new Date(my_date).toFormattedDate() " />
</code>```

my_date is a string date "2020-09-13T00:00:00"

but it always shows NaN/NaN/NaN

i tried to use moment.js but it gave me "Invalid date"

Demo:

Date.prototype.toFormattedDate = function() {
  var dd = this.getDate();
  if (dd < 10) dd = '0' + dd;
  var mm = this.getMonth() + 1;
  if (mm < 10) mm = '0' + mm;
  var yyyy = this.getFullYear();
  /* change format here */
  return String(dd + "/" + mm + "/" + yyyy);
};

const formatted = new Date("2020-09-13T00:00:00").toFormattedDate();
console.log(formatted)```

答:
It's happening because my_date is an observable. new Date(my_date) will try to convert the observable to a date and it fails. So, get the value in the observable by using my_date() and use it in the new Date() constructor

Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};

ko.applyBindings({ my_date: ko.observable('2020-09-13T00:00:00') })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<span class="form-control" data-bind="text: new Date(my_date()).toFormattedDate() " /></code>```

Another option is to create a custom binding for your date format. You could move all the date format code to the custom binding directly if you don't want to pollute Date.prototype

```<code>function customDateHandler(element, valueAccessor) {
  var value = ko.unwrap(valueAccessor());
  element.textContent = new Date(value).toFormattedDate()
}

ko.bindingHandlers.customDateFormat = {
  init: customDateHandler,
  update: customDateHandler
};
</code>```

And use the binding in your span:

```<code><span class="form-control" data-bind="customDateFormat: my_date" />
</code>```

Here's a snippet:

function customDateHandler(element, valueAccessor) {
  var value = ko.unwrap(valueAccessor());
  element.textContent = new Date(value).toFormattedDate()
}

ko.bindingHandlers.customDateFormat = {
  init: customDateHandler,
  update: customDateHandler
};

Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};

ko.applyBindings({ my_date: ko.observable('2020-09-13') })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="customDateFormat: my_date" /></code>```

Title: knockout data-bind date NaN/NaN/NaN

Body:
I just tried to make a span with formatted date under foreach using knockout

I have this script

    Date.prototype.toFormattedDate = function () {
        var dd = this.getDate();
        if (dd < 10) dd = '0' + dd;
        var mm = this.getMonth() + 1;
        if (mm < 10) mm = '0' + mm;
        var yyyy = this.getFullYear();
        /* change format here */
        return String(dd + "/" + mm + "/" + yyyy);
    };

and in html i try this

my_date is a string date "2020-09-13T00:00:00"

but it always shows NaN/NaN/NaN

i tried to use moment.js but it gave me "Invalid date"

Demo:

Date.prototype.toFormattedDate = function() {
  var dd = this.getDate();
  if (dd < 10) dd = '0' + dd;
  var mm = this.getMonth() + 1;
  if (mm < 10) mm = '0' + mm;
  var yyyy = this.getFullYear();
  /* change format here */
  return String(dd + "/" + mm + "/" + yyyy);
};

const formatted = new Date("2020-09-13T00:00:00").toFormattedDate();
console.log(formatted)

Body:
It's happening because my_date is an observable. new Date(my_date) will try to convert the observable to a date and it fails. So, get the value in the observable by using my_date() and use it in the new Date() constructor

Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};

ko.applyBindings({ my_date: ko.observable('2020-09-13T00:00:00') })

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<span class="form-control" data-bind="text: new Date(my_date()).toFormattedDate() " />

Another option is to create a custom binding for your date format. You could move all the date format code to the custom binding directly if you don't want to pollute Date.prototype

function customDateHandler(element, valueAccessor) {
  var value = ko.unwrap(valueAccessor());
  element.textContent = new Date(value).toFormattedDate()
}

ko.bindingHandlers.customDateFormat = {
  init: customDateHandler,
  update: customDateHandler
};

And use the binding in your span:

<span class="form-control" data-bind="customDateFormat: my_date" />

Here's a snippet:

function customDateHandler(element, valueAccessor) {
  var value = ko.unwrap(valueAccessor());
  element.textContent = new Date(value).toFormattedDate()
}

ko.bindingHandlers.customDateFormat = {
  init: customDateHandler,
  update: customDateHandler
};

Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};

ko.applyBindings({ my_date: ko.observable('2020-09-13') })

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="customDateFormat: my_date" />


问:
Why does spark-submit ignore the package that I include as part of the configuration of my spark session?
I am trying to include the org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3 package as part of my spark code (via the SparkSession Builder). I understand that I can download the JAR myself and include it but I would like to figure out why the following is not working as expected:

```<code>from pyspark.sql import SparkSession
import pyspark
import json

if __name__ == "__main__":
    spark = SparkSession.builder \
        .master("local") \
        .appName("App Name") \
        .config("spark.jars.packages", "org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3") \
        .getOrCreate()

    df = spark \
        .readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "localhost:9092") \
        .option("subscribe", "first_topic") \
        .load() \
        .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")

    query = df \
        .writeStream \
        .format("console") \
        .outputMode("update") \
        .start()
</code>```

When I run the job:

```<code>spark-submit main.py
</code>```

I receive the following error:

```<code>py4j.protocol.Py4JJavaError: An error occurred while calling o48.load.
: org.apache.spark.sql.AnalysisException: Failed to find data source: kafka. Please deploy the application as per the deployment section of "Structured Streaming + Kafka Integration Guide".;
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:652)
    at org.apache.spark.sql.streaming.DataStreamReader.load(DataStreamReader.scala:161)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
</code>```

If I instead include the packages via the --packages flag, the dependencies are downloaded and the code runs as expected:

```<code>spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3 main.py
</code>```

The code also works if I open the PySpark shell and paste the code above. Is there a reason that the spark-submit ignores the configuration?

答:
I think that for configurations like "spark.jars.packages", these should be configured either in spark-defaults or passed by command-line arguments, setting it in the runtime shouldn't work.

Against better judgement

I remember some people claimed something like this worked for them, but I would say that the dependency is already somewhere there (installed in local repo), just loaded.

conf = pyspark.SparkConf()
conf.set("spark.jars.packages", "org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3")

spark = SparkSession.builder \
        .master("local") \
        .appName("App Name") \
        .config(conf = conf) \
        .getOrCreate()
```

Body:
I am trying to include the org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3 package as part of my spark code (via the SparkSession Builder). I understand that I can download the JAR myself and include it but I would like to figure out why the following is not working as expected:

from pyspark.sql import SparkSession
import pyspark
import json

if __name__ == "__main__":
    spark = SparkSession.builder \
        .master("local") \
        .appName("App Name") \
        .config("spark.jars.packages", "org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3") \
        .getOrCreate()

    df = spark \
        .readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "localhost:9092") \
        .option("subscribe", "first_topic") \
        .load() \
        .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")

    query = df \
        .writeStream \
        .format("console") \
        .outputMode("update") \
        .start()

When I run the job:

spark-submit main.py

I receive the following error:

py4j.protocol.Py4JJavaError: An error occurred while calling o48.load.
: org.apache.spark.sql.AnalysisException: Failed to find data source: kafka. Please deploy the application as per the deployment section of "Structured Streaming + Kafka Integration Guide".;
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:652)
    at org.apache.spark.sql.streaming.DataStreamReader.load(DataStreamReader.scala:161)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)

If I instead include the packages via the --packages flag, the dependencies are downloaded and the code runs as expected:

spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.3 main.py

The code also works if I open the PySpark shell and paste the code above. Is there a reason that the spark-submit ignores the configuration?


问:
Get image path from SQLITE recycler view Error
Can anyone help me to understand my mistake?
What I am trying to achieve is to get the image path from SQLite dB and insert into recycler view. Folder with all images will be in res/drawable.
In adapter class, I have declared Context and is private global and in onCreateViewHolder, I added context = parent.getContext();
Also in DBModel class, I changed everywhere from bitmap to string and in DB file from blob to TEXT.

```<code>public void onBindViewHolder(@NonNull DBViewHolder holder, int position) {

    ModelClass objModelClass = objModelClassArrayList.get(position);

    holder.description_sign.setText(objModelClass.getDescription());

    //context = holder.image_sign.getContext();
    //int resAd = getIdentifier(image_path,"drawable",context.getPackageName());
    int i = context.getResources().getIdentifier(objModelClass.getImage(),"drawable",context.getPackageName());
    holder.image_sign.setImageResource(i);

        //holder.image_sign.setImageBitmap(objModelClass.getImage());  <- It works but i don't want that.
    }

>  E/AndroidRuntime: FATAL EXCEPTION: main
>             Process: com.example.dissertation, PID: 5449
>             java.lang.NullPointerException: name is null
>                 at android.content.res.ResourcesImpl.getIdentifier(ResourcesImpl.java:240)
>                 at android.content.res.Resources.getIdentifier(Resources.java:1927)
</code>```

答:
```<code>    ModelClass objModelClass = objModelClassArrayList.get(position);

    holder.description_sign.setText(objModelClass.getDescription())
    String uri = "@drawable/" + objModelClass.getImage();
    int imageResource = holder.itemView.getResources().getIdentifier(uri, null, holder.itemView.getContext().getPackageName());
    holder.image_sign.setImageResource(imageResource);
</code>```

It should also be declared Context as global and in onCreateViewHolder to refer to it context = parent.getContext();

Body:
Can anyone help me to understand my mistake?
What I am trying to achieve is to get the image path from SQLite dB and insert into recycler view. Folder with all images will be in res/drawable.
In adapter class, I have declared Context and is private global and in onCreateViewHolder, I added context = parent.getContext();
Also in DBModel class, I changed everywhere from bitmap to string and in DB file from blob to TEXT.

public void onBindViewHolder(@NonNull DBViewHolder holder, int position) {

    ModelClass objModelClass = objModelClassArrayList.get(position);

    holder.description_sign.setText(objModelClass.getDescription());

    //context = holder.image_sign.getContext();
    //int resAd = getIdentifier(image_path,"drawable",context.getPackageName());
    int i = context.getResources().getIdentifier(objModelClass.getImage(),"drawable",context.getPackageName());
    holder.image_sign.setImageResource(i);

        //holder.image_sign.setImageBitmap(objModelClass.getImage());  <- It works but i don't want that.
    }

>  E/AndroidRuntime: FATAL EXCEPTION: main
>             Process: com.example.dissertation, PID: 5449
>             java.lang.NullPointerException: name is null
>                 at android.content.res.ResourcesImpl.getIdentifier(ResourcesImpl.java:240)
>                 at android.content.res.Resources.getIdentifier(Resources.java:1927)

Body:
    ModelClass objModelClass = objModelClassArrayList.get(position);

    holder.description_sign.setText(objModelClass.getDescription())
    String uri = "@drawable/" + objModelClass.getImage();
    int imageResource = holder.itemView.getResources().getIdentifier(uri, null, holder.itemView.getContext().getPackageName());
    holder.image_sign.setImageResource(imageResource);

It should also be declared Context as global and in onCreateViewHolder to refer to it context = parent.getContext();


问:
Trouble with bot.wait_for() Discord.py
So modern documentation on the bot.wait_for() coroutine is not super detailed, and I'm having trouble getting it to work with reactions. Would appreciate feedback.

Python 3 with Discord.py

```<code>## Test Role Add
@kelutralBot.command(name='testreaction')
async def testReaction(ctx):
    member = ctx.message.author
    message = await ctx.send("This is a test message.")
    emojis = ['\u2642','\u2640','\u2716']
    for emoji in emojis:
        await message.add_reaction(emoji)

    def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '\u2642'

    try:
        reaction, user = await kelutral.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
    else:
        print(reaction)
        male = get(member.guild.roles, name="He/Him")
        await member.add_roles(male)
        print("Assigned " + member.name + " He/Him pronouns.")
</code>```

答:
The problem here is that you are checking if the person who sent the reaction is the author of the message that contains the message, which is only satisfied by the bot that reacted. Also consider using a role ID instead (server settings > roles > left click role > right click role > copy ID). You also want to be consistent with kelutral or kelutral Bot throughout the command.

@kelutralBot.command(name='testreaction')
async def testReaction(ctx):
    member = ctx.message.author
    message = await ctx.send("This is a test message.")
    emojis = ['\u2642','\u2640','\u2716']
    for emoji in emojis:
        await message.add_reaction(emoji)

    def check(reaction, user):
        return user == member and str(reaction.emoji) == '\u2642' # check against the member who sent the command, not the author of the message

    try:
        reaction, user = await kelutralBot.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
    else:
        print(reaction)
        male = ctx.message.guild.get_role(ROLE_ID_GOES_HERE) # put your role ID here #
        await member.add_roles(male)
        print(f"Assigned {member.name} He/Him pronouns.")
```

Keep in mind your code only works for the "male" role, you have to implement a different check function to use it for everything.

Title: Trouble with bot.wait_for() Discord.py

Body:
So modern documentation on the bot.wait_for() coroutine is not super detailed, and I'm having trouble getting it to work with reactions. Would appreciate feedback.

Python 3 with Discord.py

## Test Role Add
@kelutralBot.command(name='testreaction')
async def testReaction(ctx):
    member = ctx.message.author
    message = await ctx.send("This is a test message.")
    emojis = ['\u2642','\u2640','\u2716']
    for emoji in emojis:
        await message.add_reaction(emoji)

    def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '\u2642'

    try:
        reaction, user = await kelutral.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
    else:
        print(reaction)
        male = get(member.guild.roles, name="He/Him")
        await member.add_roles(male)
        print("Assigned " + member.name + " He/Him pronouns.")

Body:
The problem here is that you are checking if the person who sent the reaction is the author of the message that contains the message, which is only satisfied by the bot that reacted. Also consider using a role ID instead (server settings > roles > left click role > right click role > copy ID). You also want to be consistent with kelutral or kelutral Bot throughout the command.

@kelutralBot.command(name='testreaction')
async def testReaction(ctx):
    member = ctx.message.author
    message = await ctx.send("This is a test message.")
    emojis = ['\u2642','\u2640','\u2716']
    for emoji in emojis:
        await message.add_reaction(emoji)

    def check(reaction, user):
        return user == member and str(reaction.emoji) == '\u2642' # check against the member who sent the command, not the author of the message

    try:
        reaction, user = await kelutralBot.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
    else:
        print(reaction)
        male = ctx.message.guild.get_role(ROLE_ID_GOES_HERE) # put your role ID here #
        await member.add_roles(male)
        print(f"Assigned {member.name} He/Him pronouns.")

Keep in mind your code only works for the "male" role, you have to implement a different check function to use it for everything.


问:
UIImageView circular shape swift
I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and  layoutSubviews() </p>

```<code>  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1
</code>```

答:
if you create you tableviewCell programmatically you have to override init</p>

```<code>override init(style: UITableViewCell.CellStyle,   reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier:  reuseIdentifier)
//put your code here
}
</code>```

Title: UIImageView circular shape swift

Body:
I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and  layoutSubviews()

  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1

Body:
if you create you tableviewCell programmatically you have to override init

override init(style: UITableViewCell.CellStyle,   reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier:  reuseIdentifier)
//put your code here
}


问:
How to handle posted multipart/form-data when its send to PHP?
Rather simple question but I'm new to handling formdata and blobs. I need to handle a formdata file that contains both a blob and a string. The blob is first downloaded and then sent successfully to testPDF however in doing a var_dump of $_FILE['pdf_blob'] or $_POST['pdf_blob'] it comes out null, so probably I'm doing something wrong. Below the relevant ajax block

```<code>        var pdf_blob = new FormData();
        pdf_blob.append(filename, my_blob);
        pdf_blob.append('string', global_hash);

        $.ajax({
            url :  "testPDF.php",
            type: 'POST',
            data: pdf_blob,
            contentType: false,
            processData: false,
            success: function(data) {
            },
            error: function() {
              alert("error");
            }
        });
</code>```

Logging in console shows me that pdf_blob is not empty before it is sent through ajax

```<code>console.log(pdf_blob.get(filename));
console.log(pdf_blob.get('string'));
</code>```

答:
Solved by adding a name to the field separate from the blob's filename, like so:
Javascript

```<code>pdf_blob.append('blob', my_blob, filename);
</code>```

then on PHP

```<code>var_dump($_FILE['blob']);
</code>```

var_dumping $_FILE directly or $_FILE[0] will always be empty

Body:
Rather simple question but I'm new to handling formdata and blobs. I need to handle a formdata file that contains both a blob and a string. The blob is first downloaded and then sent successfully to testPDF however in doing a var_dump of $_FILE['pdf_blob'] or $_POST['pdf_blob'] it comes out null, so probably I'm doing something wrong. Below the relevant ajax block

        var pdf_blob = new FormData();
        pdf_blob.append(filename, my_blob);
        pdf_blob.append('string', global_hash);

        $.ajax({
            url :  "testPDF.php",
            type: 'POST',
            data: pdf_blob,
            contentType: false,
            processData: false,
            success: function(data) {
            },
            error: function() {
              alert("error");
            }
        });

Logging in console shows me that pdf_blob is not empty before it is sent through ajax

console.log(pdf_blob.get(filename));
console.log(pdf_blob.get('string'));

Body:
Solved by adding a name to the field separate from the blob's filename, like so:
Javascript

pdf_blob.append('blob', my_blob, filename);

then on PHP

var_dump($_FILE['blob']);

var_dumping $_FILE directly or $_FILE[0] will always be empty


问:
JavaFX TreeTableColumn: how to trigger column resizing and keep a new width
The question is in the title: is it possible to catch the resize of column (TreeTableColumn) to apply a new column size?

答:
Add a Listener to the columns width property. Something like this:

```<code>col.widthProperty().addListener(e->{
            if(!running.get()) {
                running.set(true);
                Runnable task = () -> {
                    try {Thread.sleep(2000);} catch (InterruptedException exc) {    }
                    Platform.runLater( () -> {
                            col.setPrefWidth(79);
                            col.setPrefWidth(80);
                    });
                    running.set(false);
                    System.out.println("done");
                };
                new Thread(task).start();
            }
        });
</code>```

If the prefWidth is just set to the previous value nothing happens. It has to actually change before the column resizes.

Body:
Add a Listener to the columns width property. Something like this:

col.widthProperty().addListener(e->{
            if(!running.get()) {
                running.set(true);
                Runnable task = () -> {
                    try {Thread.sleep(2000);} catch (InterruptedException exc) {    }
                    Platform.runLater( () -> {
                            col.setPrefWidth(79);
                            col.setPrefWidth(80);
                    });
                    running.set(false);
                    System.out.println("done");
                };
                new Thread(task).start();
            }
        });

If the prefWidth is just set to the previous value nothing happens. It has to actually change before the column resizes.