问:
Scikit Learn PolynomialFeatures - what is the use of the include_bias option?
In scikit-learn's PolynomialFeatures preprocessor, there is an option to include_bias. This essentially just adds a column of ones to the dataframe. I was wondering what the point of having this was. Of course, you can set it to False. But theoretically how does having or not having a column of ones along with the Polynomial Features generated affect Regression.

This is the explanation in the documentation, but I can't seem to get anything useful out of it relation to why it should be used or not.

include_bias : boolean

If True (default), then include a bias column, the feature in which
  all polynomial powers are zero (i.e. a column of ones - acts as an
  intercept term in a linear model).

答:
Suppose you want to perform the following regression:

```<code>y ~ a + b x + c x^2
</code>```

where x is a generic sample. The best coefficients a,b,c are computed via simple matricial calculus. First, let us denote with X = [1 | X | X^2] a matrix with N rows, where N is the number of samples. The first column is a column of 1s, the second column is a column of values x_i, for all the samples i, the third column is a column of values x_i^2, for all samples i. Let us denote with B the following column vector B=[a b c]^T If Y is a column vector of the N target values for all samples i, we can write the regression as

```<code>y ~ X B
</code>```

The i-th row of this equation is y_i ~ [1 x_i x^2] [a b c]^t = a + b x_i + c x_i^2.

The goal of training a regression is to find B=[a b c] such that X B be as close as possible to y.

If you don't add a column of 1, you are assuming a-priori that a=0, which might not be correct.

In practice, when you write Python code, and you use PolynomialFeatures together with sklearn.linear_model.LinearRegression, the latter takes care by default of adding a column of 1s (since in LinearRegression the fit_intercept parameter is True by default), so you don't need to add it as well in PolynomialFeatures. Therefore, in PolynomialFeatures one usually keeps include_bias=False.

The situation is different if you use statsmodels.OLS instead of LinearRegression

Body:
Suppose you want to perform the following regression:

y ~ a + b x + c x^2

where x is a generic sample. The best coefficients a,b,c are computed via simple matricial calculus. First, let us denote with X = [1 | X | X^2] a matrix with N rows, where N is the number of samples. The first column is a column of 1s, the second column is a column of values x_i, for all the samples i, the third column is a column of values x_i^2, for all samples i. Let us denote with B the following column vector B=[a b c]^T If Y is a column vector of the N target values for all samples i, we can write the regression as

y ~ X B

The i-th row of this equation is y_i ~ [1 x_i x^2] [a b c]^t = a + b x_i + c x_i^2.

The goal of training a regression is to find B=[a b c] such that X B be as close as possible to y.

If you don't add a column of 1, you are assuming a-priori that a=0, which might not be correct.

In practice, when you write Python code, and you use PolynomialFeatures together with sklearn.linear_model.LinearRegression, the latter takes care by default of adding a column of 1s (since in LinearRegression the fit_intercept parameter is True by default), so you don't need to add it as well in PolynomialFeatures. Therefore, in PolynomialFeatures one usually keeps include_bias=False.

The situation is different if you use statsmodels.OLS instead of LinearRegression


来源: stackexchange

问:
react-select dropdown to be required
I am new to react.

I am trying to use below library to use dropdown.

When I added 'required' attribute, it doesn't validate it with the form tag.

https://www.npmjs.com/package/react-select

```<code>import React from 'react';
import Select from 'react-select';

const options = [{
        value: 'chocolate',
        label: 'Chocolate'
    },
    {
        value: 'strawberry',
        label: 'Strawberry'
    },
    {
        value: 'vanilla',
        label: 'Vanilla'
    },
];

class App extends React.Component {
    state = {
        selectedOption: null,
    };
    handleChange = selectedOption => {
        this.setState({
            selectedOption
        });
        console.log(`Option selected:`, selectedOption);
    };
    render() {
        const {
            selectedOption
        } = this.state;

        return ( <
            Select value = {
                selectedOption
            }
            onChange = {
                this.handleChange
            }
            options = {
                options
            }
            //required
            />
        );
    }
}
</code>```

When I looked at it from the console, it shows that input tag is wrapped with bunch of div. Is there a way to access the input from  Component? or is there a javascript code that I can access to input tag in order to add required directly?

答:
I made a tiny example of using Ant-Design form, check that on codesandbox

```<code>import React from "react";
import { Form, Select, Button } from "antd";
import "./styles.css";
import "antd/dist/antd.css";
const { Option } = Select;

const AppWithForm = props => {
  const { getFieldDecorator } = props.form;

  const handleSubmit = () => {
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log("Received values of form: ", values);
      } else console.log("form is NOT valid");
    });
  };

  const onChange = value => {
    console.log(`selected ${value}`);
  };

  return (
    <div className="App">
      <Form layout="inline">
        <Form.Item>
          {getFieldDecorator("dropdown", {
            rules: [{ required: true, message: "Please select a person!" }]
          })(
            <Select
              showSearch={false}
              style={{ width: 200 }}
              placeholder="Select a person"
              optionFilterProp="children"
              onChange={onChange}
            >
              <Option value="jack">Jack</Option>
              <Option value="lucy">Lucy</Option>
              <Option value="tom">Tom</Option>
            </Select>
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleSubmit}>
            Save
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

const App = Form.create({})(AppWithForm);

export default App;
</code>```

you should wrap your component with ant-design Form HOC, it's pass a lot of function as a props to your component so you can handle your form with them by using 'getFieldDecorator', 'validateFields'

https://codesandbox.io/s/trusting-microservice-11418

ContentLicense: CC BY-SA 4.0

Title: react-select dropdown to be required

Body:
I am new to react.

I am trying to use below library to use dropdown.

When I added 'required' attribute, it doesn't validate it with the form tag.

https://www.npmjs.com/package/react-select

import React from 'react';
import Select from 'react-select';

const options = [{
        value: 'chocolate',
        label: 'Chocolate'
    },
    {
        value: 'strawberry',
        label: 'Strawberry'
    },
    {
        value: 'vanilla',
        label: 'Vanilla'
    },
];

class App extends React.Component {
    state = {
        selectedOption: null,
    };
    handleChange = selectedOption => {
        this.setState({
            selectedOption
        });
        console.log(`Option selected:`, selectedOption);
    };
    render() {
        const {
            selectedOption
        } = this.state;

        return ( <
            Select value = {
                selectedOption
            }
            onChange = {
                this.handleChange
            }
            options = {
                options
            }
            //required
            />
        );
    }
}

When I looked at it from the console, it shows that input tag is wrapped with bunch of div. Is there a way to access the input from  Component? or is there a javascript code that I can access to input tag in order to add required directly?

Body:
I made a tiny example of using Ant-Design form, check that on codesandbox

import React from "react";
import { Form, Select, Button } from "antd";
import "./styles.css";
import "antd/dist/antd.css";
const { Option } = Select;

const AppWithForm = props => {
  const { getFieldDecorator } = props.form;

  const handleSubmit = () => {
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log("Received values of form: ", values);
      } else console.log("form is NOT valid");
    });
  };

  const onChange = value => {
    console.log(`selected ${value}`);
  };

  return (
    <div className="App">
      <Form layout="inline">
        <Form.Item>
          {getFieldDecorator("dropdown", {
            rules: [{ required: true, message: "Please select a person!" }]
          })(
            <Select
              showSearch={false}
              style={{ width: 200 }}
              placeholder="Select a person"
              optionFilterProp="children"
              onChange={onChange}
            >
              <Option value="jack">Jack</Option>
              <Option value="lucy">Lucy</Option>
              <Option value="tom">Tom</Option>
            </Select>
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleSubmit}>
            Save
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

const App = Form.create({})(AppWithForm);

export default App;

you should wrap your component with ant-design Form HOC, it's pass a lot of function as a props to your component so you can handle your form with them by using 'getFieldDecorator', 'validateFields'

https://codesandbox.io/s/trusting-microservice-11418


问:
HTML/JS: Pause vertical scrolling and animate an element instead
I have a website that contains a
 element with horizontal overflow. I want the div to scroll horizontally from left to right as the user scrolls the website vertically from top to bottom. During that stage, the main content should not move, only the div should scroll. Once the div has been scrolled completely to the right, the vertical scrolling of the website should continue normally. The same should also work backwards.

I tried using ScrollMagic with pinning, however I experience stutters when trying to pin the main content container:

https://codepen.io/oelrim/pen/ZEGWvOK

Is there some other plugin that can achieve what I want?

答:
Try this:

var scene = document.querySelector('#sec-2');
var rect = document.querySelector('#rect');

var startEffect = scene.getBoundingClientRect().top + window.scrollY;
var effectLength = 500;

scene.style.marginBottom = effectLength +'px';
window.addEventListener('scroll', function(e){
  var effect = window.scrollY - startEffect;

if(effect > 0 && effect < effectLength) {
  scene.style.marginTop = effect+'px';
  scene.style.marginBottom = effectLength-effect+'px';
  rect.style.left = effect * (scene.offsetWidth-rect.offsetWidth) /effectLength+'px';
} else if (effect < 0) {
  scene.style.marginTop = 0;
  scene.style.marginBottom = effectLength+'px';
  rect.style.left = 0;
} else {
  scene.style.marginTop = effectLength+'px';
  scene.style.marginBottom = 0;
  rect.style.left = (scene.offsetWidth-rect.offsetWidth)+'px';
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {padding:0;margin:0}

#sec-1 {
height: 100vh;
background: repeating-linear-gradient(yellow 0, yellow 10px, green 10px, green 20px);
}
#sec-2 {
position: relative;
height: 100vh;
background: repeating-linear-gradient(red 0, red 10px, green 10px, green 20px);}
#sec-3 {
  height: 100vh;
background: repeating-linear-gradient(red 0, red 10px, blue 10px, blue 20px);}
h1 {
color: white;
text-shadow:  2px 2px 3px black, -2px -2px 3px black;
margin: 0;
}
#rect {
position: absolute;
width: 60px;
height: 60px;
background-color: white;
top: calc(50% - 30px);
left: 0;
}</code>```

This is section 1

This is section 2

This is section 3

```

Body:
Try this:

var scene = document.querySelector('#sec-2');
var rect = document.querySelector('#rect');

var startEffect = scene.getBoundingClientRect().top + window.scrollY;
var effectLength = 500;

scene.style.marginBottom = effectLength +'px';
window.addEventListener('scroll', function(e){
  var effect = window.scrollY - startEffect;

if(effect > 0 && effect < effectLength) {
  scene.style.marginTop = effect+'px';
  scene.style.marginBottom = effectLength-effect+'px';
  rect.style.left = effect * (scene.offsetWidth-rect.offsetWidth) /effectLength+'px';
} else if (effect < 0) {
  scene.style.marginTop = 0;
  scene.style.marginBottom = effectLength+'px';
  rect.style.left = 0;
} else {
  scene.style.marginTop = effectLength+'px';
  scene.style.marginBottom = 0;
  rect.style.left = (scene.offsetWidth-rect.offsetWidth)+'px';
}

});

html, body {padding:0;margin:0}

#sec-1 {
height: 100vh;
background: repeating-linear-gradient(yellow 0, yellow 10px, green 10px, green 20px);
}
#sec-2 {
position: relative;
height: 100vh;
background: repeating-linear-gradient(red 0, red 10px, green 10px, green 20px);}
#sec-3 {
  height: 100vh;
background: repeating-linear-gradient(red 0, red 10px, blue 10px, blue 20px);}
h1 {
color: white;
text-shadow:  2px 2px 3px black, -2px -2px 3px black;
margin: 0;
}
#rect {
position: absolute;
width: 60px;
height: 60px;
background-color: white;
top: calc(50% - 30px);
left: 0;
}

<div id="sec-1">
<h1>This is section 1</h1>
</div>
<div id="sec-2">
<h1>This is section 2</h1>
<div id="rect"></div>
</div>
<div id="sec-3">
<h1>This is section 3</h1>
</div>


问:
iOS - unarchive NSSecureCoding Object that has a property of type Date
```<code>   @objc(EventNotificationInfo)
    class EventNotificationInfo: NSObject, NSSecureCoding {
        public var name: String
        public var startTime: Date
        public var hexColor: String

         init(name: String, startTime: Date, hexColor: String) {
            self.name = name
            self.startTime = startTime
            self.hexColor = hexColor
        }

        private  struct Keys {
            static var name: String = "name"
            static let startTime: String = "startTime"
            static let hexColor: String = "hexColor"
        }

        static var supportsSecureCoding: Bool = true

        func encode(with coder: NSCoder) {
            coder.encode(name, forKey: Keys.name)
            coder.encode(startTime, forKey: Keys.startTime)
            coder.encode(hexColor, forKey: Keys.hexColor)
        }

        required init?(coder: NSCoder) {
            guard let name = coder.decodeObject(forKey: Keys.name) as? String  else {
                return nil
            }

            guard let startTime = coder.decodeObject(forKey: Keys.startTime) as? Date else {
                print("You are here")
                return nil
            }

            guard let color = coder.decodeObject(forKey: Keys.hexColor) as? String  else {
                return nil
            }
            self.name = name
            self.startTime = startTime
            self.hexColor = color
        }
    }
</code>```

An instance of the EventNotificationInfo object.

```<code>let event = EventNotificationInfo(name: "Hello from California",
                                        startTime:Date(),
                                        hexColor: "000000")
</code>```

Using the following code, I archive and unarchive the above object.

```<code>let eventInfo  = try? NSKeyedArchiver.archivedData(withRootObject: event, requiringSecureCoding: false)

let unArchive = try! NSKeyedUnarchiver.unarchivedObject(ofClass: TPEventNotificationInfo.self, from: eventInfo!)
</code>```

A Fatal error occurs when the xCode reaches a breakpoint that i set on the last line (unArchive variable). This is the console's message.

```<code>You are here.
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'startTime' was of unexpected class 'NSDate'. Allowed classes are '{(
    EventNotificationInfo
)}'." UserInfo={NSDebugDescription=value for key 'startTime' was of unexpected class 'NSDate'. Allowed classes are '{(
    EventNotificationInfo
)}'.}: file
</code>```

What could be the problem? How to unarchive this object?

Info: I have used startTime of type String. And it went well.

答:
Per the documentation for NSSecureCoding:

An object that does override init(coder:) must decode any enclosed
  objects using the decodeObjectOfClass:forKey: method. For example:

let obj = decoder.decodeObject(of:MyClass.self, forKey: "myKey")

You should do this in your implementation of init(coder:).

```<code>guard let startTime = coder.decodeObject(of: NSDate.self, forKey: Keys.startTime) as Date? else {
    return nil
}
</code>```

In addition, instead of using try!, you should wrap this in a do/catch so that you would see if an errors occurs.

Body:
   @objc(EventNotificationInfo)
    class EventNotificationInfo: NSObject, NSSecureCoding {
        public var name: String
        public var startTime: Date
        public var hexColor: String

         init(name: String, startTime: Date, hexColor: String) {
            self.name = name
            self.startTime = startTime
            self.hexColor = hexColor
        }

        private  struct Keys {
            static var name: String = "name"
            static let startTime: String = "startTime"
            static let hexColor: String = "hexColor"
        }

        static var supportsSecureCoding: Bool = true

        func encode(with coder: NSCoder) {
            coder.encode(name, forKey: Keys.name)
            coder.encode(startTime, forKey: Keys.startTime)
            coder.encode(hexColor, forKey: Keys.hexColor)
        }

        required init?(coder: NSCoder) {
            guard let name = coder.decodeObject(forKey: Keys.name) as? String  else {
                return nil
            }

            guard let startTime = coder.decodeObject(forKey: Keys.startTime) as? Date else {
                print("You are here")
                return nil
            }

            guard let color = coder.decodeObject(forKey: Keys.hexColor) as? String  else {
                return nil
            }
            self.name = name
            self.startTime = startTime
            self.hexColor = color
        }
    }

An instance of the EventNotificationInfo object.

let event = EventNotificationInfo(name: "Hello from California",
                                        startTime:Date(),
                                        hexColor: "000000")

Using the following code, I archive and unarchive the above object.

let eventInfo  = try? NSKeyedArchiver.archivedData(withRootObject: event, requiringSecureCoding: false)

let unArchive = try! NSKeyedUnarchiver.unarchivedObject(ofClass: TPEventNotificationInfo.self, from: eventInfo!)

A Fatal error occurs when the xCode reaches a breakpoint that i set on the last line (unArchive variable). This is the console's message.

You are here.
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'startTime' was of unexpected class 'NSDate'. Allowed classes are '{(
    EventNotificationInfo
)}'." UserInfo={NSDebugDescription=value for key 'startTime' was of unexpected class 'NSDate'. Allowed classes are '{(
    EventNotificationInfo
)}'.}: file

What could be the problem? How to unarchive this object?

Info: I have used startTime of type String. And it went well.

Body:
Per the documentation for NSSecureCoding:

An object that does override init(coder:) must decode any enclosed
  objects using the decodeObjectOfClass:forKey: method. For example:

let obj = decoder.decodeObject(of:MyClass.self, forKey: "myKey")

You should do this in your implementation of init(coder:).

guard let startTime = coder.decodeObject(of: NSDate.self, forKey: Keys.startTime) as Date? else {
    return nil
}

In addition, instead of using try!, you should wrap this in a do/catch so that you would see if an errors occurs.


问:
INDIRECT from another sheet
I am trying to figure out the correct syntax to have this formula reference a different sheet.
I need =INDIRECT((ADDRESS(((COUNTA($E$5:$E$204))/2)+4,7))) to reference sheet Line 3

答: Thanks Ron Rosenfeld & Justnya MK, I'm an idiot my syntax for the Sheet_Text was missing the extra 2 ,

Title: INDIRECT from another sheet


问:
How do I add a gui to an already written code?
I am currently working on my Computer Science Internal Assessment and am doing Object-Oriented Programming using java in Netbeans.

I have written the code and the output works as i want it to but I was wondering if there was an easy way to switch from using the output terminal to using a GUI for the user interface.

答:
I might misunderstand your question but if you're using netbeans then make a GUI with it! They have a drag and drop interface which is easy to use.

You can make a JTextField for each of your inputs for the program and reference the value in the text field like so...

```<code>String value = textField.getText();
</code>```

If you've never made a netbeans GUI before you can probably find a simple youtube video to get you started.

Goodluck ;)

Body:
I might misunderstand your question but if you're using netbeans then make a GUI with it! They have a drag and drop interface which is easy to use.

You can make a JTextField for each of your inputs for the program and reference the value in the text field like so...

String value = textField.getText();

If you've never made a netbeans GUI before you can probably find a simple youtube video to get you started.

Goodluck ;)


问:
Data structure padding
What is data structure padding in c++ and how do i check the number of bytes padded bytes?</p>

```<code>class a { public: int x; int y; int z; };
</code>```

答:
padding is done for performance reasons - see this article Data Structure Alignment for more info.

To see whether the compiler pads your data structure you could write a simple program:

```<code>#include <iostream>

class a {
public:
    int x;
    int y;
    int z;
};

int main()
{
    std::cout << sizeof(a) << std::endl; // print the total size in bytes required per class instance

    a anInstance;
    std::cout << &anInstance.x << std::endl; // print the address of the x member
    std::cout << &anInstance.y << std::endl; // as above but for y
    std::cout << &anInstance.z << std::endl; // etc
}
</code>```

I added the public declaration to avoid compiler errors - It will not affect the size or padding.

Edit: Running this on my macbook air gives the following output:
    12
    0x7fff5fbff650
    0x7fff5fbff654
    0x7fff5fbff658

This shows that on my machine the total size is 12 bytes, and each member is 4 bytes apart. The ints are 4 bytes each (which can be confirmed with sizeof(int)). There is no padding.

Try this with different members in your class, for example:

```<code>class b {
    public:
        char      w;
        char      x[6];
        int       y;
        long long z;
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: Data structure padding

Body:
What is data structure padding in c++ and how do i check the number of bytes padded bytes?

class a { public: int x; int y; int z; };

Body:
padding is done for performance reasons - see this article Data Structure Alignment for more info.

To see whether the compiler pads your data structure you could write a simple program:

#include <iostream>

class a {
public:
    int x;
    int y;
    int z;
};

int main()
{
    std::cout << sizeof(a) << std::endl; // print the total size in bytes required per class instance

    a anInstance;
    std::cout << &anInstance.x << std::endl; // print the address of the x member
    std::cout << &anInstance.y << std::endl; // as above but for y
    std::cout << &anInstance.z << std::endl; // etc
}

I added the public declaration to avoid compiler errors - It will not affect the size or padding.

Edit: Running this on my macbook air gives the following output:
    12
    0x7fff5fbff650
    0x7fff5fbff654
    0x7fff5fbff658

This shows that on my machine the total size is 12 bytes, and each member is 4 bytes apart. The ints are 4 bytes each (which can be confirmed with sizeof(int)). There is no padding.

Try this with different members in your class, for example:

class b {
    public:
        char      w;
        char      x[6];
        int       y;
        long long z;
};


问:
delete entire record which is associated with a certain child value
i want to delete the entire record in the database using the child value entered
this is the code i tried for it

```<code><body>

   User Name:
   <input type="text" name="user_name" id="user_name" placeholder="enter text"/><br><br>
   Enter Email:
  <input type="text" name="user_name" id="user_name2" placeholder="enter email" />

<br><br>

    <input type="button" value="Save" onclick="save_user();" />
    <input type="button" value="delete" onclick="delete_user();" />

<script>

  var tblUsers = document.getElementById('tbl_users_list');
  var databaseRef = firebase.database().ref('users/');
  var rowIndex = 1;
  var uid;
  var childKey;
  var childData;

  databaseRef.once('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
    childSnapshot.key;
    childSnapshot.val();

   var row = tblUsers.insertRow(rowIndex);
   var cellId = row.insertCell(0);
   var cellName = row.insertCell(1);
   cellId.appendChild(document.createTextNode(childKey));
   cellName.appendChild(document.createTextNode(childData.user_name));
   cellName.appendChild(document.createTextNode(childData.user_name2));

   rowIndex = rowIndex + 1;

    });
  });

  function save_user(){
   var user_name = document.getElementById('user_name').value;
   var user_name2 = document.getElementById('user_name2').value;

   uid = firebase.database().ref().child('users').push().key;

   var data = {
    user_id: uid,
    user_name: user_name,
    password: user_name2
   }

   var updates = {};
   updates['/users/' + uid] = data;
   firebase.database().ref().update(updates);

   alert('The user is created successfully!');
   reload_page();

   document.writeln(uid);

  }

  function update_user(){
   var user_name = document.getElementById('user_name').value;
   var user_id = document.getElementById('user_id').value;

   var data = {
    user_id: user_id,
    user_name: user_name
   }

   var updates = {};
   updates['/users/' + user_id] = data;
   firebase.database().ref().update(updates);

   alert('The user is updated successfully!');

   reload_page();
  }

  function delete_user(){
   var user_id = document.getElementById('user_id').value;

   firebase.database().ref().child('/users/' + user_id).remove();
   alert('The user is deleted successfully!');
   reload_page();
  }
</code>```

here the child value that to be refered and deleted is to be user_name2

all i want from this code is to delete the record of the child value associated with it

my database looks like

for example i want to delete the entire record which is associated with a child name password "ddd"

答:
Firebase can only write to a node if it knows the complete, exact path to that node. If you only know a property value of the node, you'll first need to execute a query to find the nodes with that value, and then write those nodes.

So in your case that'd be something like:

```<code>let password = "ddd"; // hard-coded value, but this could also be read from the HTML

let ref = firebase.database().ref("users");
let query = ref.orderByChild("password").equalTo(password);

query.once("value").then(function(results) {
  results.forEach(function(snapshot) {
    snapshot.ref.remove();
  })
})
</code>```

Body:
i want to delete the entire record in the database using the child value entered
this is the code i tried for it

   User Name:
   <input type="text" name="user_name" id="user_name" placeholder="enter text"/>

   Enter Email:
  <input type="text" name="user_name" id="user_name2" placeholder="enter email" />

    <input type="button" value="Save" onclick="save_user();" />
    <input type="button" value="delete" onclick="delete_user();" />

Body:
Firebase can only write to a node if it knows the complete, exact path to that node. If you only know a property value of the node, you'll first need to execute a query to find the nodes with that value, and then write those nodes.

So in your case that'd be something like:

let password = "ddd"; // hard-coded value, but this could also be read from the HTML

let ref = firebase.database().ref("users");
let query = ref.orderByChild("password").equalTo(password);

query.once("value").then(function(results) {
  results.forEach(function(snapshot) {
    snapshot.ref.remove();
  })
})


问:
How to move to next scene using scene manager in Unity 5?
I am doing a tutorial that is using unity 4 and they are using this:

```<code>Applicaiton.LoadLevel(Appliaction.loadedLevel +1);
</code>```

in order to move on to the next scene. I am using unity 5, and it is telling me to use scene manager since the previous method is now obsolete.

What is the new code to replace the one above?

答:
using UnityEngine;
using UnityEngine.SceneManagement ;
public class next_level : MonoBehaviour
{
    public void next_levl(){
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1 ) ;
    }
}
```

Body:
I am doing a tutorial that is using unity 4 and they are using this:

Applicaiton.LoadLevel(Appliaction.loadedLevel +1);

in order to move on to the next scene. I am using unity 5, and it is telling me to use scene manager since the previous method is now obsolete.

What is the new code to replace the one above?


问:
Iterating over a custom collection of objects with yield and foreach without boxing/unboxing
I'm trying to take advantage of iterators in C# to clean up some spatial queries on objects in a game I'm making.

Here's what I'm doing currently:

```<code>    public struct ObjectInfo
    {
        public int x, y;
        public int Type;
        public int hp;
    }

    public static IEnumerable<ObjectInfo> NearbyObjects(int x, int y, int distance)
    {
        // Not actually what I'm doing, but for simplicity...
        for (int i = 0; i < 10; ++ i)
        {
            yield return new ObjectInfo();
        }
    }

    public static void Explode()
    {
        foreach (ObjectInfo o in NearbyObjects(0, 0, 1))
        {
            o.hp = 0;
        }
    }
</code>```

This works great except I think there is some boxing/unboxing going on. The CLRProfiler seems to verify this as I'm seeing allocations happening in my Explode method. I'd very much like to avoid any allocations after startup so I'm not triggering the garbage collector in the middle of a level or something. Is there some way I can keep this syntax while avoiding any allocation? Maybe by implementing my own iterators or something?

答:
Boxing/unboxing will happen with structs.

See here: http://msdn.microsoft.com/en-us/library/aa664476(v=vs.71).aspx

Also here: Is there Boxing/Unboxing when casting a struct into a generic interface?

Body:
I'm trying to take advantage of iterators in C# to clean up some spatial queries on objects in a game I'm making.

Here's what I'm doing currently:

    public struct ObjectInfo
    {
        public int x, y;
        public int Type;
        public int hp;
    }

    public static IEnumerable<ObjectInfo> NearbyObjects(int x, int y, int distance)
    {
        // Not actually what I'm doing, but for simplicity...
        for (int i = 0; i < 10; ++ i)
        {
            yield return new ObjectInfo();
        }
    }

    public static void Explode()
    {
        foreach (ObjectInfo o in NearbyObjects(0, 0, 1))
        {
            o.hp = 0;
        }
    }

This works great except I think there is some boxing/unboxing going on. The CLRProfiler seems to verify this as I'm seeing allocations happening in my Explode method. I'd very much like to avoid any allocations after startup so I'm not triggering the garbage collector in the middle of a level or something. Is there some way I can keep this syntax while avoiding any allocation? Maybe by implementing my own iterators or something?


问:
How to display CMake variables from FooConfig.cmake file in CMake GUI?
I recently started using modern CMake principles and including Config files in my projects.

Despite that I can use one of my projects, let's say Foo, as a dependency of another one, let's say Bar, I can't see the foo project variables in tools as the CMake GUI when building the project Bar.

However, the paths are correctly found and the dependent project builds correctly. Does any one knows what I miss?

This is an example of the FooConfig.cmake.in file:

```<code># - Config file for the foo package
# It defines the following variables
#  Foo_INCLUDE_DIRS - include directories for Foo
#  Foo_LIBRARY_DIRS - library directories for Foo (normally not used!)
#  Foo_LIBRARIES    - libraries to link against

@PACKAGE_INIT@

# Tell the user project where to find our headers and libraries
set_and_check(Foo_INCLUDE_DIRS "@Foo_INSTALL_INCLUDEDIR@")
set_and_check(Foo_LIBRARY_DIRS "@Foo_INSTALL_LIBDIR@")

include_directories (${Foo_INCLUDE_DIRS})

include("${CMAKE_CURRENT_LIST_DIR}/FooTargets.cmake")

check_required_components("Foo")

set(foo_LIBRARIES Foo)

</code>```

Thanks in advance.

答:
CMake GUI shows only variables which are cached, that are defined with CACHE option. Since your FooConfig.cmake doesn't set the variable as cached, they are not appeared in the GUI.

Actually, there is a little sense to define these variables as CACHE ones: CACHE variables are intended to be modifiable by a user, and this is not your case.

Body:
I recently started using modern CMake principles and including Config files in my projects.

Despite that I can use one of my projects, let's say Foo, as a dependency of another one, let's say Bar, I can't see the foo project variables in tools as the CMake GUI when building the project Bar.

However, the paths are correctly found and the dependent project builds correctly. Does any one knows what I miss?

This is an example of the FooConfig.cmake.in file:

# - Config file for the foo package
# It defines the following variables
#  Foo_INCLUDE_DIRS - include directories for Foo
#  Foo_LIBRARY_DIRS - library directories for Foo (normally not used!)
#  Foo_LIBRARIES    - libraries to link against

@PACKAGE_INIT@

# Tell the user project where to find our headers and libraries
set_and_check(Foo_INCLUDE_DIRS "@Foo_INSTALL_INCLUDEDIR@")
set_and_check(Foo_LIBRARY_DIRS "@Foo_INSTALL_LIBDIR@")

include_directories (${Foo_INCLUDE_DIRS})

include("${CMAKE_CURRENT_LIST_DIR}/FooTargets.cmake")

check_required_components("Foo")

set(foo_LIBRARIES Foo)

Thanks in advance.


问:
matching row values (text) with column names and return value
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

```<code>region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396
</code>```

And I want to get something that looks like this:

```<code>region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA
</code>```

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

答:
Another base R option:</p>

```<code>dat[-1][sapply(names(dat[-1]), `!=`, dat$region)] <- NA

dat
   region   A  B   C  D   E   F
1       H  NA NA  NA NA  NA  NA
2       J  NA NA  NA NA  NA  NA
3       A 820 NA  NA NA  NA  NA
4       X  NA NA  NA NA  NA  NA
5       M  NA NA  NA NA  NA  NA
6       N  NA NA  NA NA  NA  NA
7       C  NA NA 952 NA  NA  NA
8       L  NA NA  NA NA  NA  NA
9       E  NA NA  NA NA 944  NA
10      F  NA NA  NA NA  NA 616
11      P  NA NA  NA NA  NA  NA
12      Q  NA NA  NA NA  NA  NA
</code>```

Body:
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396

And I want to get something that looks like this:

region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
Another base R option:

dat[-1][sapply(names(dat[-1]), `!=`, dat$region)] <- NA

dat
   region   A  B   C  D   E   F
1       H  NA NA  NA NA  NA  NA
2       J  NA NA  NA NA  NA  NA
3       A 820 NA  NA NA  NA  NA
4       X  NA NA  NA NA  NA  NA
5       M  NA NA  NA NA  NA  NA
6       N  NA NA  NA NA  NA  NA
7       C  NA NA 952 NA  NA  NA
8       L  NA NA  NA NA  NA  NA
9       E  NA NA  NA NA 944  NA
10      F  NA NA  NA NA  NA 616
11      P  NA NA  NA NA  NA  NA
12      Q  NA NA  NA NA  NA  NA


问:
Android Docx4J Error when reading in MS Word file: Didn't find class org.eclipse.persistence.oxm.NamespacePrefixMapper on path
I am trying to use the Docx4j library in order to read in the contents of Word files selected by the user (tried to follow the code in https://github.com/plutext/Docx4j4Android4) However, I receive the following error when I read in a MS Word file:

```<code>W/System.err: log4j:ERROR Could not parse url [jar:file:/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk!/log4j.xml].
    javax.xml.parsers.ParserConfigurationException: No validating DocumentBuilder implementation available
        at org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl.newDocumentBuilder(DocumentBuilderFactoryImpl.java:61)
...
Process 20716 terminated.
    Caused by: java.lang.ClassNotFoundException: Didn't find class "org.eclipse.persistence.oxm.NamespacePrefixMapper" on path: DexPathList[[zip file "/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk"]
</code>```

Below is the line of code in MainActivity.kt where I open the MS Word document and where the error occurs (I have imported the necessary utilities):

```<code>import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

import org.apache.commons.lang3.StringUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import java.io.BufferedReader
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {
    private var READ_IN_FILE:Int = 2; // Request code used when reading in a file

    // Asks a user to read in a file
    private fun chooseFile(view: View) {
        // Only the below specified mime types are allowed in the picker
        var selectFile = Intent(Intent.ACTION_GET_CONTENT)
        selectFile.type = "*/*"
        selectFile = Intent.createChooser(selectFile, "Choose a file")
        startActivityForResult(selectFile, READ_IN_FILE)
    }

    // After receiving a result for a launched activity...
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == READ_IN_FILE) { // When a result has been received, check if it is the result for READ_IN_FILE
            if (resultCode == Activity.RESULT_OK) { // heck if the operation to retrieve the Activity's result is successful
                // Attempt to retrieve the file
                try {
                    var uri = data?.data // Retrieve the file's resource locator
                    var document = WordprocessingMLPackage.load(uri?.let { contentResolver.openInputStream(it) });
                    //var documentPart: MainDocumentPart = document.getMainDocumentPart();
                    Toast.makeText(this, "DiffChecker successfully read in the file :D", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                    println("Exception: " + e.toString());
                    Toast.makeText(this, "Sorry, but there was an error reading in the file", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.file1).setOnClickListener(::chooseFile);
    }
}
</code>```

Below is my build.gradle code (app-level):

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffcheckertest"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')

    //implementation files('libs/commons-lang3-3.7.jar')
    //implementation files('libs/commons-text-1.2.jar')
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'

    implementation files('libs/docx4j-6.1.1-SNAPSHOT-shaded.jar')

}
</code>```

Build is my build.gradle code (project-level):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
File selecting using SAF (Storage Access Framework) available since Android 4.4 (API level 19):

```<code>// Asks a user to read in a file
private fun chooseFile(view: View) {
    // Only the below specified mime types are allowed in the picker
    var selectFile = Intent(Intent.ACTION_OPEN_DOCUMENT)
    selectFile.type = "*/*"
    selectFile.addCategory(Intent.CATEGORY_OPENABLE)
    selectFile = Intent.createChooser(selectFile, "Choose a file")
    startActivityForResult(selectFile, READ_IN_FILE)
}
</code>```

To prevent ClassNotFoundException for "org.eclipse.persistence.oxm.NamespacePrefixMapper"
add below line to your gradle file dependencies:

```<code>implementation 'org.eclipse.persistence:eclipselink:2.7.6'
</code>```

to prevent Duplicate class error you can exclude Duplicated classes:

```<code>implementation ('org.eclipse.persistence:eclipselink:2.7.6'){
          exclude group: 'javax.persistence.spi', module: 'ProviderUtil'
          exclude group: 'javax.persistence', module: 'Access'
}
</code>```

How to run JAXB in Android

Body:
I am trying to use the Docx4j library in order to read in the contents of Word files selected by the user (tried to follow the code in https://github.com/plutext/Docx4j4Android4) However, I receive the following error when I read in a MS Word file:

W/System.err: log4j:ERROR Could not parse url [jar:file:/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk!/log4j.xml].
    javax.xml.parsers.ParserConfigurationException: No validating DocumentBuilder implementation available
        at org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl.newDocumentBuilder(DocumentBuilderFactoryImpl.java:61)
...
Process 20716 terminated.
    Caused by: java.lang.ClassNotFoundException: Didn't find class "org.eclipse.persistence.oxm.NamespacePrefixMapper" on path: DexPathList[[zip file "/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk"]

Below is the line of code in MainActivity.kt where I open the MS Word document and where the error occurs (I have imported the necessary utilities):

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

import org.apache.commons.lang3.StringUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import java.io.BufferedReader
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {
    private var READ_IN_FILE:Int = 2; // Request code used when reading in a file

    // Asks a user to read in a file
    private fun chooseFile(view: View) {
        // Only the below specified mime types are allowed in the picker
        var selectFile = Intent(Intent.ACTION_GET_CONTENT)
        selectFile.type = "*/*"
        selectFile = Intent.createChooser(selectFile, "Choose a file")
        startActivityForResult(selectFile, READ_IN_FILE)
    }

    // After receiving a result for a launched activity...
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == READ_IN_FILE) { // When a result has been received, check if it is the result for READ_IN_FILE
            if (resultCode == Activity.RESULT_OK) { // heck if the operation to retrieve the Activity's result is successful
                // Attempt to retrieve the file
                try {
                    var uri = data?.data // Retrieve the file's resource locator
                    var document = WordprocessingMLPackage.load(uri?.let { contentResolver.openInputStream(it) });
                    //var documentPart: MainDocumentPart = document.getMainDocumentPart();
                    Toast.makeText(this, "DiffChecker successfully read in the file :D", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                    println("Exception: " + e.toString());
                    Toast.makeText(this, "Sorry, but there was an error reading in the file", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.file1).setOnClickListener(::chooseFile);
    }
}

Below is my build.gradle code (app-level):

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffcheckertest"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')

    //implementation files('libs/commons-lang3-3.7.jar')
    //implementation files('libs/commons-text-1.2.jar')
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'

    implementation files('libs/docx4j-6.1.1-SNAPSHOT-shaded.jar')

}

Build is my build.gradle code (project-level):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
File selecting using SAF (Storage Access Framework) available since Android 4.4 (API level 19):

// Asks a user to read in a file
private fun chooseFile(view: View) {
    // Only the below specified mime types are allowed in the picker
    var selectFile = Intent(Intent.ACTION_OPEN_DOCUMENT)
    selectFile.type = "*/*"
    selectFile.addCategory(Intent.CATEGORY_OPENABLE)
    selectFile = Intent.createChooser(selectFile, "Choose a file")
    startActivityForResult(selectFile, READ_IN_FILE)
}

To prevent ClassNotFoundException for "org.eclipse.persistence.oxm.NamespacePrefixMapper"
add below line to your gradle file dependencies:

implementation 'org.eclipse.persistence:eclipselink:2.7.6'

to prevent Duplicate class error you can exclude Duplicated classes:

implementation ('org.eclipse.persistence:eclipselink:2.7.6'){
          exclude group: 'javax.persistence.spi', module: 'ProviderUtil'
          exclude group: 'javax.persistence', module: 'Access'
}

How to run JAXB in Android


问:
dotnet build with version is not working in docker
I am trying to build my .net core app using Docker. And I want to override my app version during build. To display it somewhere later in runtime.

I have my Docker file looks like this:

```<code>FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /src

RUN apt-get update && \
    apt-get install -y libgit2-dev && \
    ln -s /usr/lib/x86_64-linux-gnu/libgit2.so /lib/x86_64-linux-gnu/libgit2-15e1193.so

COPY ..

WORKDIR /src/API

RUN dotnet restore

RUN dotnet tool install -g GitVersion.Tool --version=5.0.0-beta1-72

RUN export PATH="$PATH:/root/.dotnet/tools" && \
    version="$(dotnet gitversion /output json /showvariable NuGetVersion)" && \
    dotnet build --no-restore /property:Version=$version  && \
    dotnet publish --output "/app" --no-build

FROM microsoft/dotnet:2.2-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "API.dll"]
</code>```

When I tried the same commands like in RUN instructions on my Windows machine - everything is OK. I also tried to run the same commands on WSL (Ubuntu 18) and it's also fine - I have assembly version from my build command. But I can't figure out why it is not working inside Docker.

I've also tried to remove all my GitVersion magic and use just this:

```<code>FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /src

RUN apt-get update && \
    apt-get install -y libgit2-dev && \
    ln -s /usr/lib/x86_64-linux-gnu/libgit2.so /lib/x86_64-linux-gnu/libgit2-15e1193.so

COPY ..

WORKDIR /src/API

RUN dotnet restore

RUN dotnet build --no-restore /property:Version=1.1.1.0-beta1
RUN dotnet publish --output "/app" --no-build

FROM microsoft/dotnet:2.2-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "API.dll"]
</code>```

Anyway, my results are the same.

I use this code to check:

```<code>public static void Main(string[] args)
{
    Console.WriteLine(typeof(Program).Assembly.GetName());
}
</code>```

Every time my build is a success but I have version defined in .csproj file without override.

答:
Yes, it should be a trivial task but I also ran into a few issues before I finally could do it. Spent a few hours to solve the issue, hope you can save time. I recommend to read this post it helped.

My final solution was to use a Docker ARG, you must be declare it before the first FROM:

```<code>#Declare it at the beginning of the Dockerfile
ARG BUILD_VERSION=1.0.0
...
#Publish your project with "-p:Version=${BUILD_VERSION}" it works also with "dotnet build"
RUN dotnet publish "<xy.csproj>" -c Release -o /app/publish --no-restore -p:Version=${BUILD_VERSION}
</code>```

One very important thing to Note: is if you are using multistage build (multiple FROM in your file) you have to "re-declare" the ARG in that stage. See a similar question here.

Finally you can call your Docker build with:

```<code>docker build --build-arg BUILD_VERSION="1.1.1.1"
</code>```

Body:
I am trying to build my .net core app using Docker. And I want to override my app version during build. To display it somewhere later in runtime.

I have my Docker file looks like this:

FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /src

RUN apt-get update && \
    apt-get install -y libgit2-dev && \
    ln -s /usr/lib/x86_64-linux-gnu/libgit2.so /lib/x86_64-linux-gnu/libgit2-15e1193.so

COPY ..

WORKDIR /src/API

RUN dotnet restore

RUN dotnet tool install -g GitVersion.Tool --version=5.0.0-beta1-72

RUN export PATH="$PATH:/root/.dotnet/tools" && \
    version="$(dotnet gitversion /output json /showvariable NuGetVersion)" && \
    dotnet build --no-restore /property:Version=$version  && \
    dotnet publish --output "/app" --no-build

FROM microsoft/dotnet:2.2-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "API.dll"]

When I tried the same commands like in RUN instructions on my Windows machine - everything is OK. I also tried to run the same commands on WSL (Ubuntu 18) and it's also fine - I have assembly version from my build command. But I can't figure out why it is not working inside Docker.

I've also tried to remove all my GitVersion magic and use just this:

FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /src

RUN apt-get update && \
    apt-get install -y libgit2-dev && \
    ln -s /usr/lib/x86_64-linux-gnu/libgit2.so /lib/x86_64-linux-gnu/libgit2-15e1193.so

COPY ..

WORKDIR /src/API

RUN dotnet restore

RUN dotnet build --no-restore /property:Version=1.1.1.0-beta1
RUN dotnet publish --output "/app" --no-build

FROM microsoft/dotnet:2.2-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "API.dll"]

Anyway, my results are the same.

I use this code to check:

public static void Main(string[] args)
{
    Console.WriteLine(typeof(Program).Assembly.GetName());
}

Every time my build is a success but I have version defined in .csproj file without override.

Body:
Yes, it should be a trivial task but I also ran into a few issues before I finally could do it. Spent a few hours to solve the issue, hope you can save time. I recommend to read this post it helped.

My final solution was to use a Docker ARG, you must be declare it before the first FROM:

#Declare it at the beginning of the Dockerfile
ARG BUILD_VERSION=1.0.0
...
#Publish your project with "-p:Version=${BUILD_VERSION}" it works also with "dotnet build"
RUN dotnet publish "<xy.csproj>" -c Release -o /app/publish --no-restore -p:Version=${BUILD_VERSION}

One very important thing to Note: is if you are using multistage build (multiple FROM in your file) you have to "re-declare" the ARG in that stage. See a similar question here.

Finally you can call your Docker build with:

docker build --build-arg BUILD_VERSION="1.1.1.1"


问:
Touch move gesture logic...how to determine direction of movement in 2d?
How can i determine the direction of gesture ? The use case is shown in the image link. what is the right logic for detecting in which direction the person is trying to move the ball in the circular path ? I have called the direction method in move gesture...Can someone help me fine tune this ... ?

http://www.shrenikvikam.com/wp-content/uploads/2011/04/214e422a43E11S3.png-150x134.png

```<code>     private String getDirection(float firstTouchX, float finalTouchX){
        if((firstTouchX - finalTouchX)>0)
            return "Left";
        else
            return "Right";
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();

        switch (action) {
            // MotionEvent class constant signifying a finger-down event
            case MotionEvent.ACTION_DOWN: {
                Log.d("ACTION DOWN","Value ->");
                final float x = event.getX();
                final float y = event.getY();
                initialTouchX = x;
                initialTouchY = y;
                break;

            }
            // MotionEvent class constant signifying a finger-drag event
            case MotionEvent.ACTION_MOVE: {
                final float x = event.getX();
                final float y = event.getY();
                final String direction = getDirection(initialTouchX,x);
                Log.d("ACTION MOVE","diff in initial and cur value of x  ->" + direction + (initialTouchX - x) + initialTouchX + "y->" + initialTouchY);

                break;

            }
            // MotionEvent class constant signifying a finger-up event
            case MotionEvent.ACTION_UP: {
                Log.d("ACTION UP","Value ->");

                break;
            }
        }
        return true;
    }</code>```

答:
It seems like the slope of the line formed by the two touch points should be equal to the tangent of the circle at that point. This link has most of the math to pursue such a solution

I have used the difference between angles to the center point of the circle with good success. That may be the way to go as well.

Body:
How can i determine the direction of gesture ? The use case is shown in the image link. what is the right logic for detecting in which direction the person is trying to move the ball in the circular path ? I have called the direction method in move gesture...Can someone help me fine tune this ... ?

http://www.shrenikvikam.com/wp-content/uploads/2011/04/214e422a43E11S3.png-150x134.png

     private String getDirection(float firstTouchX, float finalTouchX){
        if((firstTouchX - finalTouchX)>0)
            return "Left";
        else
            return "Right";
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();

        switch (action) {
            // MotionEvent class constant signifying a finger-down event
            case MotionEvent.ACTION_DOWN: {
                Log.d("ACTION DOWN","Value ->");
                final float x = event.getX();
                final float y = event.getY();
                initialTouchX = x;
                initialTouchY = y;
                break;

            }
            // MotionEvent class constant signifying a finger-drag event
            case MotionEvent.ACTION_MOVE: {
                final float x = event.getX();
                final float y = event.getY();
                final String direction = getDirection(initialTouchX,x);
                Log.d("ACTION MOVE","diff in initial and cur value of x  ->" + direction + (initialTouchX - x) + initialTouchX + "y->" + initialTouchY);

                break;

            }
            // MotionEvent class constant signifying a finger-up event
            case MotionEvent.ACTION_UP: {
                Log.d("ACTION UP","Value ->");

                break;
            }
        }
        return true;
    }


问:
How to detect that Indirect GLX is needed but disabled?
For a few years now, indirect GLX (IGLX) has been disabled by default in xorg and other X Servers.  I'm writing an application that will use OpenGL if available, but can fall back to other graphics if it is not.  Is there a standard way to detect that it is going to fail, other than trying it and responding to the errors?

My current test (written about 20 years ago) just checks if XOpenDisplay and glXQueryExtension work, but that's not sufficient:  things fail later when calling glXCreateContext and other functions.

I'd prefer not to try to open a window and check for success, because at the time I want to do the test I don't know if the user is going to need one.  My preference is to do an invisible test at startup so I can warn the user that they're going to be using the backup graphics methods.

答:
Creating a OpenGL context with GLX doesn't require a window. Neiter glxCreateContext nor glxCreateNewContext take a drawable paramter. And even if they did, you can create a window without ever mapping it, i.e. make it visible, or even trigger some action from the window manager.

In X11 creating windows is a rather cheap operation, especially if the initial size of the window is 0×0 and the window is never mapped. You can still perform the whole range of X11 and GLX operations.

The upshot of all of this is, that to test if the OpenGL capabilities are available, the usual approach is to actually attempt to create an window and OpenGL context with the desired attributes and see, if this succeeds.

Since the X11 resources used for probing don't have to be mapped, this will not create any visible output; and apart from constantly polling the X server for the window tree, not even a window manager will take notice (since this depends on mapping the window).

Of course to keep thins cheap and fast, such tests should be programmed directly against X11 / Xlib, without any toolkits inbetween (since GLX is written against Xlib, even if Xcb is used, you'll have to use Xlib, for at least that part, but you'd have to do that anyway).


问:
jquery-file-upload Uploaded bytes exceed file size
I'm using jquery-file-upload plugin to upload some files.
I have a bind to the add callback where I collect the files to upload and on form submit i'm issuing the 'send' command to begin the upload.

The problem i'm facing is that the fail callback is called upon successful upload with the following error message:
"Uploaded bytes exceed file size"

can anyone explain me what does this error mean? and why I keep getting it?

I appreciate the help.

10x

答: Make sure your form only has inputs that are what AWS expects. Do not add extra form fields of your own. Or if you do, remove them with JS before the AWS upload begins.</p>


答:
Your code does not do any boxing.

Boxing only happens when you put a struct into an object field.

Since your code is fully strongly-typed and doesn't have any object fields, it doesn't box.

Calling an iterator method will create a new iterator object (which implements both IEnumerable<T> and IEnumerator<T>), but should not result in any other (behind-the-scenes) allocations.

Title: Iterating over a custom collection of objects with yield and foreach without boxing/unboxing


问:
Eloquent hasMany relation without id
I to count how many registration exist from the same nation.
So far, I came um with the following solution:
Method inside the Controller:

class Camp extends Model // ...
{
    protected $with = ['registrations_nation_count',...];
    // ...

    public function registrations_nation_count()
    {
        return $this->hasMany(CampRegistration::class)
            ->select(['camp_id','nation',DB::raw('COUNT(*) as count')])
            ->groupBy('nation');
    }
}

```

<p>This generates the following output:</p>

```      "registrations_nation_count": [
            {
                "camp_id": 1,
                "nation": "en",
                "count": 2
            },
            {
                "camp_id": 1,
                "nation": "fr",
                "count": 1
            }
        ]
```

<p>Now I would like to remove the camp_id column from the output. I already tried to simply remove it from the select but this leads to no output at all.
Is there any way to hide it?</p>

<p>Database:</p>

```
+-------+--------------------+
| camps | camp_registrations |
+-------+--------------------+
| id    | id                 |
| ...   | camp_id            |
|       | nation             |
|       | ...                |
+-------+--------------------+
```

答:
You probably want to do something like :

$camp->registrations_nation_count->makeHidden('camp_id');
```

After using 'with'

Title: Eloquent hasMany relation without id

Body:
I to count how many registration exist from the same nation.
So far, I came um with the following solution:
Method inside the Controller:

class Camp extends Model // ...
{
    protected $with = ['registrations_nation_count',...];
    // ...

    public function registrations_nation_count()
    {
        return $this->hasMany(CampRegistration::class)
            ->select(['camp_id','nation',DB::raw('COUNT(*) as count')])
            ->groupBy('nation');
    }
}

This generates the following output:

      "registrations_nation_count": [
            {
                "camp_id": 1,
                "nation": "en",
                "count": 2
            },
            {
                "camp_id": 1,
                "nation": "fr",
                "count": 1
            }
        ]

Now I would like to remove the camp_id column from the output. I already tried to simply remove it from the select but this leads to no output at all.
Is there any way to hide it?

Database:

+-------+--------------------+
| camps | camp_registrations |
+-------+--------------------+
| id    | id                 |
| ...   | camp_id            |
|       | nation             |
|       | ...                |
+-------+--------------------+

Body:
You probably want to do something like :

$camp->registrations_nation_count->makeHidden('camp_id');

After using 'with'


问:
user defined function returns error in python

    import pandas as pd
    d = {'a': [1,2,3],
         'b': [3,4,5],
         'c': [5,4,3]}
    df=pd.DataFrame(d)
    df
```

<p>returns:</p>

```        a   b   c
    0   1   3   5
    1   2   4   4
    2   3   5   3
```

<p>I create the following function to calculate m:</p>

<pre class="lang-py prettyprint-override"><code>    def foo(x,y,z):
        m=x(y+z)
        return m
</code>```

Then apply it to df:

    df['new']=df[['a', 'b', 'c']].apply(lambda x,y,z: foo(x,y,z))
```

<p>but this gives following error:</p>

<pre class="lang-py prettyprint-override"><code>    ("<lambda>() missing 2 required positional arguments: 'y' and 'z'", 'occurred at index a')
</code>```

How can i solve it?

答:
You have 2 problems, 1 is a syntax error where you seem to forget the * operator:

m=x(y+z)
```

<p>should be:</p>

<pre class="lang-py prettyprint-override"><code>m=x*(y+z)
</code>```

The more important one is about how you are distributing the arguments into the foo function via lambda. You can fix it with this solution:

```<code>df['new']=df.apply(lambda x: foo(x['a'],x['b'],x['c']),axis=1)
</code>```

see also Applying function with multiple arguments to create a new pandas column

Body:
    import pandas as pd
    d = {'a': [1,2,3],
         'b': [3,4,5],
         'c': [5,4,3]}
    df=pd.DataFrame(d)
    df

returns:

        a   b   c
    0   1   3   5
    1   2   4   4
    2   3   5   3

I create the following function to calculate m:

    def foo(x,y,z):
        m=x(y+z)
        return m

Then apply it to df:

    df['new']=df[['a', 'b', 'c']].apply(lambda x,y,z: foo(x,y,z))

but this gives following error:

    ("<lambda>() missing 2 required positional arguments: 'y' and 'z'", 'occurred at index a')

How can i solve it?

Body:
You have 2 problems, 1 is a syntax error where you seem to forget the * operator:

m=x(y+z)

should be:

m=x*(y+z)

The more important one is about how you are distributing the arguments into the foo function via lambda. You can fix it with this solution:

df['new']=df.apply(lambda x: foo(x['a'],x['b'],x['c']),axis=1)

see also Applying function with multiple arguments to create a new pandas column


问:
Numpy 2d array: account for border elements when modifying neighbouring elements
I'm using CodeSignal exercises to learn programming, so here it goes.
I have a 2d numpy array (called matrix) (doesn't have to be numpy though, if any better structure exists for this purpose), and 2 for loops which loop through each element in the matrix, checking if it meets some condition.
I have created a np.zeros array of the same size as the input matrix (called result), which will be populated with my result.

Back to the for loops. When the condition is met for a given element with indices i,j of matrix, I want the programme to identify all the neighbouring elements and add a 1 to each of them.

So for example if

```<code>matrix = [[True, False, False],
         [False, False, False],
         [False, False, False]]
</code>```

Then

```<code>result = [[0, 1, 0],
          [1, 1, 0],
          [0, 0, 0]]
</code>```

What I have now:

```<code>matrix = np.array(matrix)
(row, col) = matrix.shape
result = np.zeros((row,col), dtype=int)

for i in range(0, row):
    for j in range(0, col):
        print(i,j)
        if matrix[i,j] == True:
             matrix[i-1:i+2, j-1:j+2] += 1      ##problem
return result

</code>```

The problem with the line I have indicated is of course it does not work if the element is at a border, since there is no i-1 or i+2 etc.. (I tried, no error message, it just does not perform any function on the zeros matrix).
I could write a bunch of if-statements like if i == 0 or j == 0 or i == row or j == col and specify separate slicing for each, but there must be a way easier method than that, which I can not think of or find.

Thanks in advance for the help.

答:
What you want to do is to convolve your matrix using kernel [[1,1,1],[1,1,1],[1,1,1]] and then replace initial cellswith zeros. Usual way is to use scipy for that like so:

```<code>>>> matrix = np.array([[True, False, False],
                  [False, False, False],
                  [False, False, False]])
>>> M = scipy.signal.convolve2d(matrix,
           np.array([[1,1,1],[1,1,1],[1,1,1]]),
           mode='same')
>>> M
array([[1, 1, 0],
   [1, 1, 0],
   [0, 0, 0]])
</code>```

However numpy allows to perform 1D convolution only. But since our kernel is very symmetric, I have found a little hacky way how to achieve the same result as with 2D convolution:

```<code>M = np.vstack([np.convolve(n, [1, 1, 1], 'same') for n in matrix])
M = np.column_stack([np.convolve(n, [1, 1, 1], 'same') for n in matrix.T])
</code>```

If you want to assign initial cells to zeroes, it's possible to do it like so:

```<code>np.logical_xor(M, matrix)
</code>```

Body:
I'm using CodeSignal exercises to learn programming, so here it goes.
I have a 2d numpy array (called matrix) (doesn't have to be numpy though, if any better structure exists for this purpose), and 2 for loops which loop through each element in the matrix, checking if it meets some condition.
I have created a np.zeros array of the same size as the input matrix (called result), which will be populated with my result.

Back to the for loops. When the condition is met for a given element with indices i,j of matrix, I want the programme to identify all the neighbouring elements and add a 1 to each of them.

So for example if

matrix = [[True, False, False],
         [False, False, False],
         [False, False, False]]

Then

result = [[0, 1, 0],
          [1, 1, 0],
          [0, 0, 0]]

What I have now:

matrix = np.array(matrix)
(row, col) = matrix.shape
result = np.zeros((row,col), dtype=int)

for i in range(0, row):
    for j in range(0, col):
        print(i,j)
        if matrix[i,j] == True:
             matrix[i-1:i+2, j-1:j+2] += 1      ##problem
return result

The problem with the line I have indicated is of course it does not work if the element is at a border, since there is no i-1 or i+2 etc.. (I tried, no error message, it just does not perform any function on the zeros matrix).
I could write a bunch of if-statements like if i == 0 or j == 0 or i == row or j == col and specify separate slicing for each, but there must be a way easier method than that, which I can not think of or find.

Thanks in advance for the help.

Body:
What you want to do is to convolve your matrix using kernel [[1,1,1],[1,1,1],[1,1,1]] and then replace initial cellswith zeros. Usual way is to use scipy for that like so:

>>> matrix = np.array([[True, False, False],
                  [False, False, False],
                  [False, False, False]])
>>> M = scipy.signal.convolve2d(matrix,
           np.array([[1,1,1],[1,1,1],[1,1,1]]),
           mode='same')
>>> M
array([[1, 1, 0],
   [1, 1, 0],
   [0, 0, 0]])

However numpy allows to perform 1D convolution only. But since our kernel is very symmetric, I have found a little hacky way how to achieve the same result as with 2D convolution:

M = np.vstack([np.convolve(n, [1, 1, 1], 'same') for n in matrix])
M = np.column_stack([np.convolve(n, [1, 1, 1], 'same') for n in matrix.T])

If you want to assign initial cells to zeroes, it's possible to do it like so:

np.logical_xor(M, matrix)


问:
shopify toggle modal on button press
Im a decently experienced developer but this is my first time working with Shopify.

I need to toggle a modal on button press. What is the right way to do this in shopify?

I can easily do this with some javascript but it wouldn't be in the "shopify" way.(Unless it is becaue I have no clue)

I assume it has to do with a variable

```<code>{% assign showModal = false %}
</code>```

and then on button click, we reassign the variable to true(?)

```<code>{% if showModal %}
  {% section 'modal' %}
{% endif %}
</code>```

Appreciate the help!

答:
Shopify is using the liquid language for outputing data.

The main purpose of liquid is to output some kind of content on the page but the most important part is that it loads BEFORE the DOM loads. This means that you should treat it as a back-end language.

Or to say it simply you can't make front-end interactions lick click/hover/etc.. events and expect to modify the liquid variables.

The liquid code is executed before the DOM loads, so since Javasript fires after the DOM there is no way for the two languages to interact.

Long story short you use only simple JavaScript for front-end interactions.

Title: shopify toggle modal on button press

Body:
Im a decently experienced developer but this is my first time working with Shopify.

I need to toggle a modal on button press. What is the right way to do this in shopify?

I can easily do this with some javascript but it wouldn't be in the "shopify" way.(Unless it is becaue I have no clue)

I assume it has to do with a variable

{% assign showModal = false %}

and then on button click, we reassign the variable to true(?)

{% if showModal %}
  {% section 'modal' %}
{% endif %}

Appreciate the help!


问:
Cardview loses its radius when taken a screenshot programmatically
I have constraintlayout within cardview. The cardview looks fine on the screen. It is only when taken a screenshot,it is rendered to a bitmap thats when it loses the corners. I have added the picture of the bitmap view. The constraintlayout overlaps the rounded corners. I need edge to edge roundness.

Below is the screenshot of the emulator showing round corners correctly:

Here is the view rendered to a bitmap:

Below is my sample code.

```<code>public class MainActivity extends AppCompatActivity {

    private CardView cardView;
    private Button button;
    private ConstraintLayout parentLayoutA;
    private ConstraintLayout layoutB;
    private ConstraintLayout childLayout;
    private ConstraintSet innerSet;
    private ConstraintSet outerSet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CreateCardViewProgrammatically();
    }

    public void CreateCardViewProgrammatically(){

        cardView = new CardView(this);
        childLayout = new ConstraintLayout(this);
        parentLayoutA = new ConstraintLayout(this);
        layoutB = new ConstraintLayout(this);
        button = new Button(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            layoutB.setClipToOutline(true);
        }

        cardView.setRadius(150);

        button.setText("Click!!");
        button.setTextColor(Color.BLACK);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               takeScreenShot();
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            parentLayoutA.setId(View.generateViewId());
            layoutB.setId(View.generateViewId());
            childLayout.setId(View.generateViewId());
            cardView.setId(View.generateViewId());
            button.setId(View.generateViewId());
        }

        innerSet = new ConstraintSet();
        outerSet = new ConstraintSet();

        ConstraintLayout.LayoutParams parentParams = new ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.MATCH_PARENT
        );

        layoutB.setLayoutParams(parentParams);
        childLayout.setLayoutParams(parentParams);
        cardView.setCardElevation(0);
        cardView.setPadding(50,50,50,50);

        parentLayoutA.addView(layoutB);
        layoutB.addView(cardView);
        cardView.addView(childLayout);
        childLayout.addView(button);

        innerSet.centerHorizontally(button.getId(), ConstraintSet.PARENT_ID);
        innerSet.centerVertically(button.getId(), ConstraintSet.PARENT_ID);
        innerSet.constrainHeight(button.getId(), 200);

        outerSet.connect(cardView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 200);
        outerSet.connect(cardView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 200);
        outerSet.centerHorizontally(cardView.getId(), ConstraintSet.PARENT_ID);
        outerSet.centerVertically(cardView.getId(), ConstraintSet.PARENT_ID);
        outerSet.constrainHeight(cardView.getId(), 1500);

        innerSet.applyTo(childLayout);
        outerSet.applyTo(layoutB);

        setContentView(parentLayoutA);

        parentLayoutA.setBackgroundColor(Color.YELLOW);
        layoutB.setBackgroundColor(Color.MAGENTA);
        cardView.setCardBackgroundColor(Color.GREEN);
        childLayout.setBackgroundColor(Color.BLUE);
    }

    public void takeScreenShot() {
        imageFromView(parentLayoutA);
    }

    public Bitmap imageFromView(View view) {

        DisplayMetrics metrics = this.getApplication().getResources().getDisplayMetrics();
        int width = view.getWidth() > 0 ? view.getWidth() : metrics.widthPixels;
        int height = view.getHeight() > 0 ? view.getHeight() : metrics.heightPixels;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

</code>```

答:
From looking at your code, I am not clear on what you are trying to accomplish. However, if you change the following line

```<code>cardView.setCardBackgroundColor(Color.GREEN);
</code>```

to

```<code>cardView.setCardBackgroundColor(Color.BLUE);
</code>```

and delete the line

```<code>childLayout.setBackgroundColor(Color.BLUE);
</code>```

you will see your screen image captured the way I think you want.

The underlying problem is that the rounded corner clipping is dependent upon the hardware layer which is enabled for the canvas generated by the view display system but is turned off when you generate your own bitmap and canvas. You can check this with Canvas#isHardwareAccelerated(),

Take a look at Taking Screenshot Programmatically Using PixelCopy Api for an approach that you might be able to take. Also, see PixelCopy.

Here is a small project on GitHub demonstrating how to go about capturing a layout. This demo app simply uses the code in the question to display a layout, captures the layout and redisplays it in an ImageView. A TextView in the redisplay simply displays "Captured!"

Body:
I have constraintlayout within cardview. The cardview looks fine on the screen. It is only when taken a screenshot,it is rendered to a bitmap thats when it loses the corners. I have added the picture of the bitmap view. The constraintlayout overlaps the rounded corners. I need edge to edge roundness.

Below is the screenshot of the emulator showing round corners correctly:

Here is the view rendered to a bitmap:

Below is my sample code.

public class MainActivity extends AppCompatActivity {

    private CardView cardView;
    private Button button;
    private ConstraintLayout parentLayoutA;
    private ConstraintLayout layoutB;
    private ConstraintLayout childLayout;
    private ConstraintSet innerSet;
    private ConstraintSet outerSet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CreateCardViewProgrammatically();
    }

    public void CreateCardViewProgrammatically(){

        cardView = new CardView(this);
        childLayout = new ConstraintLayout(this);
        parentLayoutA = new ConstraintLayout(this);
        layoutB = new ConstraintLayout(this);
        button = new Button(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            layoutB.setClipToOutline(true);
        }

        cardView.setRadius(150);

        button.setText("Click!!");
        button.setTextColor(Color.BLACK);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               takeScreenShot();
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            parentLayoutA.setId(View.generateViewId());
            layoutB.setId(View.generateViewId());
            childLayout.setId(View.generateViewId());
            cardView.setId(View.generateViewId());
            button.setId(View.generateViewId());
        }

        innerSet = new ConstraintSet();
        outerSet = new ConstraintSet();

        ConstraintLayout.LayoutParams parentParams = new ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.MATCH_PARENT
        );

        layoutB.setLayoutParams(parentParams);
        childLayout.setLayoutParams(parentParams);
        cardView.setCardElevation(0);
        cardView.setPadding(50,50,50,50);

        parentLayoutA.addView(layoutB);
        layoutB.addView(cardView);
        cardView.addView(childLayout);
        childLayout.addView(button);

        innerSet.centerHorizontally(button.getId(), ConstraintSet.PARENT_ID);
        innerSet.centerVertically(button.getId(), ConstraintSet.PARENT_ID);
        innerSet.constrainHeight(button.getId(), 200);

        outerSet.connect(cardView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 200);
        outerSet.connect(cardView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 200);
        outerSet.centerHorizontally(cardView.getId(), ConstraintSet.PARENT_ID);
        outerSet.centerVertically(cardView.getId(), ConstraintSet.PARENT_ID);
        outerSet.constrainHeight(cardView.getId(), 1500);

        innerSet.applyTo(childLayout);
        outerSet.applyTo(layoutB);

        setContentView(parentLayoutA);

        parentLayoutA.setBackgroundColor(Color.YELLOW);
        layoutB.setBackgroundColor(Color.MAGENTA);
        cardView.setCardBackgroundColor(Color.GREEN);
        childLayout.setBackgroundColor(Color.BLUE);
    }

    public void takeScreenShot() {
        imageFromView(parentLayoutA);
    }

    public Bitmap imageFromView(View view) {

        DisplayMetrics metrics = this.getApplication().getResources().getDisplayMetrics();
        int width = view.getWidth() > 0 ? view.getWidth() : metrics.widthPixels;
        int height = view.getHeight() > 0 ? view.getHeight() : metrics.heightPixels;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

Body:
From looking at your code, I am not clear on what you are trying to accomplish. However, if you change the following line

cardView.setCardBackgroundColor(Color.GREEN);

to

cardView.setCardBackgroundColor(Color.BLUE);

and delete the line

childLayout.setBackgroundColor(Color.BLUE);

you will see your screen image captured the way I think you want.

The underlying problem is that the rounded corner clipping is dependent upon the hardware layer which is enabled for the canvas generated by the view display system but is turned off when you generate your own bitmap and canvas. You can check this with Canvas#isHardwareAccelerated(),

Take a look at Taking Screenshot Programmatically Using PixelCopy Api for an approach that you might be able to take. Also, see PixelCopy.

Here is a small project on GitHub demonstrating how to go about capturing a layout. This demo app simply uses the code in the question to display a layout, captures the layout and redisplays it in an ImageView. A TextView in the redisplay simply displays "Captured!"


问:
How can I convert an array into an Android resource?
I'm new to Android programming, so please let me know if I'm doing anything stupid. However, I currently have an array String[] gamesList that is dynamically generated from a database.

I want to use each element of an array in a Spinner, but the Adapter has a method signature of (Context, int, int). The first and third inputs I can do, but the second is asking for the id of a resource; but I don't have a R.array.someRandomName resource, I only have a local array.

Is there some way to make the array a resource, or if not, how do I do this?

答:
Making the array into a resource is an unnecessary and unconventional step. Instead, you should look at this previous question:
Android - configure Spinner to use array</p>


问:
SSR API cookies set/delete
I can pass cookies on ssr in getInitialProps using

```<code>req?.headers?.cookie
</code>```

I can read them in api route, also i can set them if request was not ssr using

res.setHeader('Set-Cookie', ...)

But how to set/delete them if request was from getInitialProps (SSR) in API resolver?

```<code>// Api handler
const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  console.log(req.headers.cookie) // works on ssr/client

  res.setHeader('Set-Cookie', ['testSSR2=2; path=/; expires=Thu, 01 Jan 2021 00:00:01 GMT;']) // works on client request only

  res.json({ data: 'test' })
}
</code>```

答:
Ok, this seems to work:

If fetch request was made by server, than we clone (with some parsing) 'Set-Cookie' header to res header.

```<code>import fetch from 'isomorphic-unfetch'
import { IncomingMessage, ServerResponse } from 'http'

const payload = (body: any, cookies?: any): object => {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    cookie: cookies || ''
  }

  return {
    method: 'POST',
    headers,
    credentials: 'same-origin',
    body: JSON.stringify(body)
  }
}

type ApiRes<ExpectedData> = Partial<{ data: ExpectedData }>
type AnyObj = { [key: string]: any }

const fetchAPI = <Body = AnyObj, ExpectedData = AnyObj>(
  apiAction: string,
  body: Body,
  req?: IncomingMessage,
  res?: ServerResponse
): Promise<ApiRes<ExpectedData>> => {
  return new Promise((resolve) => {
    fetch(`mysite/api/some`, payload(body, req?.headers?.cookie))
      .then((raw) => {
        if (req && res) {
          const setCookies = raw.headers.get('Set-Cookie')

          if (setCookies !== null) {
            res.setHeader('Set-Cookie', setCookies.split(';, '))
          }
        }

        return raw.json()
      })
      .then((parsed: ApiRes<ExpectedData>) => resolve(parsed))
      .catch((err) => {
        console.log(err)
      })
  })
}
</code>```

Title: SSR API cookies set/delete

Body:
I can pass cookies on ssr in getInitialProps using

req?.headers?.cookie

I can read them in api route, also i can set them if request was not ssr using

res.setHeader('Set-Cookie', ...)

But how to set/delete them if request was from getInitialProps (SSR) in API resolver?

// Api handler
const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  console.log(req.headers.cookie) // works on ssr/client

  res.setHeader('Set-Cookie', ['testSSR2=2; path=/; expires=Thu, 01 Jan 2021 00:00:01 GMT;']) // works on client request only

  res.json({ data: 'test' })
}

Body:
Ok, this seems to work:

If fetch request was made by server, than we clone (with some parsing) 'Set-Cookie' header to res header.

import fetch from 'isomorphic-unfetch'
import { IncomingMessage, ServerResponse } from 'http'

const payload = (body: any, cookies?: any): object => {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    cookie: cookies || ''
  }

  return {
    method: 'POST',
    headers,
    credentials: 'same-origin',
    body: JSON.stringify(body)
  }
}

type ApiRes<ExpectedData> = Partial<{ data: ExpectedData }>
type AnyObj = { [key: string]: any }

const fetchAPI = <Body = AnyObj, ExpectedData = AnyObj>(
  apiAction: string,
  body: Body,
  req?: IncomingMessage,
  res?: ServerResponse
): Promise<ApiRes<ExpectedData>> => {
  return new Promise((resolve) => {
    fetch(`mysite/api/some`, payload(body, req?.headers?.cookie))
      .then((raw) => {
        if (req && res) {
          const setCookies = raw.headers.get('Set-Cookie')

          if (setCookies !== null) {
            res.setHeader('Set-Cookie', setCookies.split(';, '))
          }
        }

        return raw.json()
      })
      .then((parsed: ApiRes<ExpectedData>) => resolve(parsed))
      .catch((err) => {
        console.log(err)
      })
  })
}


问:
How to download a file from FileField django
I am building an application that should allow users to upload and download files using Django.

I have a model that stores files:

```<code>class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    unit_code = models.CharField(max_length=6)
    input = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    @property
    def filename(self):
        return os.path.basename(self.document.name)
</code>```

I am able to display the list of uploaded files in my template from my view as such:

```<code>def Document(request, str):
    documents = Document.objects.filter(unit_code=str)
</code>```

And in the template an anchor tag to download the file using the url as seen here:

```<code>{% for document in documents %}
    {{document.filename}}<a  href="{{document.input.url}}"> Download Document </a>
{% endfor %}
</code>```

Right now I'm getting an error page not found (The url is directing to 127.0.0.1:8000/media/documents/file_name

Is it possible to download the file using the anchor tag with the Django development server?

答:
Assuming you have your MEDIA_ROOT and MEDIA_URL settings properly set, you need to add something like this to your urls.py

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

You can read the docs here.

Important: this solution is only good during development. For production your media files should be served directly from nginx (or whatever web server you are using) not through Django

Body:
I am building an application that should allow users to upload and download files using Django.

I have a model that stores files:

class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    unit_code = models.CharField(max_length=6)
    input = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    @property
    def filename(self):
        return os.path.basename(self.document.name)

I am able to display the list of uploaded files in my template from my view as such:

def Document(request, str):
    documents = Document.objects.filter(unit_code=str)

And in the template an anchor tag to download the file using the url as seen here:

{% for document in documents %}
    {{document.filename}} Download Document
{% endfor %}

Right now I'm getting an error page not found (The url is directing to 127.0.0.1:8000/media/documents/file_name

Is it possible to download the file using the anchor tag with the Django development server?

Body:
Assuming you have your MEDIA_ROOT and MEDIA_URL settings properly set, you need to add something like this to your urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

You can read the docs here.

Important: this solution is only good during development. For production your media files should be served directly from nginx (or whatever web server you are using) not through Django