qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | `preg_replace()` will not do much in terms of security. You should familiarize yourself with some basic security/crypto before doing this work. Also, consider the use of a standard cryptographic library for encrypting/decrypting data instead of arbitrarily using hash or regex functions.
Take a look at this: <http://php.net/manual/en/book.openssl.php> | First: good for you for giving attention to security issues. It's a big subject and one that many people overlook until it's too late. So, kudos to you for seeking more understanding about best practices. :-)
[OWASP](http://owasp.org) is a good resource for understanding web security issues.
Another good resource is the SANS report [The Top Cyber Security Risks](http://www.sans.org/top-cyber-security-risks/).
Specifically, [Cross-Site Scripting (XSS)](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet) and [SQL Injection](https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet) are the top two security risks for most websites. You should read about how to design your code to minimize these risks.
I have also designed a presentation [SQL Injection Myths and Fallacies](http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies) that goes deeper into the nature of this issue and methods of defense.
Read the blog [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html) by StackOverflow founder Jeff Atwood.
I also cover SQL injection and password hashing in my book [SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming](https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/). |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | First: good for you for giving attention to security issues. It's a big subject and one that many people overlook until it's too late. So, kudos to you for seeking more understanding about best practices. :-)
[OWASP](http://owasp.org) is a good resource for understanding web security issues.
Another good resource is the SANS report [The Top Cyber Security Risks](http://www.sans.org/top-cyber-security-risks/).
Specifically, [Cross-Site Scripting (XSS)](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet) and [SQL Injection](https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet) are the top two security risks for most websites. You should read about how to design your code to minimize these risks.
I have also designed a presentation [SQL Injection Myths and Fallacies](http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies) that goes deeper into the nature of this issue and methods of defense.
Read the blog [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html) by StackOverflow founder Jeff Atwood.
I also cover SQL injection and password hashing in my book [SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming](https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/). | I am an experienced PHP developer and I want suggest to you to take a look to this project [OWASP\_Development\_Guide](https://www.owasp.org/index.php/Projects/OWASP_Development_Guide). Every web developer should be use it as a bible. It has been very useful for me and I hope it will be the same for you.
Here a brief description of the document:
>
> The Development Guide provides practical guidance and includes J2EE, ASP.NET, and PHP code samples. The Development Guide covers an extensive array of application-level security issues, from SQL injection through modern concerns such as phishing, credit card handling, session fixation, cross-site request forgeries, compliance, and privacy issues.
>
>
> |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | `preg_replace()` will not do much in terms of security. You should familiarize yourself with some basic security/crypto before doing this work. Also, consider the use of a standard cryptographic library for encrypting/decrypting data instead of arbitrarily using hash or regex functions.
Take a look at this: <http://php.net/manual/en/book.openssl.php> | I am an experienced PHP developer and I want suggest to you to take a look to this project [OWASP\_Development\_Guide](https://www.owasp.org/index.php/Projects/OWASP_Development_Guide). Every web developer should be use it as a bible. It has been very useful for me and I hope it will be the same for you.
Here a brief description of the document:
>
> The Development Guide provides practical guidance and includes J2EE, ASP.NET, and PHP code samples. The Development Guide covers an extensive array of application-level security issues, from SQL injection through modern concerns such as phishing, credit card handling, session fixation, cross-site request forgeries, compliance, and privacy issues.
>
>
> |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | First: good for you for giving attention to security issues. It's a big subject and one that many people overlook until it's too late. So, kudos to you for seeking more understanding about best practices. :-)
[OWASP](http://owasp.org) is a good resource for understanding web security issues.
Another good resource is the SANS report [The Top Cyber Security Risks](http://www.sans.org/top-cyber-security-risks/).
Specifically, [Cross-Site Scripting (XSS)](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet) and [SQL Injection](https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet) are the top two security risks for most websites. You should read about how to design your code to minimize these risks.
I have also designed a presentation [SQL Injection Myths and Fallacies](http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies) that goes deeper into the nature of this issue and methods of defense.
Read the blog [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html) by StackOverflow founder Jeff Atwood.
I also cover SQL injection and password hashing in my book [SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming](https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/). | As others have pointed out, md5 is broken. Also, a SHA1 hash is very fast to compute which actually makes it **worse** as a hashing algo. Instead look at bcrypt. Assuming you're using PHP, the <http://www.openwall.com/phpass/> is very a nice password to use that handles hashing and salting for you transparently.
Using preg\_replace() for escaping data to the database is a **very bad idea**. Almost all databases include their own sanitization functions, PHP/MySQL is no exception with mysql\_real\_escape\_string().
Some more points (please note none of these are set in stone):
**Sanitize all input**
Assume that everything the user sends to your server is designed to cause harm. This includes form submissions, but also URL routes, cookie values, server vars, EVERYTHING. Using a framework will often provide some insulation from this, automatically escaping a lot of data for you.
**Escape all output**
Assume that everything you display on your site is designed to cause harm. **XSS** and **CSRF** are amongst the most common techniques for attacking websites. Escape all text that you output to the browser. Look into using nonces to mitigate attacks.
**Use TLS/SSL**
If you want to protect your users data enroute, get yourself a signed SSL certificate and set it up. This allows visitors to go to <https://yoursite.com> securely (or at least more securely if they're the kind of person who does internet banking on coffee shop wifi).
**Use a framework**
Everyone begins by writing their own framework because they know how to do it right, or don't need the extra complexity or whatever reason they come up with. Unless you're writing a super-specific-niche-application for which PHP probably isn't the right answer anyway, **use a framework**. I prefer <http://kohanaframework.org/>, but there's a whole range out there from <http://codeigniter.com/> through to <http://framework.zend.com/>. Frameworks handle session encryption, database escaping, input sanitization and more for you, and because they're used by many people the chance of a bug is much less than code that only one person has worked on.
**Secure your infrastructure**
This one tends to fly by most people, but make sure you take some time to look at the server(s) you're running on. Are you on a shared account? You don't want to be storing financial information on them then (in some countries it's even illegal too). Apply security patches for your OS/software, make sure you haven't left an old upload script lying around, check your file permissions, use SSH with keys and turn off password logins. Attackers are always looking for the easiest way in.
At the end of the day, the only way to stay secure is to sleep with one eye open, totally paranoid. Watch your logs, install Nagios and set-up some alerts, hire a professional to do a security audit. There's no such thing as 100% secure, but knowing that is half the battle. |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | md5 is a *[cryptographic hash function](http://en.wikipedia.org/wiki/MD5)*. once hashed, it cannot be "un-hashed" back to the original value (one-way) as opposed to [encryption](http://en.wikipedia.org/wiki/Encryption) which is two-way (encrypt-decrypt).
for security of your data, consider these scenarios and ways of prevention instead of just encryption:
* [cross-site request forgeries](http://en.wikipedia.org/wiki/Cross-site_request_forgery) (CRSF) - prevent using form tokens
* [SSL connection](http://en.wikipedia.org/wiki/Secure_Sockets_Layer) (the "httpS://") to prevent data interception in transport
* [hash salting](http://en.wikipedia.org/wiki/Salt_%28cryptography%29) to further protect (but not totally) hashed passwords from dictionary attacks. weak and common passwords are the targets in this case.
* hashing is not absolute. there is a limit to how many combinations of letters and numbers in a hash. at some point extremely different strings may have the same hash value. this is known as a [collision](http://en.wikipedia.org/wiki/Collision_%28computer_science%29)
* hashes are prone to brute-force/dictionary attacks. although hashes are one way, one can create a string-hash dictionary, match the hash and figure out the string behind it.
* [cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) (XSS) which can include (but not limited to) cookie stealing, click jacking, etc.
* [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) - ways to trick your SQL when forms are unsanitized
* expendable [session ids](http://en.wikipedia.org/wiki/Session_ID) to track user sessions - which should expire in a given amount of time, hence an auto log-out mechanism.
* identify your user! user ip address, browser detection, etc to profile your user. any odd data (like sudden change in IP, location etc.) should be considered within a certain threshold. (facebook has this feature. i once accessed my facebook using a proxy - auto lockdown) | You are doing it wrong, because:
* md5 is considered broken,
* preg\_replace() will not give you much.
Consider using already developed, tested and secure frameworks (candidates include Zend Framework, Symphony, Kohana, Yii) for your system. You have a long way before you will achieve security at least nearly as good as standard framework's. Also consider using prepared statements instead of preg\_replace() and salted sha1 instead of simple md5, if you still want to reinvent the wheel.
Furthermore:
* secure your app against such acronyms as XSS, CSRF,
* require SSL at all times (for every request, even for images / styles / scripts),
* read security newsletters (you will need them if you want to build secure system for financial activities). |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | md5 is a *[cryptographic hash function](http://en.wikipedia.org/wiki/MD5)*. once hashed, it cannot be "un-hashed" back to the original value (one-way) as opposed to [encryption](http://en.wikipedia.org/wiki/Encryption) which is two-way (encrypt-decrypt).
for security of your data, consider these scenarios and ways of prevention instead of just encryption:
* [cross-site request forgeries](http://en.wikipedia.org/wiki/Cross-site_request_forgery) (CRSF) - prevent using form tokens
* [SSL connection](http://en.wikipedia.org/wiki/Secure_Sockets_Layer) (the "httpS://") to prevent data interception in transport
* [hash salting](http://en.wikipedia.org/wiki/Salt_%28cryptography%29) to further protect (but not totally) hashed passwords from dictionary attacks. weak and common passwords are the targets in this case.
* hashing is not absolute. there is a limit to how many combinations of letters and numbers in a hash. at some point extremely different strings may have the same hash value. this is known as a [collision](http://en.wikipedia.org/wiki/Collision_%28computer_science%29)
* hashes are prone to brute-force/dictionary attacks. although hashes are one way, one can create a string-hash dictionary, match the hash and figure out the string behind it.
* [cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) (XSS) which can include (but not limited to) cookie stealing, click jacking, etc.
* [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) - ways to trick your SQL when forms are unsanitized
* expendable [session ids](http://en.wikipedia.org/wiki/Session_ID) to track user sessions - which should expire in a given amount of time, hence an auto log-out mechanism.
* identify your user! user ip address, browser detection, etc to profile your user. any odd data (like sudden change in IP, location etc.) should be considered within a certain threshold. (facebook has this feature. i once accessed my facebook using a proxy - auto lockdown) | I am an experienced PHP developer and I want suggest to you to take a look to this project [OWASP\_Development\_Guide](https://www.owasp.org/index.php/Projects/OWASP_Development_Guide). Every web developer should be use it as a bible. It has been very useful for me and I hope it will be the same for you.
Here a brief description of the document:
>
> The Development Guide provides practical guidance and includes J2EE, ASP.NET, and PHP code samples. The Development Guide covers an extensive array of application-level security issues, from SQL injection through modern concerns such as phishing, credit card handling, session fixation, cross-site request forgeries, compliance, and privacy issues.
>
>
> |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | `preg_replace()` will not do much in terms of security. You should familiarize yourself with some basic security/crypto before doing this work. Also, consider the use of a standard cryptographic library for encrypting/decrypting data instead of arbitrarily using hash or regex functions.
Take a look at this: <http://php.net/manual/en/book.openssl.php> | As others have pointed out, md5 is broken. Also, a SHA1 hash is very fast to compute which actually makes it **worse** as a hashing algo. Instead look at bcrypt. Assuming you're using PHP, the <http://www.openwall.com/phpass/> is very a nice password to use that handles hashing and salting for you transparently.
Using preg\_replace() for escaping data to the database is a **very bad idea**. Almost all databases include their own sanitization functions, PHP/MySQL is no exception with mysql\_real\_escape\_string().
Some more points (please note none of these are set in stone):
**Sanitize all input**
Assume that everything the user sends to your server is designed to cause harm. This includes form submissions, but also URL routes, cookie values, server vars, EVERYTHING. Using a framework will often provide some insulation from this, automatically escaping a lot of data for you.
**Escape all output**
Assume that everything you display on your site is designed to cause harm. **XSS** and **CSRF** are amongst the most common techniques for attacking websites. Escape all text that you output to the browser. Look into using nonces to mitigate attacks.
**Use TLS/SSL**
If you want to protect your users data enroute, get yourself a signed SSL certificate and set it up. This allows visitors to go to <https://yoursite.com> securely (or at least more securely if they're the kind of person who does internet banking on coffee shop wifi).
**Use a framework**
Everyone begins by writing their own framework because they know how to do it right, or don't need the extra complexity or whatever reason they come up with. Unless you're writing a super-specific-niche-application for which PHP probably isn't the right answer anyway, **use a framework**. I prefer <http://kohanaframework.org/>, but there's a whole range out there from <http://codeigniter.com/> through to <http://framework.zend.com/>. Frameworks handle session encryption, database escaping, input sanitization and more for you, and because they're used by many people the chance of a bug is much less than code that only one person has worked on.
**Secure your infrastructure**
This one tends to fly by most people, but make sure you take some time to look at the server(s) you're running on. Are you on a shared account? You don't want to be storing financial information on them then (in some countries it's even illegal too). Apply security patches for your OS/software, make sure you haven't left an old upload script lying around, check your file permissions, use SSH with keys and turn off password logins. Attackers are always looking for the easiest way in.
At the end of the day, the only way to stay secure is to sleep with one eye open, totally paranoid. Watch your logs, install Nagios and set-up some alerts, hire a professional to do a security audit. There's no such thing as 100% secure, but knowing that is half the battle. |
9,073,440 | I am creating a information system that will handle financial information, contacts, etc. I am developing the site from complete scratch using object oriented programming (classes, functions, etc). A majority of the data will be from a MySQL database. Users will be able to get and submit data to the database.
I am already using the hash function to encrypt data such as passwords, serial keys. I am also using preg\_replace() function for all other data going to the database.
What other security measures do I need to take to insure that submitting and getting data from the database does not compromise security? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9073440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029393/"
] | `preg_replace()` will not do much in terms of security. You should familiarize yourself with some basic security/crypto before doing this work. Also, consider the use of a standard cryptographic library for encrypting/decrypting data instead of arbitrarily using hash or regex functions.
Take a look at this: <http://php.net/manual/en/book.openssl.php> | Hope you have good liability insurance if you are using md5 to secure financial information. Read about md5, <http://en.wikipedia.org/wiki/MD5>, paying close attention to the line
>
> The security of the MD5 hash function is severely compromised.
>
>
> |
25,164,282 | As a newbie to Java, and many years of iOS and .NET experience, I found this to be massively confusing. What I want I thought would be very simple - I want a dialog (called from a main window) with OK and Cancel buttons. When you click OK, it does something, then dismisses the dialog. When you click Cancel, it just dismisses the dialog.
However, doing this using the SWT shell Dialog class is not obvious. How do you get a button to dismiss the dialog, and return execution back to the main Window? | 2014/08/06 | [
"https://Stackoverflow.com/questions/25164282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706983/"
] | Use `Shell.close()` rather than `dispose()` - so `shlCheckOut.close()`.
`Shell.close` sends the `SWT.Close` event and then calls `dispose`. | With some trial-and-error and a lot of fruitless searching, I found in your button code, you have to call the .dispose() method of the dialog's shell variable. For example, my dialog is `CheckOutDialog`, thus I named the shell variable `shlCheckOut`. In the `createContents()` method, I put the button code as such:
...
```
Button btnCancel = new Button(shlCheckOut, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shlCheckOut.dispose();
}
}
}
``` |
56,282,102 | This is the current hierarchy:
**App.js:**
The state in this parent component has the following grid object:
```
grid: [
[{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" }],
[{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" }],
[{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" }],
[{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" }],
[{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" },{ color: "lightgray" }]
],
```
This grid is passed down to `GridContainer` like so:
```
render(){
return (
<div className="App">
<GridContainer grid={this.state.grid} currentColor={this.state.currentColor} handleClick={this.handleClick}/>
</div>
);
}
```
In `GridContainer`, grid is mapped through and it generates a `RowContainer` component for every "row", which is every array of objects in the parent array.
```
{this.props.grid.map((row) => {
return <RowContainer row={row} handleClick = {this.props.handleClick} currentColor = {this.props.currentColor}/>;
})}
```
Likewise, in `RowContainer`, the row is mapped through and a cell is generated for every object in that array:
```
{this.props.row.map((cell) => {
return <Cell cell={cell} color={cell.color} handleClick = {this.props.handleClick} currentColor={this.props.currentColor}/>;
})}
```
**Cell.js:**
```
import React, { Component } from 'react';
import styled from 'styled-components'
const StyledCell = styled.div`
background-color: ${props => props.color};
border-radius: 50%;
margin: 1rem;
width: 133px;
height: 100px;
`;
// Give cell its own state from passed down props, and change state based on current color only when CLICKED
class Cell extends Component {
render() {
return(
<StyledCell onClick={this.props.handleClick} color = {this.props.color}>
</StyledCell>
)
}
}
export default Cell;
```
My question is, when a cell is clicked and the `handleClick` method in App.js is triggered, how do I instruct it to change only the `color` key value pair of that specific element in the grid?
Apologies for the lengthy post, I tried to keep it as concise as I could. | 2019/05/23 | [
"https://Stackoverflow.com/questions/56282102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948489/"
] | Each item should ideally have a unique id. You *could* do this with the nested indices (e.g. `grid[2][3]`) but that is not as explicit. For example, if an item in `grid` was
```
{ color: "lightgrey", id: 123 }
```
Then in your `Row`, you can make a function to pass the id (instead of declaring it inside each cell) -
```
handleClick = id => () => this.props.handleClick(id);
```
and you can return -
```
<Cell cell={cell} color={cell.color} handleClick={this.handleClick(cell.id)} currentColor={this.props.currentColor}/>;
```
`handleClick` can take an `id` as an argument and only apply your change to that item:
```
handleClick = id => {
const { grid } = this.state;
const newGrid = grid.map(row => (
row.map(cell => (
cell.id === id ? {...cell, color: "yourNewColor" } : cell
))
));
this.setState({ grid: newGrid });
}
```
That way, you only change the color of the specific cell you clicked, while keeping the rest of your cells in the same state they were before. | I suggest adding the cell parameter to the `handleClick` function
```
{this.props.row.map((cell, index) => (
<Cell
cell={cell}
handleClick={this.props.handleClick}
/>;
)}
class Cell extends Component {
handleClick = () => {
this.props.handleClick(this.props.cell)
}
render() {
return (
<StyledCell
onClick={this.handleClick}
color={this.props.cell.color}
/>;
)}
}
```
Then you should update the `handleClick` function into the top Component
```
handleClick = cellToUpdate => {
const grid = this.state.grid.map(
row => row.map(cell => cell === cellToUpdate ? {color: "red"} : cell
);
this.setState({ grid });
}
```
Note that using this method will create an extra function for each cell
If you absolutly want to declare only one function, you should consider passing `data-attributes` to `StyledCell` (`data-rowIndex` and `data-columnIndex`) and retrieve them into the `handleClick` function with `event.currentTarget.dataset.rowIndex` and `event.currentTarget.dataset.columnIndex` |
16,567,316 | I am working in ASP.NET MVC. I want to add videos in my view. I have read article on [Working With Videos in ASP.NET](http://www.asp.net/web-pages/tutorials/files,-images,-and-media/10-working-with-video)
But i want a generic way to play all type of videos in my web page. This article, although good, but confuses me that how to identify file format and then use related type of Web Helper. There are hundreds of video file formats, how to play all of them, by a single strategy. Mentioned article only describes three formats. Please guide me in this regard. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16567316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351521/"
] | You are encoding ASCII codepoints *only*. UTF-8 is a superset of ASCII, any ASCII codepoints are encoded to the *same bytes* as ASCII would use. What you are printing is correct, that **is** UTF-8.
Use some non-ASCII codepoints to see the difference:
```
>>> 'Hello world with an em-dash: \u2014\n'.encode('utf8')
b'Hello world with an em-dash: \xe2\x80\x94\n'
```
Python will just use the characters themselves when it shows you a `bytes` value with printable ASCII bytes in it. Any byte value that is *not* printable is shown as a `\x..` escape code, or a single-character escape sequence if there is one (`\n` for newline).
From your example output, on the other hand, you seem to be expecting to output Python unicode literal escape codes:
```
>>> '\u0015\u0123'
'\x15ģ'
```
Since U+0123 is printable, Python 3 just shows it; the non-printable U+0015 (`NEGATIVE ACKNOWLEDGE`) is a codepoint in the `0x00`-`0xFF` range and is shown using the shorter `\x..` escape notation.
To show *only* unicode escape sequences for your text, you need to process it character by character:
```
>>> input_text = 'Hello World!'
>>> print(''.join('\\u{:04x}'.format(ord(c)) for c in input_text))
\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064\u0021
>>> input_text = 'Hello world with an em-dash: \u2014\n'
>>> print(''.join('\\u{:04x}'.format(ord(c)) for c in input_text))
\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064\u0020\u0077\u0069\u0074\u0068\u0020\u0061\u006e\u0020\u0065\u006d\u002d\u0064\u0061\u0073\u0068\u003a\u0020\u2014\u000a
```
It is important to stress that this is **not** UTF-8, however. | You can use *ord* to the encoded bytes into numbers and use string formatting you display their hex values.
```
>>> s = u'Hello World \u0664\u0662'
>>> print s
Hello World ٤٢
>>> print ''.join('\\x%02X' % ord(c) for c in s.encode('utf-8'))
\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x20\xD9\xA4\xD9\xA2
``` |
74,237 | >
> Ezekiel26:7 YLT
>
>
> For, thus said the Lord Jehovah: Lo, I am bringing in unto Tyre Nebuchadrezzar king of Babylon, From the north -- a king of kings, With horse, and with chariot, and with horsemen, Even an assembly, and a numerous people.
>
>
>
>
> Ezra 7:12 YLT
>
>
> Artaxerxes, king of kings, to Ezra the priest, a perfect scribe of the law of the God of heaven, and at such a time:
>
>
>
Why is the title "king of kings" given to Artaxerxes and Nebuchadnezzar? | 2022/02/06 | [
"https://hermeneutics.stackexchange.com/questions/74237",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42310/"
] | The root word for immortality here is ἀθανασία ("athanasia"), also used by Paul in 1 Cor. 15:53-54, therein to describe the change from a mortal body which will die to an immortal body that can never die (through the resurrection).
**Life in and of Himself**
Gill's commentary is helpful:
>
> Who only hath immortality,.... Angels are immortal, and so are the
> souls of men, and so will be the bodies of men after the resurrection;
> but then **neither of these have immortality of themselves, they have
> it from God**; who only has it, of himself
>
>
>
See also similar comments from Ellicott:
>
> Who only hath immortality.—The holy angels—the souls of men—are
> immortal. “But one alone, ‘God,’ can be said to have immortality,”
> because He, unlike other immortal beings who enjoy their immortality
> through the will of another, derives it from His own essence.
>
>
>
Jesus affirmed this in John 5:26:
>
> For as the Father hath life in himself; so hath he given to the Son to
> have life in himself;
>
>
>
Indeed this attribute is described by the very name Jehovah:
>
> Jehovah is the Anglicized rendering of the Hebrew, Yahveh or Jahveh,
> signifying the **Self-existent One** (Talmage, *Jesus the Christ* p. 36)
>
>
>
**Conclusion**
The passage from Timothy does not describe the *duration* of the life of a human, but rather its *source*. This is in sharp contrast to the impotence of the false gods worshipped in Ephesus, where Timothy resided at this time (see 1 Tim. 1:2-3) -- they had no life to offer here or hereafter.
As John beautifully put it in his prologue:
>
> In him was life (John 1:4)
>
>
> | “Immortal” is a term that means “not subject to death...everlasting” (American Heritage Dictionary). God alone is immortal, and we derive our immortal bodies at the resurrection from Him (1 Corinthians 15:53).
But the *definitions* that matter are *biblical* definitions - *not* dictionary one. Example - define ‘death’? Biblically *death* means separation. Example, at ‘physical’ death, *you* separate from your ‘earthly’ body.
Everlasting ‘death’ means being separated from God - forever. And God being the ‘source’ of life, means this equates to everlasting death - as opposed to everlasting ‘life’, which is forever joined with God. (through or ‘in’ Christ). Man needs God for immortality. Man ‘needs’ a source of ‘life’.
Now to your Q. Are ‘souls’ inherently immortal? This requires an understanding of the makeup of man. Man himself [spirit] is ‘known’ via his soul. But ‘it’ [his soul] needs a ‘body’. That’s what happened in Genesis 2:7.
Your ‘soul’ needs a ‘body’ in order to ‘express’ yourself. But via the fall, that ‘body’ became subject to ‘death’. Hence, the resurrection will result in - a ‘new’ body. Now importantly, ‘immortal’ is a term that applies to *the body* - and the ‘soul’ gets or inherits this from the ‘body’. So the answer to the Q “are souls *inherently* immortal” is no, or yes.
Back to the definition of ‘immortal’ - “not subject to death”. Our present ‘bodies’ are not immortal - so our ‘soul’ isn’t. But with a ‘new immortal’ body, it [our soul] will be. |
74,237 | >
> Ezekiel26:7 YLT
>
>
> For, thus said the Lord Jehovah: Lo, I am bringing in unto Tyre Nebuchadrezzar king of Babylon, From the north -- a king of kings, With horse, and with chariot, and with horsemen, Even an assembly, and a numerous people.
>
>
>
>
> Ezra 7:12 YLT
>
>
> Artaxerxes, king of kings, to Ezra the priest, a perfect scribe of the law of the God of heaven, and at such a time:
>
>
>
Why is the title "king of kings" given to Artaxerxes and Nebuchadnezzar? | 2022/02/06 | [
"https://hermeneutics.stackexchange.com/questions/74237",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42310/"
] | “Immortal” is a term that means “not subject to death...everlasting” (American Heritage Dictionary). God alone is immortal, and we derive our immortal bodies at the resurrection from Him (1 Corinthians 15:53).
But the *definitions* that matter are *biblical* definitions - *not* dictionary one. Example - define ‘death’? Biblically *death* means separation. Example, at ‘physical’ death, *you* separate from your ‘earthly’ body.
Everlasting ‘death’ means being separated from God - forever. And God being the ‘source’ of life, means this equates to everlasting death - as opposed to everlasting ‘life’, which is forever joined with God. (through or ‘in’ Christ). Man needs God for immortality. Man ‘needs’ a source of ‘life’.
Now to your Q. Are ‘souls’ inherently immortal? This requires an understanding of the makeup of man. Man himself [spirit] is ‘known’ via his soul. But ‘it’ [his soul] needs a ‘body’. That’s what happened in Genesis 2:7.
Your ‘soul’ needs a ‘body’ in order to ‘express’ yourself. But via the fall, that ‘body’ became subject to ‘death’. Hence, the resurrection will result in - a ‘new’ body. Now importantly, ‘immortal’ is a term that applies to *the body* - and the ‘soul’ gets or inherits this from the ‘body’. So the answer to the Q “are souls *inherently* immortal” is no, or yes.
Back to the definition of ‘immortal’ - “not subject to death”. Our present ‘bodies’ are not immortal - so our ‘soul’ isn’t. But with a ‘new immortal’ body, it [our soul] will be. | Neither human intelligent soul, being a creation, is inherently immortal, for inherently immortal is only Three - Father, the Logos, and H. Ghost, the Three being One in their co-eternal and co-unbegun existence and essence.
When Paul says that "only He has immortality", he cannot possibly deny immortality of the Father and the H.Ghost, but that among men only the man Jesus Christ has inherently immortality, for His human nature became an eternal aspect of His divine Person/Hypostasis, so that the eternal, divine, uncreated Person/Hypostasis of Logos after His incarnation or inhumanation cannot be any longer considered without His human nature, to the effect that Jesus Christ is since the Incarnation the name of the Logos/the Son. And so much so that even we can freely worship the dead body of Jesus Christ in tomb before its resurrection while lying there three days without committing an idolatry, for this body is beginnedly but eternally hypostatized and impersonalized by the uncreated divine Person/Hypostasis of Logos; and also, we can freely say that Jesus Christ created the universe along with the Father, for Jesus Christ is exactly the same hypostasis of Logos, who being God is changeless both in the infinity of before and the infinity of the after (Hebrews 13:8), and moreover "before" and "after" apply to Him only from our point of view, while from His own point of view His being is eternal that has only "is" or "am" as a proper tense of the verb to be applied (John 8:58). |
74,237 | >
> Ezekiel26:7 YLT
>
>
> For, thus said the Lord Jehovah: Lo, I am bringing in unto Tyre Nebuchadrezzar king of Babylon, From the north -- a king of kings, With horse, and with chariot, and with horsemen, Even an assembly, and a numerous people.
>
>
>
>
> Ezra 7:12 YLT
>
>
> Artaxerxes, king of kings, to Ezra the priest, a perfect scribe of the law of the God of heaven, and at such a time:
>
>
>
Why is the title "king of kings" given to Artaxerxes and Nebuchadnezzar? | 2022/02/06 | [
"https://hermeneutics.stackexchange.com/questions/74237",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42310/"
] | I agree that the 1 Tim 6:16 clearly teaches that God is the sole source of life - all other beings and creatures depend upon God for existence and life. We see this several times:
* Col 1:17 - And He is before all things, and in Him all things hold together.
* Matt 10:28 - Do not be afraid of those who kill the body but cannot kill the soul. Instead, fear the One who can destroy both soul and body in hell. [See my [answer](https://hermeneutics.stackexchange.com/a/73799/38524) to this question: [A living soul cannot exist without a body (Gen 2:7; 1 Cor 15:44-45) but killing the body doesn't kill the soul (Matt 10:28). Is this a contradiction?](https://hermeneutics.stackexchange.com/q/73790/38524) ]
* Eze 18:4, 20 - Behold, every soul belongs to Me; both father and son are Mine. The soul who sins is the one who will die. ... The soul who sins is the one who will die.
* 1 John 5:12 - Whoever has the Son has life; whoever does not have the Son of God does not have life.
* 2 Thess 1:9 - They will suffer the penalty of eternal destruction, separated from the presence of the Lord and the glory of His might,. [According to the above references, such an arrangement, separated from God means we cannot exist because we are dependent of God for life.]
Recall that the "soul" is the combination of the breath of life and the body as per Gen 2:7 [Again see my [answer](https://hermeneutics.stackexchange.com/a/73799/38524) to [A living soul cannot exist without a body (Gen 2:7; 1 Cor 15:44-45) but killing the body doesn't kill the soul (Matt 10:28). Is this a contradiction?](https://hermeneutics.stackexchange.com/q/73790/38524) ] Only God can destroy the person completely - but God can also resurrect the person as well.
Thus, no one is inherently immortal - we all depend on God for life and existence. Thus when a Person is permanently separated from God, that person/being ceases to exist.
Let me state the same thing in a different way - if souls/people were immortal, then they would not be dependent on God for life but would have an independent existence. God could not destroy them. Such an idea is unthinkable!
Stated another way - humans and other beings have what is known in technical theology speak as "conditional immortality" meaning that we (as resurrected saints) and heavenly angels only have life and immortality as long as we remain connected to the source of life, God. | “Immortal” is a term that means “not subject to death...everlasting” (American Heritage Dictionary). God alone is immortal, and we derive our immortal bodies at the resurrection from Him (1 Corinthians 15:53).
But the *definitions* that matter are *biblical* definitions - *not* dictionary one. Example - define ‘death’? Biblically *death* means separation. Example, at ‘physical’ death, *you* separate from your ‘earthly’ body.
Everlasting ‘death’ means being separated from God - forever. And God being the ‘source’ of life, means this equates to everlasting death - as opposed to everlasting ‘life’, which is forever joined with God. (through or ‘in’ Christ). Man needs God for immortality. Man ‘needs’ a source of ‘life’.
Now to your Q. Are ‘souls’ inherently immortal? This requires an understanding of the makeup of man. Man himself [spirit] is ‘known’ via his soul. But ‘it’ [his soul] needs a ‘body’. That’s what happened in Genesis 2:7.
Your ‘soul’ needs a ‘body’ in order to ‘express’ yourself. But via the fall, that ‘body’ became subject to ‘death’. Hence, the resurrection will result in - a ‘new’ body. Now importantly, ‘immortal’ is a term that applies to *the body* - and the ‘soul’ gets or inherits this from the ‘body’. So the answer to the Q “are souls *inherently* immortal” is no, or yes.
Back to the definition of ‘immortal’ - “not subject to death”. Our present ‘bodies’ are not immortal - so our ‘soul’ isn’t. But with a ‘new immortal’ body, it [our soul] will be. |
74,237 | >
> Ezekiel26:7 YLT
>
>
> For, thus said the Lord Jehovah: Lo, I am bringing in unto Tyre Nebuchadrezzar king of Babylon, From the north -- a king of kings, With horse, and with chariot, and with horsemen, Even an assembly, and a numerous people.
>
>
>
>
> Ezra 7:12 YLT
>
>
> Artaxerxes, king of kings, to Ezra the priest, a perfect scribe of the law of the God of heaven, and at such a time:
>
>
>
Why is the title "king of kings" given to Artaxerxes and Nebuchadnezzar? | 2022/02/06 | [
"https://hermeneutics.stackexchange.com/questions/74237",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42310/"
] | The root word for immortality here is ἀθανασία ("athanasia"), also used by Paul in 1 Cor. 15:53-54, therein to describe the change from a mortal body which will die to an immortal body that can never die (through the resurrection).
**Life in and of Himself**
Gill's commentary is helpful:
>
> Who only hath immortality,.... Angels are immortal, and so are the
> souls of men, and so will be the bodies of men after the resurrection;
> but then **neither of these have immortality of themselves, they have
> it from God**; who only has it, of himself
>
>
>
See also similar comments from Ellicott:
>
> Who only hath immortality.—The holy angels—the souls of men—are
> immortal. “But one alone, ‘God,’ can be said to have immortality,”
> because He, unlike other immortal beings who enjoy their immortality
> through the will of another, derives it from His own essence.
>
>
>
Jesus affirmed this in John 5:26:
>
> For as the Father hath life in himself; so hath he given to the Son to
> have life in himself;
>
>
>
Indeed this attribute is described by the very name Jehovah:
>
> Jehovah is the Anglicized rendering of the Hebrew, Yahveh or Jahveh,
> signifying the **Self-existent One** (Talmage, *Jesus the Christ* p. 36)
>
>
>
**Conclusion**
The passage from Timothy does not describe the *duration* of the life of a human, but rather its *source*. This is in sharp contrast to the impotence of the false gods worshipped in Ephesus, where Timothy resided at this time (see 1 Tim. 1:2-3) -- they had no life to offer here or hereafter.
As John beautifully put it in his prologue:
>
> In him was life (John 1:4)
>
>
> | Neither human intelligent soul, being a creation, is inherently immortal, for inherently immortal is only Three - Father, the Logos, and H. Ghost, the Three being One in their co-eternal and co-unbegun existence and essence.
When Paul says that "only He has immortality", he cannot possibly deny immortality of the Father and the H.Ghost, but that among men only the man Jesus Christ has inherently immortality, for His human nature became an eternal aspect of His divine Person/Hypostasis, so that the eternal, divine, uncreated Person/Hypostasis of Logos after His incarnation or inhumanation cannot be any longer considered without His human nature, to the effect that Jesus Christ is since the Incarnation the name of the Logos/the Son. And so much so that even we can freely worship the dead body of Jesus Christ in tomb before its resurrection while lying there three days without committing an idolatry, for this body is beginnedly but eternally hypostatized and impersonalized by the uncreated divine Person/Hypostasis of Logos; and also, we can freely say that Jesus Christ created the universe along with the Father, for Jesus Christ is exactly the same hypostasis of Logos, who being God is changeless both in the infinity of before and the infinity of the after (Hebrews 13:8), and moreover "before" and "after" apply to Him only from our point of view, while from His own point of view His being is eternal that has only "is" or "am" as a proper tense of the verb to be applied (John 8:58). |
74,237 | >
> Ezekiel26:7 YLT
>
>
> For, thus said the Lord Jehovah: Lo, I am bringing in unto Tyre Nebuchadrezzar king of Babylon, From the north -- a king of kings, With horse, and with chariot, and with horsemen, Even an assembly, and a numerous people.
>
>
>
>
> Ezra 7:12 YLT
>
>
> Artaxerxes, king of kings, to Ezra the priest, a perfect scribe of the law of the God of heaven, and at such a time:
>
>
>
Why is the title "king of kings" given to Artaxerxes and Nebuchadnezzar? | 2022/02/06 | [
"https://hermeneutics.stackexchange.com/questions/74237",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42310/"
] | The root word for immortality here is ἀθανασία ("athanasia"), also used by Paul in 1 Cor. 15:53-54, therein to describe the change from a mortal body which will die to an immortal body that can never die (through the resurrection).
**Life in and of Himself**
Gill's commentary is helpful:
>
> Who only hath immortality,.... Angels are immortal, and so are the
> souls of men, and so will be the bodies of men after the resurrection;
> but then **neither of these have immortality of themselves, they have
> it from God**; who only has it, of himself
>
>
>
See also similar comments from Ellicott:
>
> Who only hath immortality.—The holy angels—the souls of men—are
> immortal. “But one alone, ‘God,’ can be said to have immortality,”
> because He, unlike other immortal beings who enjoy their immortality
> through the will of another, derives it from His own essence.
>
>
>
Jesus affirmed this in John 5:26:
>
> For as the Father hath life in himself; so hath he given to the Son to
> have life in himself;
>
>
>
Indeed this attribute is described by the very name Jehovah:
>
> Jehovah is the Anglicized rendering of the Hebrew, Yahveh or Jahveh,
> signifying the **Self-existent One** (Talmage, *Jesus the Christ* p. 36)
>
>
>
**Conclusion**
The passage from Timothy does not describe the *duration* of the life of a human, but rather its *source*. This is in sharp contrast to the impotence of the false gods worshipped in Ephesus, where Timothy resided at this time (see 1 Tim. 1:2-3) -- they had no life to offer here or hereafter.
As John beautifully put it in his prologue:
>
> In him was life (John 1:4)
>
>
> | I agree that the 1 Tim 6:16 clearly teaches that God is the sole source of life - all other beings and creatures depend upon God for existence and life. We see this several times:
* Col 1:17 - And He is before all things, and in Him all things hold together.
* Matt 10:28 - Do not be afraid of those who kill the body but cannot kill the soul. Instead, fear the One who can destroy both soul and body in hell. [See my [answer](https://hermeneutics.stackexchange.com/a/73799/38524) to this question: [A living soul cannot exist without a body (Gen 2:7; 1 Cor 15:44-45) but killing the body doesn't kill the soul (Matt 10:28). Is this a contradiction?](https://hermeneutics.stackexchange.com/q/73790/38524) ]
* Eze 18:4, 20 - Behold, every soul belongs to Me; both father and son are Mine. The soul who sins is the one who will die. ... The soul who sins is the one who will die.
* 1 John 5:12 - Whoever has the Son has life; whoever does not have the Son of God does not have life.
* 2 Thess 1:9 - They will suffer the penalty of eternal destruction, separated from the presence of the Lord and the glory of His might,. [According to the above references, such an arrangement, separated from God means we cannot exist because we are dependent of God for life.]
Recall that the "soul" is the combination of the breath of life and the body as per Gen 2:7 [Again see my [answer](https://hermeneutics.stackexchange.com/a/73799/38524) to [A living soul cannot exist without a body (Gen 2:7; 1 Cor 15:44-45) but killing the body doesn't kill the soul (Matt 10:28). Is this a contradiction?](https://hermeneutics.stackexchange.com/q/73790/38524) ] Only God can destroy the person completely - but God can also resurrect the person as well.
Thus, no one is inherently immortal - we all depend on God for life and existence. Thus when a Person is permanently separated from God, that person/being ceases to exist.
Let me state the same thing in a different way - if souls/people were immortal, then they would not be dependent on God for life but would have an independent existence. God could not destroy them. Such an idea is unthinkable!
Stated another way - humans and other beings have what is known in technical theology speak as "conditional immortality" meaning that we (as resurrected saints) and heavenly angels only have life and immortality as long as we remain connected to the source of life, God. |
74,237 | >
> Ezekiel26:7 YLT
>
>
> For, thus said the Lord Jehovah: Lo, I am bringing in unto Tyre Nebuchadrezzar king of Babylon, From the north -- a king of kings, With horse, and with chariot, and with horsemen, Even an assembly, and a numerous people.
>
>
>
>
> Ezra 7:12 YLT
>
>
> Artaxerxes, king of kings, to Ezra the priest, a perfect scribe of the law of the God of heaven, and at such a time:
>
>
>
Why is the title "king of kings" given to Artaxerxes and Nebuchadnezzar? | 2022/02/06 | [
"https://hermeneutics.stackexchange.com/questions/74237",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42310/"
] | I agree that the 1 Tim 6:16 clearly teaches that God is the sole source of life - all other beings and creatures depend upon God for existence and life. We see this several times:
* Col 1:17 - And He is before all things, and in Him all things hold together.
* Matt 10:28 - Do not be afraid of those who kill the body but cannot kill the soul. Instead, fear the One who can destroy both soul and body in hell. [See my [answer](https://hermeneutics.stackexchange.com/a/73799/38524) to this question: [A living soul cannot exist without a body (Gen 2:7; 1 Cor 15:44-45) but killing the body doesn't kill the soul (Matt 10:28). Is this a contradiction?](https://hermeneutics.stackexchange.com/q/73790/38524) ]
* Eze 18:4, 20 - Behold, every soul belongs to Me; both father and son are Mine. The soul who sins is the one who will die. ... The soul who sins is the one who will die.
* 1 John 5:12 - Whoever has the Son has life; whoever does not have the Son of God does not have life.
* 2 Thess 1:9 - They will suffer the penalty of eternal destruction, separated from the presence of the Lord and the glory of His might,. [According to the above references, such an arrangement, separated from God means we cannot exist because we are dependent of God for life.]
Recall that the "soul" is the combination of the breath of life and the body as per Gen 2:7 [Again see my [answer](https://hermeneutics.stackexchange.com/a/73799/38524) to [A living soul cannot exist without a body (Gen 2:7; 1 Cor 15:44-45) but killing the body doesn't kill the soul (Matt 10:28). Is this a contradiction?](https://hermeneutics.stackexchange.com/q/73790/38524) ] Only God can destroy the person completely - but God can also resurrect the person as well.
Thus, no one is inherently immortal - we all depend on God for life and existence. Thus when a Person is permanently separated from God, that person/being ceases to exist.
Let me state the same thing in a different way - if souls/people were immortal, then they would not be dependent on God for life but would have an independent existence. God could not destroy them. Such an idea is unthinkable!
Stated another way - humans and other beings have what is known in technical theology speak as "conditional immortality" meaning that we (as resurrected saints) and heavenly angels only have life and immortality as long as we remain connected to the source of life, God. | Neither human intelligent soul, being a creation, is inherently immortal, for inherently immortal is only Three - Father, the Logos, and H. Ghost, the Three being One in their co-eternal and co-unbegun existence and essence.
When Paul says that "only He has immortality", he cannot possibly deny immortality of the Father and the H.Ghost, but that among men only the man Jesus Christ has inherently immortality, for His human nature became an eternal aspect of His divine Person/Hypostasis, so that the eternal, divine, uncreated Person/Hypostasis of Logos after His incarnation or inhumanation cannot be any longer considered without His human nature, to the effect that Jesus Christ is since the Incarnation the name of the Logos/the Son. And so much so that even we can freely worship the dead body of Jesus Christ in tomb before its resurrection while lying there three days without committing an idolatry, for this body is beginnedly but eternally hypostatized and impersonalized by the uncreated divine Person/Hypostasis of Logos; and also, we can freely say that Jesus Christ created the universe along with the Father, for Jesus Christ is exactly the same hypostasis of Logos, who being God is changeless both in the infinity of before and the infinity of the after (Hebrews 13:8), and moreover "before" and "after" apply to Him only from our point of view, while from His own point of view His being is eternal that has only "is" or "am" as a proper tense of the verb to be applied (John 8:58). |
26,015,682 | I have a table like so:
```
Code | BuildDate | BuildQuantity
---------------------------------
1 | 2013-04-10 | 4
1 | 2014-09-23 | 1
1 | 2014-08-20 | 2
7 | 2014-02-05 | 4
```
I want the LINQ query to pick up the LATEST Build date for each Code, pick the BuildQuantity for that Code, and so on for all the records, and sum it up. So for the data above, the result should be `1 + 4 = 5`.
This is what I'm trying:
```
var built = (from tb in db.Builds
orderby tb.BuildDate descending
group tb by tb.Code into tbgrp
select tbgrp.Sum(c => c.BuildQuantity)).First();
```
This query returns 7... What am I doing wrong? | 2014/09/24 | [
"https://Stackoverflow.com/questions/26015682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131992/"
] | You are summing all code's BuildQuantities before you take the first, instead you want to sum the firsts.
```
int built = db.Builds
.GroupBy(b => b.Code)
.Sum(g => g.OrderByDescending(b => b.BuildDate).First().BuildQuantity);
``` | You are looking for the sum of the build quantity of the last entry per code. You're currently ordering before you group, which doesn't actually do anything (after the group, the ordering isn't defined)
So first of, you're looking to get the latest element by code. Lets group first. I'm more comfortable writing through the extension methods:
```
IGrouping<int, Build> grouped = db.Builds.GroupBy(tb => tb.Code)
```
we now have the elements grouped. From each group, we want to get the first element ordered descending by build date.
```
var firsts = grouped.Select(gr => gr.OrderByDescending(gr => gr.BuildDate)
.First())
```
finally, we can get the sum:
```
var sum = firsts.Sum(tb => tb.BuildQuantity);
```
plugging this all together becomes
```
var sum = db.Builds.GroupBy(tb => tb.Code).
.Select(gr => gr.OrderByDescending(gr => gr.BuildDate).First())
.Sum(tb => tb.BuildQuantity);
```
Group by has overloads that allows you to roll almost everything in the group.
If you like compact code, you could write
```
var sum = db.Builds
.GroupBy(tb => tb.Code,
tb => tb,
gr => gr.OrderByDescending(gr => gr.BuildDate)
.First()
.BuildQuantity)
.Sum()
```
though I wouldn't recommend it from a readability point of view |
22,589,341 | I'm new to Spring development.And right now,i'm really facing a problem.Here are the code snippets to make you realize my problem clearly.............
Here is my DAO class:
```
public class LoginDaoImpl {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public int checkLoginDetails(LoginVo loginVo){
String sql = "select count(*) from empsctygrp where username=? and password=?";
jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject(sql,new Object[]{loginVo.getUserName(),loginVo.getPassword()},Integer.class);
return count;
}
}
```
Now here is my Business-Object(BO) class:
```
public class LoginBo {
LoginDaoImpl loginDaoImpl = new LoginDaoImpl();
public int checkLoginDetails(LoginVo loginVo){
return loginDaoImpl.checkLoginDetails(loginVo);
}
}
```
Now,here is my dispatcher-servlet xml code:
```
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@117.194.83.9:1521:XE"/>
<property name="username" value="system"/>
<property name="password" value="password1$"/>
</bean>
<bean id="loginDaoImpl" class="com.abhinabyte.dao.LoginDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
```
Now whenever i'm trying to run this on server the following exception is given:
```
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/A] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required] with root cause
```
java.lang.IllegalArgumentException: Property 'dataSource' is required
Please help me solve this problem.............:( | 2014/03/23 | [
"https://Stackoverflow.com/questions/22589341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3159714/"
] | The tool you are looking for is called grunt.
<http://gruntjs.com/>
You have over 2000 packages for doing many things and one of them in concatenation and minification.
grunt-contrib-cssmin
grunt-contrib-uglify
grunt-contrib-concat
the list goes on an on, but check 'em all here.
<https://github.com/gruntjs/grunt-contrib>
grunt is a little confusing the first time you see it, but there are heaps of resources for it and also heaps of stackoverflow examples.
Once you go grunt you never go back! | I'd think you can merge all javascript files and then minify it. are you using double function names or do you have javascript code outside of functions? maybe that is what is throwing up your errors.
would leave you with only one request to retrieve all your javascript functions , and you would only need to minify / compress one file. |
28,859,295 | If I am in **/home/usr** and I call python **/usr/local/rcom/bin/something.py**
How can I make the script inside **something.py** know he resides in **/usr/local/rcom/bin**?
The `os.path.abspath` is calculated with the `cwd` which is **/home/usr** in this case. | 2015/03/04 | [
"https://Stackoverflow.com/questions/28859295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67153/"
] | Assign the result of `df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)` to a variable so you can perform boolean indexing and then use the index from this to call `isin` and filter your orig df:
```
In [366]:
users = df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)
users
Out[366]:
User_ID
189757330 False
222583401 False
287280509 False
329757763 False
414673119 True
624921653 False
Name: Datetime, dtype: bool
In [367]:
users[users]
Out[367]:
User_ID
414673119 True
Name: Datetime, dtype: bool
In [368]:
users[users].index
Out[368]:
Int64Index([414673119], dtype='int64')
In [361]:
df[df['User_ID'].isin(users[users].index)]
Out[361]:
User_ID Latitude Longitude Datetime
5 414673119 41.555014 2.096583 2014-02-24 20:15:30
6 414673119 41.555014 2.097583 2014-02-24 20:16:30
7 414673119 41.555014 2.098583 2014-02-24 20:17:30
```
You can then call `to_csv` on the above as normal | first, make sure you have no duplicate entries:
```
df = df.drop_duplicates()
```
then, figure out the counts for each:
```
counts = df.groupby('User_ID').Datetime.count()
```
finally, figure out where the indexes overlap:
```
df[df.User_ID.isin(counts[counts > 1].index)]
``` |
17,156,404 | I'm still learning in programming
I'm trying to get customer data in list. So I can get the value from the index, but it only can get the first customer. the index won't increment, I'm still confusing, I have already move the variable for increment the index won't work, maybe my logic isn't right. here's the code, tell me where is not right..?? thank you for you help and explanation
```
public void getJamVSpot()
{
var listJamAwal = new List<String>();
var listJamAkhir = new List<String>();
var listNota = new List<int>();
DateTime tglSewa = dtp_tglSewa.Value.Date;
int r = 0;
String ja = String.Empty;
String jb = String.Empty;
int n = 0;
int indexUp = 0;
if (dtp_tglSewa.Value.Date == jl.getTglJadwalVspot(tglSewa, lap) && rdb_Lapangan_VSpot.Checked == true || rdb_rumputSintetis.Checked == true)
{
IEnumerator<String> jAwal = jl.getJamAwalbyDate(tglSewa, lap);
while (jAwal.MoveNext())
{
listJamAwal.Add(jAwal.Current);
}
IEnumerator<String> jAkhir = jl.getJamAkhirbyDate(tglSewa, lap);
while (jAkhir.MoveNext())
{
listJamAkhir.Add(jAkhir.Current);
}
IEnumerator<int> nota = jl.getNota(tglSewa, lap);
while (nota.MoveNext())
{
listNota.Add(nota.Current);
}
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
} indexUp++;
}
```
 | 2013/06/17 | [
"https://Stackoverflow.com/questions/17156404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2466872/"
] | When you increment the `indexUp` variable you aren't using it anymore.
In your code you are just recovering the first item (0), doing some stuff with this value (in the loops) and exits.
For example, you can wrap your stuff with this loop:
```
for (int indexUp = 0; indexUp < listJamAwal.Count; indexUp++)
{
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
{
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
}
}
``` | There are two problems with how you access the items:
* You assign the variables outside the loop. That will get the values that the index points to at that moment, and changing the index variable later doesn't change what's assigned to the variables. You have to assign the variables inside the loop, except the `count` variable of course which you need before the loop starts.
* You are incrementing the `indexUp` variable after the loop, when you have no use for it any more. You have to put that inside the loop so that it can be used in the next iteration to read new values into the variables. |
17,156,404 | I'm still learning in programming
I'm trying to get customer data in list. So I can get the value from the index, but it only can get the first customer. the index won't increment, I'm still confusing, I have already move the variable for increment the index won't work, maybe my logic isn't right. here's the code, tell me where is not right..?? thank you for you help and explanation
```
public void getJamVSpot()
{
var listJamAwal = new List<String>();
var listJamAkhir = new List<String>();
var listNota = new List<int>();
DateTime tglSewa = dtp_tglSewa.Value.Date;
int r = 0;
String ja = String.Empty;
String jb = String.Empty;
int n = 0;
int indexUp = 0;
if (dtp_tglSewa.Value.Date == jl.getTglJadwalVspot(tglSewa, lap) && rdb_Lapangan_VSpot.Checked == true || rdb_rumputSintetis.Checked == true)
{
IEnumerator<String> jAwal = jl.getJamAwalbyDate(tglSewa, lap);
while (jAwal.MoveNext())
{
listJamAwal.Add(jAwal.Current);
}
IEnumerator<String> jAkhir = jl.getJamAkhirbyDate(tglSewa, lap);
while (jAkhir.MoveNext())
{
listJamAkhir.Add(jAkhir.Current);
}
IEnumerator<int> nota = jl.getNota(tglSewa, lap);
while (nota.MoveNext())
{
listNota.Add(nota.Current);
}
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
} indexUp++;
}
```
 | 2013/06/17 | [
"https://Stackoverflow.com/questions/17156404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2466872/"
] | When you increment the `indexUp` variable you aren't using it anymore.
In your code you are just recovering the first item (0), doing some stuff with this value (in the loops) and exits.
For example, you can wrap your stuff with this loop:
```
for (int indexUp = 0; indexUp < listJamAwal.Count; indexUp++)
{
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
{
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
}
}
``` | I dont see any point of using first loop with "i" and then second with foreach. Its totally wrong - you are doing the same thing "count" times!
You also need to change penyewa, no\_kontak, status because you are using same values inside loop
And in addition, I have never seen so confusing and unclear variable naming, you should change it if you want some else to use it :D |
17,156,404 | I'm still learning in programming
I'm trying to get customer data in list. So I can get the value from the index, but it only can get the first customer. the index won't increment, I'm still confusing, I have already move the variable for increment the index won't work, maybe my logic isn't right. here's the code, tell me where is not right..?? thank you for you help and explanation
```
public void getJamVSpot()
{
var listJamAwal = new List<String>();
var listJamAkhir = new List<String>();
var listNota = new List<int>();
DateTime tglSewa = dtp_tglSewa.Value.Date;
int r = 0;
String ja = String.Empty;
String jb = String.Empty;
int n = 0;
int indexUp = 0;
if (dtp_tglSewa.Value.Date == jl.getTglJadwalVspot(tglSewa, lap) && rdb_Lapangan_VSpot.Checked == true || rdb_rumputSintetis.Checked == true)
{
IEnumerator<String> jAwal = jl.getJamAwalbyDate(tglSewa, lap);
while (jAwal.MoveNext())
{
listJamAwal.Add(jAwal.Current);
}
IEnumerator<String> jAkhir = jl.getJamAkhirbyDate(tglSewa, lap);
while (jAkhir.MoveNext())
{
listJamAkhir.Add(jAkhir.Current);
}
IEnumerator<int> nota = jl.getNota(tglSewa, lap);
while (nota.MoveNext())
{
listNota.Add(nota.Current);
}
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
} indexUp++;
}
```
 | 2013/06/17 | [
"https://Stackoverflow.com/questions/17156404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2466872/"
] | There are two problems with how you access the items:
* You assign the variables outside the loop. That will get the values that the index points to at that moment, and changing the index variable later doesn't change what's assigned to the variables. You have to assign the variables inside the loop, except the `count` variable of course which you need before the loop starts.
* You are incrementing the `indexUp` variable after the loop, when you have no use for it any more. You have to put that inside the loop so that it can be used in the next iteration to read new values into the variables. | I dont see any point of using first loop with "i" and then second with foreach. Its totally wrong - you are doing the same thing "count" times!
You also need to change penyewa, no\_kontak, status because you are using same values inside loop
And in addition, I have never seen so confusing and unclear variable naming, you should change it if you want some else to use it :D |
58,937,483 | Let's say there are two sub images of a large image. I am trying to detect the overlapping area of two sub images. I know that template matching can help to find the templates. But i'm not sure how to find the intersected area and remove them in either one of the sub images. Please help me out. | 2019/11/19 | [
"https://Stackoverflow.com/questions/58937483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12318972/"
] | MatchTemplate returns the most probable position of a template inside a picture. You could do the following steps:
* Find the (x,y) origin, width and height of each picture inside the larger one
* Save them as rectangles with that data(cv::Rect r1, cv::Rect r2)
* Using the & operator, find the overlap area between both rectangles (r1&r2) | Extract features from both images using feature descriptor (SIFT, SURF, ORB, Daisy, etc). Then you match those keypoints and ran RANSAC to estimate homography matrix.
[Here](https://www.pyimagesearch.com/2016/01/11/opencv-panorama-stitching/) is a nice post with code. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | How To Train Kill Your Dragon
=============================
This is not even close to a fair fight.
What you've described is a sort of enormous, slow, heavily armored helicopter lacking long range weaponry against a force designed to repel forces many times larger, faster, and more effective.
If he flies, he dies.
---------------------
The MEU has air detection and defense systems to deal with supersonic aircraft with weapons it can launch from dozens of miles out. It's also able to deal with low flying aircraft and attack helicopters. It will see Smaug as soon as he takes off either on radar, infrared, or visual.
Smaug's pokey 75 knots is laughably slow, even for a helicopter. +4g to -2g is very sluggish for a military aircraft. Almost every heavy weapon of the MEU will be able to hit him, especially with his very large cross-section and poor maneuverability. Even a tank could hit him.
About the only thing Smaug has going for him is his all over resistance to 23mm and his bulk. That will probably render normal AAA and air-to-air missiles which are designed to hit lightly armored aircraft with [a sort of shotgun blast](https://en.wikipedia.org/wiki/Air-to-air_missile#Warhead) ineffective. Unfortunately for Smaug, he's so big and sluggish that anti-tank weapons can track and hit him.
All Marine attack aircraft and helicopters can outrun and outmaneuver Smaug. Even an [Osprey](https://en.wikipedia.org/wiki/Bell_Boeing_V-22_Osprey#Specifications_.28MV-22B.29) or [Super Stallion](https://en.wikipedia.org/wiki/Sikorsky_CH-53E_Super_Stallion). They can easily stay outside of his short attack range and pelt him with any number of weapons.
Here are all the ways Smaug will die if it is detected by the MEU, in rough order of range.
* [AV-8B Harrier II](https://en.wikipedia.org/wiki/AV-8B_Harrier_II) attack aircraft
+ Any number of anti-tank missiles.
+ [25mm GAU-12 cannon](https://en.wikipedia.org/wiki/GAU-12_Equalizer) chewing through his armor.
* [AH-1Z Viper](https://en.wikipedia.org/wiki/Bell_AH-1Z_Viper) attack helicopters.
+ [Hellfire missiles](https://en.wikipedia.org/wiki/AGM-114_Hellfire).
+ [20mm cannon](https://en.wikipedia.org/wiki/M197_Gatling_gun) chewing through his armor.
* [TOW missiles](https://en.wikipedia.org/wiki/BGM-71_TOW) mounted on air units, vehicles, and tripods.
* 120mm shell from [a M1A1's main gun](https://en.wikipedia.org/wiki/M1_Abrams#Aiming).
* [Various LAV weapons](https://en.wikipedia.org/wiki/LAV-25#Variants).
* Hand held [Javelin anti-tank missile](https://en.wikipedia.org/wiki/Javelin_anti-tank_missile).
Any of these can hit and disable Smaug well over a kilometer out, far outside his fire breath range.
That's not even counting what's available on their ships.
If he attempts to approach on the ground, he dies.
--------------------------------------------------
Something as big as Smaug cannot hide on the ground. As with aircraft, Marines are prepared to deal with smaller targets which are stealthier and just as speedy. They have radar, infrared, and visual detection. They'll send out scouting parties in force to find or herd the enormous dragon.
Once found, a single helicopter can keep him in sight.
Any number of anti-tank weapons and high rate of fire autocannons will take him down before he gets anywhere near fire breathing range.
In addition, the MEU's [155mm towed artillery](https://en.wikipedia.org/wiki/M777_howitzer) has sufficient range (24 km) to cover most of the 500 km2 area without moving. While it might not be accurate enough to hit Smaug, it will certainly keep him on his toes should he land. It could even be used as bait.
If he hides in a cave, he surrenders or he dies slowly.
-------------------------------------------------------
[The US military's experience in Afghanistan has made them very good at dealing with enemies in caves](http://usatoday30.usatoday.com/tech/news/2001/11/27/tech-cave-hunting.htm).
Smaug's presence will be detectable from the air. Scorch marks, knocked over trees, patterns of disturbed soil will all give away his general area.
Once they've found his general location, the Marines will use locals, satellite data, infrared, audio, seismic, ground penetrating radar, and even microgravity to find caves in the area. Much of this can be done safely from the air. Ground scouts will be backed up with personal anti-tank weapons, light armor, and continuous air cover. If Smaug interferes with the search, see previous sections.
Once they've found where he's hiding, they'll probably try negotiations. If negotiations fail, any number of weapons are available to either kill him or flush him out. Smaug is presumably fire-proof, but a [thermobaric weapon](https://en.wikipedia.org/wiki/Thermobaric_weapon), ie. a Fuel-air explosive, can harm or kill him with the over-pressure. | I like Dayton Saragosa's answer, he treats the dragon as somebody with a mind of a human and abilities of an animal, and not an odd piece of military hardware. I'd like to follow up with a few ideas.
I agree dragon will not survive a direct hit from many modern weapons, but I assume he is smart enough to (try to) avoid getting hit, and smart enough to try to hide and escape. After all, the "win" condition for the dragon is to survive, not to destroy the military.
Hitting the dragon
==================
As a flying creature, he should be more agile than human-made aircraft. After all, he can change geometry of his wings, or fold them altogether.
He is probably more aware of its surroundings than an aircraft pilot.
Hitting him with direct-fire weapons is hard because he will see the flash and dodge.
Hitting him with tracking missiles is not as easy as it sounds.
He is a reptile, so probably cold-blooded, and infrared does not work.
He is not metallic, so radar-guided will not work.
I hear there are missiles that use a camera to track a dark dot against the blue sky. Dragon can dive below the missile to confuse this.
Guidance directly by a human is subject to reaction time.
But of course all this dodging will make him tired eventually, and he might not be able to dodge multiple threats at the same time. So his best bet is to avoid detection.
Finding the dragon
==================
Yes he is large, but we are talking about miles and miles of land.
And we will let dragon have really good senses.
He will not show up on radar due to lack of metal, and he might be cold-blooded, so no infrared. He is smart enough to hide in caves, or in the terrain that has similar color to him, or even roll around in dirt or sand to make himself harder to spot. And he is smart enough not to leave tracks or other tell-tale signs near his hiding place. He might even be able to dig a hole big enough to bury himself. So detection from air is problematic.
So military will have to look for him with land patrols, cave scanners, etc.
This will be slow, and they cannot cover entire 500 square miles at once, so dragon could try to sneak into territory that has already been searched.
But again, he cannot hide forever - he needs to eat and sleep.
If the dragon is spotted
------------------------
He can evade immediate fire, at least for a bit. But then he needs to disappear again. He cannot out-run the helicopters. But here are a few ideas:
* Hide in the clouds, assuming there are some
* Dive underwater. If he is the right color, he will be very hard to spot.
* Hide in a dense forest, using his senses to stay away from ground units.
* Out-maneuver helicopters in rocky canyons
* Pull the observation helicopter away from ground forces, get below it,claw through the tail boom
Long Term
=========
In fact, once dragon becomes aware of the military hunting for him, could just leave the area before they find him. But I will assume that he has to stay for some reason.
If dragon is tied to specific item or spot (eggs, magic crystal giving him power), and military find out, the dragon is screwed.
If there is no specific spot, then dragon will have to resort to guerilla tactics: hit small patrols and run, try to disrupt supply lines or food stores of the military. But I do admit that his chances are slim - he is one mistake short of death. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | I like Dayton Saragosa's answer, he treats the dragon as somebody with a mind of a human and abilities of an animal, and not an odd piece of military hardware. I'd like to follow up with a few ideas.
I agree dragon will not survive a direct hit from many modern weapons, but I assume he is smart enough to (try to) avoid getting hit, and smart enough to try to hide and escape. After all, the "win" condition for the dragon is to survive, not to destroy the military.
Hitting the dragon
==================
As a flying creature, he should be more agile than human-made aircraft. After all, he can change geometry of his wings, or fold them altogether.
He is probably more aware of its surroundings than an aircraft pilot.
Hitting him with direct-fire weapons is hard because he will see the flash and dodge.
Hitting him with tracking missiles is not as easy as it sounds.
He is a reptile, so probably cold-blooded, and infrared does not work.
He is not metallic, so radar-guided will not work.
I hear there are missiles that use a camera to track a dark dot against the blue sky. Dragon can dive below the missile to confuse this.
Guidance directly by a human is subject to reaction time.
But of course all this dodging will make him tired eventually, and he might not be able to dodge multiple threats at the same time. So his best bet is to avoid detection.
Finding the dragon
==================
Yes he is large, but we are talking about miles and miles of land.
And we will let dragon have really good senses.
He will not show up on radar due to lack of metal, and he might be cold-blooded, so no infrared. He is smart enough to hide in caves, or in the terrain that has similar color to him, or even roll around in dirt or sand to make himself harder to spot. And he is smart enough not to leave tracks or other tell-tale signs near his hiding place. He might even be able to dig a hole big enough to bury himself. So detection from air is problematic.
So military will have to look for him with land patrols, cave scanners, etc.
This will be slow, and they cannot cover entire 500 square miles at once, so dragon could try to sneak into territory that has already been searched.
But again, he cannot hide forever - he needs to eat and sleep.
If the dragon is spotted
------------------------
He can evade immediate fire, at least for a bit. But then he needs to disappear again. He cannot out-run the helicopters. But here are a few ideas:
* Hide in the clouds, assuming there are some
* Dive underwater. If he is the right color, he will be very hard to spot.
* Hide in a dense forest, using his senses to stay away from ground units.
* Out-maneuver helicopters in rocky canyons
* Pull the observation helicopter away from ground forces, get below it,claw through the tail boom
Long Term
=========
In fact, once dragon becomes aware of the military hunting for him, could just leave the area before they find him. But I will assume that he has to stay for some reason.
If dragon is tied to specific item or spot (eggs, magic crystal giving him power), and military find out, the dragon is screwed.
If there is no specific spot, then dragon will have to resort to guerilla tactics: hit small patrols and run, try to disrupt supply lines or food stores of the military. But I do admit that his chances are slim - he is one mistake short of death. | How would you beat him? With a stick, while he slept. With the number of resources available to an MEU, they could take shifts. Given the dragon's speed he could be kept under constant attack. With no chance to rest, he would be easy prey in a couple days. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | I was a Marine Infantryman and I think people have zero idea how truly powerful modern weaponry is. In movies fighter jets float lazily in at a monster firing point blank until he swats it down like a bird. In reality those jets are going to be at 30,000 feet moving at twice the speed of sound carrying enough ordinance to level several city blocks which they can target and fire from several miles away.
For example, the TOW 2 bravo Aero missile (my weapon specialization). It was a 68 pound guided missile with a range of 4,500 meters (just under 3 miles.) The missile covers that maximum distance in 26 seconds. Thats a 68 pound guided missile with a shaped charge that can penetrate meters of concrete or several inches of hardened homogenous steel moving faster than a lot of handgun bullets. The TOW is considered a small and somewhat slow missile, and is also somewhat obsolete since it needs to be manually steered and nwer stuff like the javelin are fire and forget.
So yeah. A single Marine could mess up yer dragon good from several miles away and not even have to get out of his gun turret seat. | Air-launched missiles.
A dragon can't outrun or evade [the missiles that a Marine helicopter or tiltrotor can carry](https://en.wikipedia.org/wiki/AGM-114_Hellfire). |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | I was a Marine Infantryman and I think people have zero idea how truly powerful modern weaponry is. In movies fighter jets float lazily in at a monster firing point blank until he swats it down like a bird. In reality those jets are going to be at 30,000 feet moving at twice the speed of sound carrying enough ordinance to level several city blocks which they can target and fire from several miles away.
For example, the TOW 2 bravo Aero missile (my weapon specialization). It was a 68 pound guided missile with a range of 4,500 meters (just under 3 miles.) The missile covers that maximum distance in 26 seconds. Thats a 68 pound guided missile with a shaped charge that can penetrate meters of concrete or several inches of hardened homogenous steel moving faster than a lot of handgun bullets. The TOW is considered a small and somewhat slow missile, and is also somewhat obsolete since it needs to be manually steered and nwer stuff like the javelin are fire and forget.
So yeah. A single Marine could mess up yer dragon good from several miles away and not even have to get out of his gun turret seat. | **Wrong tool for the job**
So, this dragon has no chance against a moderm military, but then you wouldn't want to send the military against such creature. If he is not inteligent then you will probably need to devise a conservation plan to stop the creature from being hunted to death, since any animal like that will probably have a big impact on the whole enviroment.
Just think about wolves, many people seem them as these terrible predators and feel justified in hunting them, but after the wolves ar killed off you will have a super polutation of deer and other herbivores in the region that will destroy the ecological balance of the region.
Another good example are lions in Africa, seem for many years as a plague, but now there are many programs to conserve them.
However! If the animal is intelligent, you will want to bring in the historians, this creature supposedly has existed for a very long time and any historian will give his left arm just to be able to ask a few questions to the dragon. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | Air-launched missiles.
A dragon can't outrun or evade [the missiles that a Marine helicopter or tiltrotor can carry](https://en.wikipedia.org/wiki/AGM-114_Hellfire). | The firepower of a MEU could dispose of Smaug quite easily, although they'd need to use visually guided weapons, as Smaug doesn't emit enough consistent heat for a heat seeker.
However, that would be wasteful. Instead, negotiate with Smaug. He's no dummy and he has talents that could be quite beneficial. If he joins in with the allied forces, he could provide air cover for the invasion of Mordor. Unlike the Nazgul, Smaug breathes fire, so he could incinerate them in flight... burn their wings off and watch them drop. Mmmm... broiled nazgul... tastes like chicken.
Why would Smaug do that? Because the Allies can provide the financial knowledge to send his net worth though the roof.
Imagine what Smaug could get if he were to put all of that gold into a S&P fund. He could easily get 8-10% return on that investment rather than just have it scattered all over the place for burglars to come in and steal. Plus, a diversified portfolio would guard against fluctuations in gold value. One major discovery elsewhere, and Smaug's gold could plummet in value.
Smaug Industries (stock symbol SMG) could revive the gold mines on the Lonely Mountain. With the income from that, he could orchestrate a leveraged buyout of the Moria mines, hire mercenary elves to clear out the orcs, and own the gold market. The dwarves are living a nomadic, vagabond life right now. Negotiate a contract with them: the dwarves provide the mining know-how, Smaug provides the financial backing, both become fabulously wealthy, and no unions to deal with.
Travel in Middle Earth is both very slow and very dangerous. A few Smaugs could offer a fast and safe alternative: Smaug Air. Don't battle your way through Mirkwood, fly over it in comfort. Don't wait for the eagles to show up at the last minute, use our reservation service and schedule your rescue. Watch us incinerate Wargs as the in-flight entertainment. Oh, and let's not forget those fat government contracts for air mail delivery... as long as he doesn't sneeze on the cargo.
Smaug and his relatives have been subject to persecution for ages. He could apply for refugee status. Bring the kids along for an added bonus... the host nation could establish a Screamer act to delay action against refugee dragons with kids.
The best way to deal with Smaug is the capitalist way. Dude, you are really missing out. Work with us, and you can live in immense wealth, without all those messy and dangerous battles. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | It's really not a fair fight. The dragon is outnumbered, out-gunned, and out-ranged. The MEU's Harrier jets can easily defeat it in a dogfight; the Viper attack helicopters can probably do the same. The Abrams, LAV-25, and AAV all have guns that can punch through the dragon's armor, and it's a good bet the infantry's anti-aircraft and anti-tank missiles can do the same if they can score a hit.
The goal in fighting the dragon is basically to locate it while taking a minimum of casualties, then call in the heavy weapons to finish it off. Since you know there's only one dragon, you can split up your forces to degrees that would be suicidal against a more numerous opponent -- the armored vehicles would operate individually to provide support for scouting forces.
Ideally, your scouts would find the dragon while it's asleep and call in an airstrike to finish it off; if they find it while it's awake, they'd call in the nearest heavy weapons, with air support as a backup. | **Wrong tool for the job**
So, this dragon has no chance against a moderm military, but then you wouldn't want to send the military against such creature. If he is not inteligent then you will probably need to devise a conservation plan to stop the creature from being hunted to death, since any animal like that will probably have a big impact on the whole enviroment.
Just think about wolves, many people seem them as these terrible predators and feel justified in hunting them, but after the wolves ar killed off you will have a super polutation of deer and other herbivores in the region that will destroy the ecological balance of the region.
Another good example are lions in Africa, seem for many years as a plague, but now there are many programs to conserve them.
However! If the animal is intelligent, you will want to bring in the historians, this creature supposedly has existed for a very long time and any historian will give his left arm just to be able to ask a few questions to the dragon. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | I was a Marine Infantryman and I think people have zero idea how truly powerful modern weaponry is. In movies fighter jets float lazily in at a monster firing point blank until he swats it down like a bird. In reality those jets are going to be at 30,000 feet moving at twice the speed of sound carrying enough ordinance to level several city blocks which they can target and fire from several miles away.
For example, the TOW 2 bravo Aero missile (my weapon specialization). It was a 68 pound guided missile with a range of 4,500 meters (just under 3 miles.) The missile covers that maximum distance in 26 seconds. Thats a 68 pound guided missile with a shaped charge that can penetrate meters of concrete or several inches of hardened homogenous steel moving faster than a lot of handgun bullets. The TOW is considered a small and somewhat slow missile, and is also somewhat obsolete since it needs to be manually steered and nwer stuff like the javelin are fire and forget.
So yeah. A single Marine could mess up yer dragon good from several miles away and not even have to get out of his gun turret seat. | How would you beat him? With a stick, while he slept. With the number of resources available to an MEU, they could take shifts. Given the dragon's speed he could be kept under constant attack. With no chance to rest, he would be easy prey in a couple days. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | I was a Marine Infantryman and I think people have zero idea how truly powerful modern weaponry is. In movies fighter jets float lazily in at a monster firing point blank until he swats it down like a bird. In reality those jets are going to be at 30,000 feet moving at twice the speed of sound carrying enough ordinance to level several city blocks which they can target and fire from several miles away.
For example, the TOW 2 bravo Aero missile (my weapon specialization). It was a 68 pound guided missile with a range of 4,500 meters (just under 3 miles.) The missile covers that maximum distance in 26 seconds. Thats a 68 pound guided missile with a shaped charge that can penetrate meters of concrete or several inches of hardened homogenous steel moving faster than a lot of handgun bullets. The TOW is considered a small and somewhat slow missile, and is also somewhat obsolete since it needs to be manually steered and nwer stuff like the javelin are fire and forget.
So yeah. A single Marine could mess up yer dragon good from several miles away and not even have to get out of his gun turret seat. | It's really not a fair fight. The dragon is outnumbered, out-gunned, and out-ranged. The MEU's Harrier jets can easily defeat it in a dogfight; the Viper attack helicopters can probably do the same. The Abrams, LAV-25, and AAV all have guns that can punch through the dragon's armor, and it's a good bet the infantry's anti-aircraft and anti-tank missiles can do the same if they can score a hit.
The goal in fighting the dragon is basically to locate it while taking a minimum of casualties, then call in the heavy weapons to finish it off. Since you know there's only one dragon, you can split up your forces to degrees that would be suicidal against a more numerous opponent -- the armored vehicles would operate individually to provide support for scouting forces.
Ideally, your scouts would find the dragon while it's asleep and call in an airstrike to finish it off; if they find it while it's awake, they'd call in the nearest heavy weapons, with air support as a backup. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | The firepower of a MEU could dispose of Smaug quite easily, although they'd need to use visually guided weapons, as Smaug doesn't emit enough consistent heat for a heat seeker.
However, that would be wasteful. Instead, negotiate with Smaug. He's no dummy and he has talents that could be quite beneficial. If he joins in with the allied forces, he could provide air cover for the invasion of Mordor. Unlike the Nazgul, Smaug breathes fire, so he could incinerate them in flight... burn their wings off and watch them drop. Mmmm... broiled nazgul... tastes like chicken.
Why would Smaug do that? Because the Allies can provide the financial knowledge to send his net worth though the roof.
Imagine what Smaug could get if he were to put all of that gold into a S&P fund. He could easily get 8-10% return on that investment rather than just have it scattered all over the place for burglars to come in and steal. Plus, a diversified portfolio would guard against fluctuations in gold value. One major discovery elsewhere, and Smaug's gold could plummet in value.
Smaug Industries (stock symbol SMG) could revive the gold mines on the Lonely Mountain. With the income from that, he could orchestrate a leveraged buyout of the Moria mines, hire mercenary elves to clear out the orcs, and own the gold market. The dwarves are living a nomadic, vagabond life right now. Negotiate a contract with them: the dwarves provide the mining know-how, Smaug provides the financial backing, both become fabulously wealthy, and no unions to deal with.
Travel in Middle Earth is both very slow and very dangerous. A few Smaugs could offer a fast and safe alternative: Smaug Air. Don't battle your way through Mirkwood, fly over it in comfort. Don't wait for the eagles to show up at the last minute, use our reservation service and schedule your rescue. Watch us incinerate Wargs as the in-flight entertainment. Oh, and let's not forget those fat government contracts for air mail delivery... as long as he doesn't sneeze on the cargo.
Smaug and his relatives have been subject to persecution for ages. He could apply for refugee status. Bring the kids along for an added bonus... the host nation could establish a Screamer act to delay action against refugee dragons with kids.
The best way to deal with Smaug is the capitalist way. Dude, you are really missing out. Work with us, and you can live in immense wealth, without all those messy and dangerous battles. | **Wrong tool for the job**
So, this dragon has no chance against a moderm military, but then you wouldn't want to send the military against such creature. If he is not inteligent then you will probably need to devise a conservation plan to stop the creature from being hunted to death, since any animal like that will probably have a big impact on the whole enviroment.
Just think about wolves, many people seem them as these terrible predators and feel justified in hunting them, but after the wolves ar killed off you will have a super polutation of deer and other herbivores in the region that will destroy the ecological balance of the region.
Another good example are lions in Africa, seem for many years as a plague, but now there are many programs to conserve them.
However! If the animal is intelligent, you will want to bring in the historians, this creature supposedly has existed for a very long time and any historian will give his left arm just to be able to ask a few questions to the dragon. |
59,919 | First off -- this differs from our [history](https://worldbuilding.stackexchange.com/questions/21618/from-which-point-on-would-including-a-dragon-on-one-side-of-a-historical-battle) [questions](https://worldbuilding.stackexchange.com/questions/21719/dragon-vs-antiaircraft-artillery) on this topic in that we are dealing with *modern* assets here, not historical ones, and from [this question](https://worldbuilding.stackexchange.com/questions/19140/how-would-a-dragon-be-used-in-a-modern-military) in that our military units are out to slay the dragon, not recruit and utilize him. Furthermore, we are discussing tactics and strategy here, not the level of technology needed.
In the left corner, we have our big, scaly, fire-breathing, livestock-chomping dragon. He's been kept alive throughout history by scales that can stop blade, arrow, bolt, and anti-personnel bullet, up to a ordinary slug of 23mm caliber and armor-piercing slugs short of 12.7mm caliber. He has human-like intelligence (if not better) to go with nasty, albeit short-ranged, fire breath and quite the appetite, as well as the ability to extract energy efficiently from most organic carbon sources (so he can dine on trees just as well as cows or princesses). His flight envelope is similar to a small aircraft: +4 to -2g, with a max cruise speed of 75 knots and a max dive speed of 150 knots. He also needs to sleep at least 4 hours per 24 hours of wakefulness, and cannot do so on the wing.
In the right corner, we have a [Marine Expeditionary Unit](https://en.wikipedia.org/wiki/Marine_expeditionary_unit) -- the smallest complete combined-arms fighting force in the United States Marine Corps. This MEU has but has one mission -- slay the dragon, and they must do it on their own (i.e. no reinforcement units allowed). Our modern-day dragonslayers do have an amphibious assault ship's worth of ammunition, fuel, and supplies available to them, as well as the ability to obtain food from the land and purify the water sources available to them, and utilize any liquid fuel stores that have been left behind in the land.
Furthermore, this battle is taking place over mixed terrain (wide elevation, temperature, and moisture variations) in a 500km square area. Basic roads are the only fixed transport assets available on it (i.e. no divided highways, aerodromes, or dedicated port facilities), and the civilian population is sparse (most of them have fled the dragon's ravages already), so civilian casualties are not a major concern.
How can our MEU's commander best accomplish his mission? (I.e. most expeditiously and/or with the fewest casualties) | 2016/10/29 | [
"https://worldbuilding.stackexchange.com/questions/59919",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3097/"
] | Air-launched missiles.
A dragon can't outrun or evade [the missiles that a Marine helicopter or tiltrotor can carry](https://en.wikipedia.org/wiki/AGM-114_Hellfire). | How would you beat him? With a stick, while he slept. With the number of resources available to an MEU, they could take shifts. Given the dragon's speed he could be kept under constant attack. With no chance to rest, he would be easy prey in a couple days. |
58,002,531 | Running my Python 3.7.4 app that uses `tensorflow` v1.14.0 causes a large list of deprecation warnings to appear. The following code clears up most of it.
```
try:
from tensorflow.python.util import module_wrapper as deprecation
except ImportError:
from tensorflow.python.util import deprecation_wrapper as deprecation
deprecation._PER_MODULE_WARNING_LIMIT = 0
```
However, none of the warnings are removed. Updating `tensorflow` to v2.x is not an option right now.
How can these messages be removed?
**Warning messages:**
```
/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint16 = np.dtype([("qint16", np.int16, 1)])
/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_quint16 = np.dtype([("quint16", np.uint16, 1)])
/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint32 = np.dtype([("qint32", np.int32, 1)])
/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
np_resource = np.dtype([("resource", np.ubyte, 1)])
WARNING:tensorflow:From /Users/x/foo/dnnlib/tflib/tfutil.py:34: The name tf.Dimension is deprecated. Please use tf.compat.v1.Dimension instead.
WARNING:tensorflow:From /Users/x/foo/dnnlib/tflib/tfutil.py:74: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.
WARNING:tensorflow:From /Users/x/foo/dnnlib/tflib/tfutil.py:128: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.
``` | 2019/09/19 | [
"https://Stackoverflow.com/questions/58002531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You can ignore all "FutureWarning" warnings by putting the following code at the beginning of your scripts ([source](https://machinelearningmastery.com/how-to-fix-futurewarning-messages-in-scikit-learn/)):
```
from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
```
Please note that you have to put those lines before any other imports as some of those might already import dependencies on their own. | Overview
--------
The issue that brought me here was actually for a recent numpy deprecation warning coming from code in `tensorboard`, but I expect that the principles comes to bear on the question in the OP as well.
Approach
--------
Adding the following before any `tensorflow` imports will suppress developer-directed [`DeprecationWarnings`](https://docs.python.org/3/library/exceptions.html#DeprecationWarning) arising from [that specific module](https://stackoverflow.com/a/63980460/3780389) (DeprecationWarnings are ignored by default, but they might be turned on, e.g., by QA tools; use [`FutureWarnings`](https://docs.python.org/3/library/exceptions.html#FutureWarning) instead if the deprecation warnings are directed at end-users):
```py
from warnings import filterwarnings # noqa
warnings.filterwarnings(action='ignore',
category=DeprecationWarning,
module='tensorflow') # noqa
```
Notes
-----
* If you are developing a multi-file package, you might considering putting the filter code at the top of your `__init__.py` file (after any `__future__` imports).
* Auto-formatters (like `black` or `autopep8`) may push these lines *after* the offending import. Since I'm use an autopep8-on-save trigger in VSCode, I also needed to add the `# noqa` to the import and filter lines so that they were not moved (see [this post](https://stackoverflow.com/a/57067521/3780389)). To avoid needing to squelch linting error for the following imports, another option is to move the warning filtering lines to a separate python file and then import that from `__init__.py` (see [this post](https://stackoverflow.com/a/40257363/3780389)).
* (Of course, for my `tensorboard` issue, I used `module='tensorboard'` instead.) |
59,409,141 | I have a yaml-file like this:
```
object_0:
- v: 1.55
- t_x: 110.281
- t_y: 367.959
- traj_const_dist: 1.0
- trajectory: [[117, 356], [116, 356], [115, 356], [114, 356], [113, 356], [113, 357], [113, 358], [113, 359], [113, 360]]
```
The parameter `trajectory` is defined like this: `std::vector<std::pair<double,double>> trajectory_;`
When I read in the parameters:
```
ros::NodeHandle nh_;
nh_.param<std::vector<std::pair<double, double>>>(obj_topic, trajectory_, std::vector<std::pair<double, double>>());
```
... I get this error:
```
error: no matching function for call to ‘ros::NodeHandle::getParam(const string&, std::vector<std::pair<double, double> >&) const’
if (getParam(param_name, param_val))
```
It would help if you give me suggestions. Is the data type `std::vector<std::pair<double, double>>>` not correct?
(Sorry, it is a huge project and difficult to make a small and compilable example. I will do a small one if you insist on it.) | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4355878/"
] | It can be done by making use of XmlRpc::XmlRpcValue
Assuming the parameters in yaml file already loaded to parameter server,the following code snippet can be used:
```
XmlRpc::XmlRpcValue trajectory;
nh_.getParam("/param_name", trajectory);
/*To ensure the reading will happen if the data is provided in right format*/
if (trajectory.getType() == XmlRpc::XmlRpcValue::TypeArray)
{
for (int i = 0; i < trajectory.size(); i++)
{
XmlRpc::XmlRpcValue trajectoryObject = trajectory[i];
/*Individual coordinate points in trajectory*/
int xCoordinate = trajectoryObject[0];
int yCoordinate = trajectoryObject[1];
ROS_INFO("The %d th coordinate values are : %d and %d", ixCoordinate, yCoordinate);
}
}
``` | According to the [documentation](http://docs.ros.org/melodic/api/roscpp/html/classros_1_1NodeHandle.html) there is not any function `getParam` to get vector of pairs or vector of vectors. So, you need to change your YAML file and use only existing functions `getParam`. |
96,659 | I'm making a C++ game engine for entertainment and am using OpenGL to render my stuff. I made a batch renderer that was able to render 50K sprites with 300 FPS (untextured). My old setup that was able to run with 300 FPS was the following:
I had a class called `Renderable2D`, which held everything:
```
class Renderable2D
{
protected:
vec3f m_Position;
vec2f m_Size;
vec4f m_Color;
const Texture2D * m_Texture;
std::vector<vec2f> m_TexCoords;
protected:
Renderable2D() { }
public:
Renderable2D(vec3f position, vec2f size, vec4f color)
: m_Position(position), m_Size(size), m_Color(color), m_Texture(nullptr)
{
m_TexCoords.push_back(vec2f(0, 0));
m_TexCoords.push_back(vec2f(0, 1));
m_TexCoords.push_back(vec2f(1, 1));
m_TexCoords.push_back(vec2f(1, 0));
}
virtual ~Renderable2D()
{ }
inline virtual void Submit(Renderer2D * renderer) const
{
renderer->Submit(*this);
}
inline const vec3f& GetPosition() const { return m_Position; }
inline const vec2f& GetSize() const { return m_Size; }
inline const vec4f& GetColor() const { return m_Color; }
inline const std::vector<vec2f>& GetTexCoords() const { return m_TexCoords; }
inline const GLuint GetTextureID() const { return (m_Texture == nullptr ? 0 : m_Texture->GetTextureID()); }
};
```
Basically, this was a class that held everything: the texture coordinates (if it had any), the color, position and size. My batch renderer had a method to draw any `Renderable2D` based on this class:
```
void BatchRenderer::Submit(const Renderable2D& renderable)
{
const vec3f& position = renderable.GetPosition();
const vec2f& size = renderable.GetSize();
const unsigned int color = renderable.GetColor();
const std::vector<vec2f>& texCoords = renderable.GetTexCoords();
const GLuint tid = renderable.GetTextureID();
float ts = 0.0f;
if (tid > 0)
{
bool found = false;
for (unsigned int i = 0; i < m_TextureSlots.size(); i++)
{
if (m_TextureSlots[i] == tid)
{
ts = (float)(i + 1);
found = true;
break;
}
}
if (!found)
{
if (m_TextureSlots.size() >= 32)
{
End();
Flush();
Begin();
}
m_TextureSlots.push_back(tid);
ts = (float)(m_TextureSlots.size());
}
}
Maths::vec3f _tpos = *m_TransformationBack * position;
m_Buffer->Position = _tpos;
m_Buffer->TexCoord = texCoords[0];
m_Buffer->TexID = ts;
m_Buffer->Color = color;
m_Buffer++;
_tpos.y += size.y;
m_Buffer->Position = _tpos;
m_Buffer->TexCoord = texCoords[1];
m_Buffer->TexID = ts;
m_Buffer->Color = color;
m_Buffer++;
_tpos.x += size.x;
m_Buffer->Position = _tpos;
m_Buffer->TexCoord = texCoords[2];
m_Buffer->TexID = ts;
m_Buffer->Color = color;
m_Buffer++;
_tpos.y -= size.y;
m_Buffer->Position = _tpos;
m_Buffer->TexCoord = texCoords[3];
m_Buffer->TexID = ts;
m_Buffer->Color = color;
m_Buffer++;
m_IndexCount += 6;
}
```
I wanted to make this a bit nicer and faster, so I created subclasses for `renderable2D`. `Renderable2D` only had it's position and size. `Rectangle` (inherited from `Renderable2D`) had color too, and Sprite had a texture and texture coords. I think this is a bit more categorized and makes a simple colored rectangle less heavily-weighted (no texture coords). Then I overrode the `Renderable2D`'s submit method for both the rectangle and the sprite and created (which I thought were) optimized submit methods for my renderer. I've kept the original one, but overloaded the method, so I had:
```
void BatchRenderer::Submit(const vec2f& position, const vec2f& size, unsinged int color);
void BatchRenderer::Submit(const vec2f& position, const vec2f& size, GLuint textureID, const std::vector<vec2f>& textureCoords);
```
This way I didn't need to assign everything for `m_Buffer` and I could eliminate the `if` statement (`if (tid > 0)`) because now I knew when the renderable used a texture. I thought this would speed up the code, but it slowed it down to about half its speed (testing conditions were the same for the unoptimized and "optimized" code). Why did this refactor (which I think should speed up the code) slow it down? Less assignments, one less `if` statement, smaller data structures.
* `m_Buffer`: It's actually a vertex buffer object, it's named simply buffer because it's not only storing vertices, but colors, texture coordinates and texture IDs too. The `Submit` method basically writes mapped data to this buffer.
* `ts`: It stands for texture slot, yes it's a really bad naming, I should rename it. It's a float because OpenGL actually likes float more in a float buffer than an integer.
* `m_IndexCount`: The size of the index buffer. (Index of vertices)
* `Renderable2D`: I have a Submit method that just passes itself to the renderer. It's virtual on purpose. You don't send sprites directly to the renderer, because there are `Rendereable2D`s called `Group`s. They override the `Submit` method and sends their children instead.
* `m_Texture`: `Renderable2D` sets it as `nullptr` for now. There's a subclass called `Sprite` that's basically a constructor which sets the texture to the passed parameter. And my plan is to clean up `Renderable2D` from the things it doesn't need like texture, because sprite needs it really. | 2015/07/12 | [
"https://codereview.stackexchange.com/questions/96659",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/77766/"
] | A couple things I would have done differently, plus some other broader advices:
* `Renderable2D` seems to me is representing a single sprite, each sprite being a quadrilateral. In that case, you really don't need a variable amount of texture coordinates, but rather just 4. No need to use a `std::vector` in this case and force a heap allocation. Just use a plain array of `vec2f` or a [`std::array`](http://en.cppreference.com/w/cpp/container/array) if you are open to using C++11.
* You don't need to add `inline` when the method is defined directly inside the class body in the header file. That serves no practical purpose and only makes the code more verbose.
* Always favor the C++-style casts. [`static_cast`](http://en.cppreference.com/w/cpp/language/static_cast) and friends will provide better compiler diagnostics if you attempt some unsafe cast.
Two bits of personal style:
* It is a common convention to name user defined types using `PascalCase`, like you already do, and variables and functions with `camelCase`, to differentiate both kinds of things. Actually, the idea is to name anything that can have its memory address take with `camelCase` and reserve the first letter capitalized for types.
* I find it better to place the **public** interface of a class first in the header file, to give it more emphasis. That's usually the part you and users of your code will be looking at more often. **protected** and **private** are implementation details, so shouldn't need to stand out as much. | I concur with @glampert's suggestions. I have a few questions of my own.
**Naming**
What is the purpose of the `Submit()` method? What is it submitting? (I don't see any calls to OpenGL to submit vertex attribute data, for example.) Also, it appears to update the value of an internal pointer, `m_Buffer`. What is it a buffer of? Its name should reflect what it represents. Is it vertex data? If so, name it `m_VertexBuffer` or `m_SpriteBuffer` or whatever would be appropriate.
**Types**
In the `Submit()` method what is the purpose of `ts`? It's a `float` but you eventually assign `mBuffer->TexId` to the value of `ts`. But texture IDs are `GLuints`. Also, it appears to be an index in the array of texture slots, and not an actual texture ID as OpenGL knows it. If it's not actually the ID returned by `glGenTextures()` or some equivalent, I would not name it `TexID`. Maybe `TextureIndex` instead? And it's not likely a `float`, so make `ts` be the correct type, whether it's `GLuint` or just an `unsigned int`.
**Repetition**
You have almost identical code written 4 times:
```
m_Buffer->Position = _tpos;
m_Buffer->TexCoord = texCoords[0];
m_Buffer->TexID = ts;
m_Buffer->Color = color;
m_Buffer++;
```
Why not make that into a function and call it 4 times with the appropriate arguments instead of writing it out by hand 4 times?
**Miscellaneous**
What does the last line of `Submit()` do?
```
m_IndexCount += 6;
```
The code above it appears to be adding 4 entries to the m\_Buffers list. Why does the index count increase by 6? What is its purpose?
In `Renderable2D`, you have a `Submit()` method that you pass a `Renderer2D` to. It simply calls `renderer->Submit(*this);`. That seems like a pointless method. Why doesn't the caller just call `renderer->Submit(*renderable);` and save 1 step?
**Memory**
How does one set `Renderable2D::m_Texture`? I see how to get it, but it doesn't get set in the constructor, it's `protected`, and there's no accessor to set it. (It's also never freed, which might be OK if another object owns it. If so, you might consider using a `std::shared_ptr` if you're in C++11.) |
5,150,311 | I'm a relative newcomer to cocoa & programming for the ipad.
I've built an app that has a split view controller. In the detail view is a toolbar with a button on it. When the button is pressed, the split view controller is removed from the superview, and another view is put in its place. A toolbar button on this new view removes the view and puts the split view back. Works great... except when the ipad is rotated while the second view is visible. When the user returns to the split view, it's displayed as it was before the rotation.
The split view and all the sub views are set to autoresize=yes, and return yes when they receive the autorotatetointerfaceorientation message.
I'm guessing I need to tell the split view and its sub views to resize themselves when I add it as a subview to the window.
Thanks
Chris | 2011/03/01 | [
"https://Stackoverflow.com/questions/5150311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578847/"
] | If you are just after the delegates that have a void return type you could do the following:
```
public static bool IsActionDelegate(Type sourceType)
{
if(sourceType.IsSubclassOf(typeof(MulticastDelegate)) &&
sourceType.GetMethod("Invoke").ReturnType == typeof(void))
return true;
return false;
}
```
This would not distinguish between `Action` and `MethodInvoker` (or other void delegates for that matter) though. As other answers suggest you could examine the type name, but that kinda smells ;-)
It would help if you could clarify for what reason you want to identify `Action` delegates, to see which approach would work best. | This seems to work:
```
private static bool IsActionDelegate(this Type source)
{
var type = source.Name;
return source.Name.StartsWith("System.Action");
}
```
Example:
```
public static class Test
{
public static bool IsActionDelegate(this Type source)
{
var type = source.Name;
return source.Name.StartsWith("Action");
}
}
class Program
{
static void Main(string[] args)
{
Action<string> one = s => { return; };
Action<int, string> two = (i, s) => { return; };
Func<int, string> function = (i) => { return null; };
var single = one.GetType().IsActionDelegate();
var dueces = two.GetType().IsActionDelegate();
var func = function.GetType().IsActionDelegate();
}
}
```
Single and dueces are true. func is false |
5,150,311 | I'm a relative newcomer to cocoa & programming for the ipad.
I've built an app that has a split view controller. In the detail view is a toolbar with a button on it. When the button is pressed, the split view controller is removed from the superview, and another view is put in its place. A toolbar button on this new view removes the view and puts the split view back. Works great... except when the ipad is rotated while the second view is visible. When the user returns to the split view, it's displayed as it was before the rotation.
The split view and all the sub views are set to autoresize=yes, and return yes when they receive the autorotatetointerfaceorientation message.
I'm guessing I need to tell the split view and its sub views to resize themselves when I add it as a subview to the window.
Thanks
Chris | 2011/03/01 | [
"https://Stackoverflow.com/questions/5150311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578847/"
] | If you are just after the delegates that have a void return type you could do the following:
```
public static bool IsActionDelegate(Type sourceType)
{
if(sourceType.IsSubclassOf(typeof(MulticastDelegate)) &&
sourceType.GetMethod("Invoke").ReturnType == typeof(void))
return true;
return false;
}
```
This would not distinguish between `Action` and `MethodInvoker` (or other void delegates for that matter) though. As other answers suggest you could examine the type name, but that kinda smells ;-)
It would help if you could clarify for what reason you want to identify `Action` delegates, to see which approach would work best. | These are distinct types with nothing in common but their name. The only semi-reasonable shortcut I can think of:
```
public static bool IsActionDelegate( this Type source )
{
return source.FullName.StartsWith("System.Action");
}
```
Certainly not fail-safe, but whomever declares his own types in the System namespace deserves some pain and suffering. |
5,150,311 | I'm a relative newcomer to cocoa & programming for the ipad.
I've built an app that has a split view controller. In the detail view is a toolbar with a button on it. When the button is pressed, the split view controller is removed from the superview, and another view is put in its place. A toolbar button on this new view removes the view and puts the split view back. Works great... except when the ipad is rotated while the second view is visible. When the user returns to the split view, it's displayed as it was before the rotation.
The split view and all the sub views are set to autoresize=yes, and return yes when they receive the autorotatetointerfaceorientation message.
I'm guessing I need to tell the split view and its sub views to resize themselves when I add it as a subview to the window.
Thanks
Chris | 2011/03/01 | [
"https://Stackoverflow.com/questions/5150311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578847/"
] | If you are just after the delegates that have a void return type you could do the following:
```
public static bool IsActionDelegate(Type sourceType)
{
if(sourceType.IsSubclassOf(typeof(MulticastDelegate)) &&
sourceType.GetMethod("Invoke").ReturnType == typeof(void))
return true;
return false;
}
```
This would not distinguish between `Action` and `MethodInvoker` (or other void delegates for that matter) though. As other answers suggest you could examine the type name, but that kinda smells ;-)
It would help if you could clarify for what reason you want to identify `Action` delegates, to see which approach would work best. | ```
static Type[] _actionTypes = new[]{
typeof(Action),
typeof(Action<>),
typeof(Action<,>),
typeof(Action<,,>),
typeof(Action<,,,>),
typeof(Action<,,,,>),
typeof(Action<,,,,,>),
typeof(Action<,,,,,,>),
typeof(Action<,,,,,,,>),
typeof(Action<,,,,,,,,>),
typeof(Action<,,,,,,,,,>),
typeof(Action<,,,,,,,,,,>),
typeof(Action<,,,,,,,,,,,>),
typeof(Action<,,,,,,,,,,,,>),
typeof(Action<,,,,,,,,,,,,,>),
typeof(Action<,,,,,,,,,,,,,,>),
typeof(Action<,,,,,,,,,,,,,,,>)
};
private static bool IsAction(Delegate d)
{
return d != null && Array.IndexOf(_actionTypes, d.GetType()) != -1;
}
``` |
12,926,178 | I want to get the current date day/month/year min:sec in Android so I have used the follow code
```
String data="";
Calendar c = Calendar.getInstance();
data=c.getTime().toGMTString();
```
But Eclipse notify me that the method `.toGMTString();` is deprecated.
How could I get the current date as formatted String avoiding the use of this deprecated method? | 2012/10/17 | [
"https://Stackoverflow.com/questions/12926178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1145744/"
] | From the Android documentation:
>
> This method is deprecated.
>
> use [`DateFormat`](http://developer.android.com/reference/java/text/DateFormat.html)
>
>
>
Since the GMT string is represented as `22 Jun 1999 13:02:00 GMT`, we can use `SimpleDateFormat` (subclass of the abstract `DateFormat`) like so:
```
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
String asGmt = df.format(c.getTime()) + " GMT";
```
~~Might want to double-check that format, but this'll get you started.~~ Have a look at [this IDEOne code](http://ideone.com/8y5xn). | The method `toGMTString()` from the type Date is deprecated.
you can check [this](http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) for different types of date formations.
In your case use
```
SimpleDateFormat dfDate = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss");
String data="";
Calendar c = Calendar.getInstance();
data=dfDate.format(c.getTime());
System.out.println(data);//==========> 17/Oct/2012 08:36:52
```
If you want to print month number instead of month name
use
```
SimpleDateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String data="";
Calendar c = Calendar.getInstance();
data=dfDate.format(c.getTime());
System.out.println(data);//==========> 17/10/2012 08:36:52
``` |
37,019,877 | I was wondering how to use **Laravels softdelete** with something like MySql **foreign key restrict** constraints.
Is there already something build into the framework? Softdelete is already working but I need some kind of validation to related models. e.g. an error message to the user "You cannot delete this item because it hast 5 related records"
Thanks, | 2016/05/04 | [
"https://Stackoverflow.com/questions/37019877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272741/"
] | There's is no build in solution for "unpluging" DB relation on soft delete.
What You can do for example is to use observers ([event listener](https://laravel.com/docs/5.2/events)) or use [eloquent model events](https://laravel.com/docs/5.1/eloquent#events) for example `deleting`/`deleted` like:
```
public function boot()
{
User::deleted(function ($user) {
if ($user->deleted_at) {
// here You have to unplug all the dependencies
}
});
}
``` | Yes, in Laravel they have soft delete models.To use this `Illuminate\Database\Eloquent\SoftDeletes` trait on the model and add the `deleted_at` column to your `$dates` property.
They also have their Querying Soft Deleted Models.You can choose anyone.
You can get all documentation about this in **[here.](https://laravel.com/docs/5.1/eloquent#deleting-models)** |
2,126,738 | i have an uiscrollview and i add one by one uiimageviews but when i add more than 40 objects i have problem with memory i guess and the app crashes...what should i do? i am trying to make an app like photo viewer from apple! Help please!
i do not want thumbnais i just want to show the next image when the user flick from one to another but i have to unload the previous image and show the next one
i remove the previous like this
```
UIImageView l;
l=[[scroll subviews] objectAtIndex:0];
[l removeFromSuperview];
l=nil;
```
and then i add the next one like this
```
[scroll insertSubview:imageView atIndex:counter];
```
but i see a black background no image
please help! | 2010/01/24 | [
"https://Stackoverflow.com/questions/2126738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235532/"
] | The best way to do this is to load a few of the images at a time into a table view. In each cell of the table, put three thumbnails. You'll need to make a custom cell. That way, the table cells will be de-queued and the memory re-used. Check the Facebook Three20 project, I think they've implemented it like this, so you'll have some code to work with.
<http://joehewitt.com/post/the-three20-project/> | Ask yourself, do you *really* need to load all 100 images into memory? Why not just load a few images at a time in the background, depending on what image the user has scrolled to? |
2,126,738 | i have an uiscrollview and i add one by one uiimageviews but when i add more than 40 objects i have problem with memory i guess and the app crashes...what should i do? i am trying to make an app like photo viewer from apple! Help please!
i do not want thumbnais i just want to show the next image when the user flick from one to another but i have to unload the previous image and show the next one
i remove the previous like this
```
UIImageView l;
l=[[scroll subviews] objectAtIndex:0];
[l removeFromSuperview];
l=nil;
```
and then i add the next one like this
```
[scroll insertSubview:imageView atIndex:counter];
```
but i see a black background no image
please help! | 2010/01/24 | [
"https://Stackoverflow.com/questions/2126738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235532/"
] | Ask yourself, do you *really* need to load all 100 images into memory? Why not just load a few images at a time in the background, depending on what image the user has scrolled to? | There is exactly an apple sample code that do what you want. Look for the PageControl sample, it is already implemented. Basically the slider gets the image controller from an array of controllers; among other things, when the scroller changes to the previous or next image, controllers are added and removed from this array dynamically to keep memory footprint low.
Have a look at the sample code, it is quite simple.
Hope it helps. |
2,126,738 | i have an uiscrollview and i add one by one uiimageviews but when i add more than 40 objects i have problem with memory i guess and the app crashes...what should i do? i am trying to make an app like photo viewer from apple! Help please!
i do not want thumbnais i just want to show the next image when the user flick from one to another but i have to unload the previous image and show the next one
i remove the previous like this
```
UIImageView l;
l=[[scroll subviews] objectAtIndex:0];
[l removeFromSuperview];
l=nil;
```
and then i add the next one like this
```
[scroll insertSubview:imageView atIndex:counter];
```
but i see a black background no image
please help! | 2010/01/24 | [
"https://Stackoverflow.com/questions/2126738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235532/"
] | The best way to do this is to load a few of the images at a time into a table view. In each cell of the table, put three thumbnails. You'll need to make a custom cell. That way, the table cells will be de-queued and the memory re-used. Check the Facebook Three20 project, I think they've implemented it like this, so you'll have some code to work with.
<http://joehewitt.com/post/the-three20-project/> | Don't do it that way.
If you want to display a 100 small thumbnails, resize them first with core graphics. Then they take up much less memory when you display 100 images at once.
If you want to display a 100 large images but only one is visible at a time, have 1 or 2 image views that load up the current and next images, and animate them in a clever way to make it look an endless stream. You can still use a scrollView, just monitor it's position and position your image views appropriately. |
2,126,738 | i have an uiscrollview and i add one by one uiimageviews but when i add more than 40 objects i have problem with memory i guess and the app crashes...what should i do? i am trying to make an app like photo viewer from apple! Help please!
i do not want thumbnais i just want to show the next image when the user flick from one to another but i have to unload the previous image and show the next one
i remove the previous like this
```
UIImageView l;
l=[[scroll subviews] objectAtIndex:0];
[l removeFromSuperview];
l=nil;
```
and then i add the next one like this
```
[scroll insertSubview:imageView atIndex:counter];
```
but i see a black background no image
please help! | 2010/01/24 | [
"https://Stackoverflow.com/questions/2126738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235532/"
] | Don't do it that way.
If you want to display a 100 small thumbnails, resize them first with core graphics. Then they take up much less memory when you display 100 images at once.
If you want to display a 100 large images but only one is visible at a time, have 1 or 2 image views that load up the current and next images, and animate them in a clever way to make it look an endless stream. You can still use a scrollView, just monitor it's position and position your image views appropriately. | There is exactly an apple sample code that do what you want. Look for the PageControl sample, it is already implemented. Basically the slider gets the image controller from an array of controllers; among other things, when the scroller changes to the previous or next image, controllers are added and removed from this array dynamically to keep memory footprint low.
Have a look at the sample code, it is quite simple.
Hope it helps. |
2,126,738 | i have an uiscrollview and i add one by one uiimageviews but when i add more than 40 objects i have problem with memory i guess and the app crashes...what should i do? i am trying to make an app like photo viewer from apple! Help please!
i do not want thumbnais i just want to show the next image when the user flick from one to another but i have to unload the previous image and show the next one
i remove the previous like this
```
UIImageView l;
l=[[scroll subviews] objectAtIndex:0];
[l removeFromSuperview];
l=nil;
```
and then i add the next one like this
```
[scroll insertSubview:imageView atIndex:counter];
```
but i see a black background no image
please help! | 2010/01/24 | [
"https://Stackoverflow.com/questions/2126738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235532/"
] | The best way to do this is to load a few of the images at a time into a table view. In each cell of the table, put three thumbnails. You'll need to make a custom cell. That way, the table cells will be de-queued and the memory re-used. Check the Facebook Three20 project, I think they've implemented it like this, so you'll have some code to work with.
<http://joehewitt.com/post/the-three20-project/> | There is exactly an apple sample code that do what you want. Look for the PageControl sample, it is already implemented. Basically the slider gets the image controller from an array of controllers; among other things, when the scroller changes to the previous or next image, controllers are added and removed from this array dynamically to keep memory footprint low.
Have a look at the sample code, it is quite simple.
Hope it helps. |
74,251,321 | '
```
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users/mihirshah/Desktop/api/create_area_api/urls.py", line 3, in <module>
from create_area_api.views import api_create_area
File "/Users/mihirshah/Desktop/api/create_area_api/views.py", line 7, in <module>
class api_create_area(viewsets.ModelViewSet):
File "/Users/mihirshah/Desktop/api/create_area_api/views.py", line 10, in api_create_area
print(queryset.get())
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 646, in get
num = len(clone)
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 376, in __len__
self._fetch_all()
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 87, in __iter__
results = compiler.execute_sql(
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1398, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "accounts_project" does not exist
LINE 1: ...."start_date", "accounts_project"."end_date" FROM "accounts_...
```
`
I typed cmd - "python3 manage.py makemigrations"
and encountered the above error,
* I tried several commands and tried refreshing the database too by changing it,
* Deleted all the .pyc in migrations and **pycache** folder but still getting the same problem.
```
python3 manage.py makemigrations
``` | 2022/10/30 | [
"https://Stackoverflow.com/questions/74251321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760217/"
] | Next.js v13 new image component receives a `fill` prop which is a boolean instead of the old `layout` prop. Example:
```
<Image
src="https://picsum.photos/800/600"
fill
...
/>
```
Also, you can now style the component's underlying image element using `style` or `className`.
Example using Tailwind CSS:
```
<Image
src="some-image-url"
width="0"
height="0"
sizes="100vw"
className="w-full h-auto"
/>
``` | without width and height
```
<Image
// deprecated
// layout="fill"
fill
objectFit="cover"
className="addClassName"
src={src} alt=""
/>
``` |
29,749,375 | I am testing magento with varnish and turpentine extesion. I installed all successfully but when i try to by pass (or flush per second) a block, it is hidden or disapear.
For Example i want to by pass product.info.media block.
My xml configuration for by pass in turpenine\_esi.xml :
```
<catalog_product_view>
<reference name="product.info.media">
<action method="setEsiOptions">
<params>
<access>public</access>
<ttl>1</ttl>
</params>
</action>
</reference>
</catalog_product_view>
```
The block is:
```
<block type="catalog/product_view_media" name="product.info.media" as="media" template="catalog/product/view/media.phtml">
<block type="core/text_list" name="product.info.media.after" as="after" />
</block>
```
is possible to do this? I'm doing wrong?
thanks a lot. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29749375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808475/"
] | Can you try next:
```
<catalog_product_view>
<reference name="product.info.media">
<action method="setEsiOptions">
<params>
<method>esi</method>
<access>public</access>
<scope>page</scope>
<ttl>1</ttl>
</params>
</action>
</reference>
</catalog_product_view>
```
Also check what your block inherit from Mage\_Core\_Block\_Template class. | You're better off putting your ESI options in the *local.xml* for your theme, since *turpentine\_esi.xml* may get overwritten when you update the extension.
Turn on debugging in Turpentine and see if anything interesting shows up in your system.log. Other caching extensions or having other caches enabled can cause errors like these. Also, check for exceptions being generated from your template, those can also cause issues like this. |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You can use 'regex' for this....
```
>>> import re
>>> mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
>>> [re.findall('_(\d+)', i)[0] for i in mylist]
['100', '17', '1000']
``` | Use re
```
import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
pattern = re.compile(r'^event_(\d+).')
mylist = list(map(lambda x : pattern.findall(x)[0] , mylist))
print(mylist)
#['100', '17', '1000']
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You could use `lstrip` for your `event_` and then `split` for `'of'`:
```
res = [i.lstrip('event_').split('of')[0] for i in mylist]
print(res)
['100', '17', '1000']
```
**EDIT**
```
res = [int(i.lstrip('event_').split('of')[0]) for i in mylist]
print(res)
[100, 17, 1000]
``` | You can use 'regex' for this....
```
>>> import re
>>> mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
>>> [re.findall('_(\d+)', i)[0] for i in mylist]
['100', '17', '1000']
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | Using list comprehension and regular expressions:
```
import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]
extracted_list = [re.search("\d+", x).group(0) for x in mylist]
``` | Use `map` function for this:
```
>>> extracted_list = map(lambda x: int(x[:x.find('of')].lstrip('event_')), mylist)
>>> print extracted_list
[100, 17, 1000]
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You could use `lstrip` for your `event_` and then `split` for `'of'`:
```
res = [i.lstrip('event_').split('of')[0] for i in mylist]
print(res)
['100', '17', '1000']
```
**EDIT**
```
res = [int(i.lstrip('event_').split('of')[0]) for i in mylist]
print(res)
[100, 17, 1000]
``` | I also would use re
```
import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
list_id_of = [re.search("event_(\d+)of(\d+)", e).groups() for e in mylist]
[('100', '1000'), ('17', '1000'), ('1000', '1000')]
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You could use `lstrip` for your `event_` and then `split` for `'of'`:
```
res = [i.lstrip('event_').split('of')[0] for i in mylist]
print(res)
['100', '17', '1000']
```
**EDIT**
```
res = [int(i.lstrip('event_').split('of')[0]) for i in mylist]
print(res)
[100, 17, 1000]
``` | Use `map` function for this:
```
>>> extracted_list = map(lambda x: int(x[:x.find('of')].lstrip('event_')), mylist)
>>> print extracted_list
[100, 17, 1000]
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | Use re
```
import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
pattern = re.compile(r'^event_(\d+).')
mylist = list(map(lambda x : pattern.findall(x)[0] , mylist))
print(mylist)
#['100', '17', '1000']
``` | Use `map` function for this:
```
>>> extracted_list = map(lambda x: int(x[:x.find('of')].lstrip('event_')), mylist)
>>> print extracted_list
[100, 17, 1000]
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You can use map:
```
events = map(lambda x: x.split('of')[0], mylist)
map(lambda x: x.split('_')[1], events)
``` | I also would use re
```
import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
list_id_of = [re.search("event_(\d+)of(\d+)", e).groups() for e in mylist]
[('100', '1000'), ('17', '1000'), ('1000', '1000')]
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You could use `lstrip` for your `event_` and then `split` for `'of'`:
```
res = [i.lstrip('event_').split('of')[0] for i in mylist]
print(res)
['100', '17', '1000']
```
**EDIT**
```
res = [int(i.lstrip('event_').split('of')[0]) for i in mylist]
print(res)
[100, 17, 1000]
``` | You can use map:
```
events = map(lambda x: x.split('of')[0], mylist)
map(lambda x: x.split('_')[1], events)
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | I also would use re
```
import re
mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
list_id_of = [re.search("event_(\d+)of(\d+)", e).groups() for e in mylist]
[('100', '1000'), ('17', '1000'), ('1000', '1000')]
``` | Use `map` function for this:
```
>>> extracted_list = map(lambda x: int(x[:x.find('of')].lstrip('event_')), mylist)
>>> print extracted_list
[100, 17, 1000]
``` |
35,222,580 | I have a list of elements like this:
`mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...]`
How can I extract the "number" of the event only and produce another list, in the likes of:
`extracted_list=['100','17','1000',...]`? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35222580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | You can use 'regex' for this....
```
>>> import re
>>> mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000']
>>> [re.findall('_(\d+)', i)[0] for i in mylist]
['100', '17', '1000']
``` | Use `map` function for this:
```
>>> extracted_list = map(lambda x: int(x[:x.find('of')].lstrip('event_')), mylist)
>>> print extracted_list
[100, 17, 1000]
``` |
47,198,661 | I'm building an Eclipse RCP and use an editor written with Xtext. The editor project is not developed by me so I can't just implement the `DSLProposalProvider`.
In my project I want to add some additional content assistant if a concrete model element is used in the editor. The editor offers no Extension Point to extend the `ProposalProvider`, so I'm looking for another possiblity.
I saw this [example](http://kofler.nonblocking.at/2013/07/extending-the-content-assist-capabilities-of-the-eclipse-xml-editor/), but it does not work, since I'm not using the XML editor and I can't match this way to my requirement. I currently have no idea how to go along with this problem and I'm sorry for this bad and unprecise description but I don't even know where to start so I'm open to any kind of help. | 2017/11/09 | [
"https://Stackoverflow.com/questions/47198661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6625339/"
] | You may be interested in the `org.eclipse.jface.fieldassist.ContentProposalAdapter`class
You create an instance of this class that you'll attach to a `org.eclipse.swt.widgets.Text` component for example
To create an instance of `ContentProposalAdapter`you'll need to provide an instance of `TextContentAdapter`and `IContentProposalProvider` that will implement the logic of the content assist plus a few other things (ie what key will trigger the content assist etc)
[This page](https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fjface_fieldassist.htm) in the official eclipse documentation explains how to use those classes | In this usecase correct solution is to add proposals in `ProposalProvider` where you can give proposals based on the value entered in editor. You can also explore [scope provider](http://www.peterfriese.de/writing-xtext-scope-providers-with-xtend/) and check whether it will fit your usecase. |
51,139,657 | I have this [fiddle](http://jsfiddle.net/d63y4bxc/65/) that works nicely. So when I click on one of the list items in the menu I get an alert telling me which item was clicked.
However, in my actual application nothing happens when I click on a list item and to me, it looks exactly the same?
---
```js
// get list of strategies
var $regions = $('#regionList');
$.ajax({
type: 'GET',
url: 'api/Region',
dataType: 'json',
success: function(codes) {
$.each(codes, function(i, code) {
$regions.append('<li id="' + code + '">' + code + '</li>');
});
},
error: function() {
alert("Error loading data! Please try again");
}
});
$("#regionList li").click(function() {
alert('Clicked ' + this.id);
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="dropdown">
<button class="dropbtn">Strategy</button>
<div class="dropdown-content">
<ul id="regionList"></ul>
</div>
</div>
``` | 2018/07/02 | [
"https://Stackoverflow.com/questions/51139657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2730554/"
] | Li elements are created dynamically. hence your way of attaching listener is not applicable for them.
Attach your listener in following ways. it will work.
```
$(document).on('click',"#regionList li",function () {
alert('Clicked ' + this.id);
});
``` | I would bind the click event on the success of the ajax call otherwise you cannot be sure that the `li` are there |
8,171,186 | >
> **Possible Duplicate:**
>
> [Using Mockito to test abstract classes](https://stackoverflow.com/questions/1087339/using-mockito-to-test-abstract-classes)
>
>
>
I have an abstract class with functionality I need to test. I could create simple derivative of that class with no op implementations of abstract methods, but is it possible to be done with mocking framework? I need to maintain class internal state, so I can't just call
```
mockedInstance = mock(ClassUnderTest.class);
```
I need something
```
mockedInstance = spy(new ClassUnderTest(...));
```
but apparently this is impossible to do as class is abstract. | 2011/11/17 | [
"https://Stackoverflow.com/questions/8171186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/471149/"
] | When I want to unit test an Abstract class I don't mock, I subclass.
borrowing code from mijer in other answer
```
public class MockitoTest {
public static abstract class MyAbstractClass {
private int state;
public abstract int abstractMethod();
public int method(....)
{
...
}
}
}
class Testclass extends MyAbstractClass
{
public int abstractMethod()
{
...
}
}
```
Then run your tests of MyAbstractClass using an instance of Testclass.
you can control the implementation of the abstract methods in your local subclass. | ```
import org.junit.Test;
import org.mockito.internal.stubbing.answers.CallsRealMethods;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
public class MockitoTest {
public static abstract class MyAbstractClass {
private int state;
public abstract int abstractMethod();
public void method() {
System.out.println("method. State: " + (++state));
System.out.println("abstractMethod: " + abstractMethod());
anotherMethod();
}
public void anotherMethod() {
System.out.println("anotherMethod. State: " + (++state));
}
}
@Test
public void test() throws Exception {
MyAbstractClass obj = mock(MyAbstractClass.class, new CallsRealMethods());
doReturn(5).when(obj).abstractMethod();
obj.method();
verify(obj).abstractMethod();
assertEquals(2, obj.state);
}
}
```
---
-EDIT-
1. If you need to maintain internal state of the object you have to use `org.mockito.internal.util.reflection.Whitebox.setInternalState`, for example:
```
@Test
public void test() throws Exception {
MyAbstractClass obj = mock(MyAbstractClass.class, new CallsRealMethods());
setInternalState(obj, "state", 100);
doReturn(5).when(obj).abstractMethod();
obj.method();
verify(obj).abstractMethod();
assertEquals(102, obj.state);
}
```
2. If you have an abstract class with a complex logic in its constructor which you would like to test, you should extend this class just for testing or refactor your class moving all the logic to some method to be tested. |
6,824,728 | By doing this:
```
File file1 = new File("/usr/local/test/multipartMimeMsg.txt");
FileOutputStream fos1 = new FileOutputStream(file1);
String s = byteArrayToHexString(multipartMimeMsg.getBytes());
fos1.write(s.getBytes(), 0, s.getBytes().length);
```
I verified that my multipartMimeMsg string can see the hexa representation of the chinese characters. I then proceed to do this:
```
prepstmt.setObject(2, multipartMimeMsg );
```
But it turns up as ??? or 3F3F3F in hexa representation. It should show E4BDA0E5A5BDE59097 Am I missing something? I have set my Table Options to Charset utf8, Collation to utf8\_general\_ci.
Connection string is jdbc:mysql://localhost:3306/test | 2011/07/26 | [
"https://Stackoverflow.com/questions/6824728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/659906/"
] | To work around this, you can use a second non-persistent cookie to act as a session id that you can control the value of. The idea is to generate a unique id and store it in both the cookie and the session. Implement the same logic with this cookie that you are attempting to do with the session through using invalidate. Specifically, don't issue the actual identifier that will be accepted for future requests until authentication is successful. Then create a Servlet Filter that checks each request and matches the value of this new cookie to the value stored in the session. If they don't match, something nefarious is going on. I know it is a bit more cumbersome than just relying on `session.invalidate()` to issue a new id. But given your constraints and JRun's behavior, this will provide sufficient protection against session fixation. | From Section 7.3 of the [Java Servlet 3.0 specification](http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-eval-oth-JSpec/), you can see that:
>
> HttpSession objects must be scoped at the application (or servlet
> context) level. **The underlying mechanism, such as the cookie used to
> establish the session, can be the same for different contexts**, but the
> object referenced, including the attributes in that object, must never
> be shared between contexts by the container.
>
>
>
It's a really terrible idea, but I wonder if the JSESSIONID cookie is simply re-used and the actual session context destroyed. Can you still acess state (i.e. attributes) of the invalidated session? |
49,130,298 | In `EditText` `android:nextFocusDown="@+id/fuelfrom"` will goes to next field when press done, similarly, how can I make a `AutoCompleteTextView` goes to next field when pressing `enter` key... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49130298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8855530/"
] | Use
```
android:singleLine="true"
```
it will show focus on next field on pressing enter.
**EDIT:**
try this one
```
android:imeOptions="actionNext"
``` | ```
use this.
<EditText android:imeOptions="actionDone"
android:inputType="text"/>
edittext.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Here you can write the code");
}
return false;
}
});
```
should return true in the if clause to say you've handled i |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | In my interpretation, the AC VS DC thing depends on how the PC would like to open the door.
DC would mean the character wants to keep the door whole, but just get rid of whatever would stop the door from opening (like the small metal part of a lock sliding into the side of a wall or a wooden bar behind it). This might leave the door damaged, but still usable (depending on the lock method).
AC would mean a player attacks the door, so they would just physically destroy it, which I would just describe as a player trying to return a wooden door back to some planks with nails sticking out or something similar. | It depends on the Situation
---------------------------
Is there a *penalty for failure*, and how detailed do we *really* need to be?
### Scenario 1
If your party is in the middle of a combat and needs to break through a door, then how long it takes them matters just as much as how hard they hit. There is definitely a penalty for failure here, and as it is combat, and thus a tense situation where every action matters, we want to be detailed. Thus, use AC and hit points.
### Scenario 2
If your party is not threatened, has plenty of time, and there is no penalty for failure, you don't even need to roll. Look at the proposed DC, look at the characters and how they intend to do it and make a judgement call. If they have any chance of success, they'll get there eventually so just narrate it happening. If there is no chance of them achieving it, perhaps because they're all Strength 8 wizards with just their fists against a locked iron door, then you just tell them they have no chance.
### Scenario 3
But what if there is a penalty for failure? Maybe there's some unsuspecting monsters on the other side, who could be taken by surprise if you successfully kick the door down on the first attempt, but will be able to react if it takes longer. We could make attacks against the door until it breaks, and decide that if the players do not break the door in X turns then the monsters will have had time to prepare a defence. But in practice, all this will turn into is a bunch of meaningless dice throws. Nothing has changed from the players' point of view, so they're just going to keep hitting the door again, and again, and again, until the door breaks. That is a boring waste of precious table time.
So instead, roll against the DC. If your players make the roll, they did it quickly enough that the monsters are still napping, playing cards or whatever. If they fail, they had to hit the thing enough times that the monsters were able to ready a defence.
### In conclusion
Don't roll the dice any more than you need to. If there is no penalty for failure and a chance to succeed, give it to them. If the failure doesn't get any worse if they repeatedly fail, just roll once against the DC. If it really does matter exactly how long it takes to break the door, and you really need to know exactly how many hits it will take then, and only then, use AC and hit points.
A caveat is if your players want to give the door an opportunistic kick, just to see if it'll open, without investing all the time necessary to guarantee that the door breaks. In this case, roll the DC once. If they make it, great! If they don't then anyone on the other side knows they are there, so you don't need to bother rolling again. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | It depends on the Situation
---------------------------
Is there a *penalty for failure*, and how detailed do we *really* need to be?
### Scenario 1
If your party is in the middle of a combat and needs to break through a door, then how long it takes them matters just as much as how hard they hit. There is definitely a penalty for failure here, and as it is combat, and thus a tense situation where every action matters, we want to be detailed. Thus, use AC and hit points.
### Scenario 2
If your party is not threatened, has plenty of time, and there is no penalty for failure, you don't even need to roll. Look at the proposed DC, look at the characters and how they intend to do it and make a judgement call. If they have any chance of success, they'll get there eventually so just narrate it happening. If there is no chance of them achieving it, perhaps because they're all Strength 8 wizards with just their fists against a locked iron door, then you just tell them they have no chance.
### Scenario 3
But what if there is a penalty for failure? Maybe there's some unsuspecting monsters on the other side, who could be taken by surprise if you successfully kick the door down on the first attempt, but will be able to react if it takes longer. We could make attacks against the door until it breaks, and decide that if the players do not break the door in X turns then the monsters will have had time to prepare a defence. But in practice, all this will turn into is a bunch of meaningless dice throws. Nothing has changed from the players' point of view, so they're just going to keep hitting the door again, and again, and again, until the door breaks. That is a boring waste of precious table time.
So instead, roll against the DC. If your players make the roll, they did it quickly enough that the monsters are still napping, playing cards or whatever. If they fail, they had to hit the thing enough times that the monsters were able to ready a defence.
### In conclusion
Don't roll the dice any more than you need to. If there is no penalty for failure and a chance to succeed, give it to them. If the failure doesn't get any worse if they repeatedly fail, just roll once against the DC. If it really does matter exactly how long it takes to break the door, and you really need to know exactly how many hits it will take then, and only then, use AC and hit points.
A caveat is if your players want to give the door an opportunistic kick, just to see if it'll open, without investing all the time necessary to guarantee that the door breaks. In this case, roll the DC once. If they make it, great! If they don't then anyone on the other side knows they are there, so you don't need to bother rolling again. | I always change it based on what the door is made of and what the players is doing.
If the player says they are going to shoulder check the door that is obviously a strength check if they say they are going to use an axe to chop through the door that is attacking the door. I never let my players just say "I am going to try to break the door down" my immediate response is "How? How are you trying to break it"
But I limit what the players can do (or at least what works, hey you can *try* anything) based on the door material. You are not chopping through an iron door no matter how many times you hit it with the axe, the object damage rules support this with something called a [damage threshold and damage immunities](https://roll20.net/compendium/dnd5e/Objects#content). For instance I always rule slashing don't work on stone or at least not unless you are doing at least 30 points of damage with each attack, so generally a strength checks are all that is possible. A stone door might be possible to break with a hammer or heavy pick but almost no other weapon is going to leave a mark but a strength check is always possible even if impossibly high. this mechanic is great for mitigating what I call tomfoolery, like players attempting to cut a rope with a sling or club or trying to smash down a wooden door with a rapier.
A homebrew thing I sometimes do is say every attack does 1 point of damage to the weapon or 1d2-1 if it is an very sturdy weapon, this keeps players from just always relying on breaking things down, now they might destroy their weapon if they get unlikely with their rolls to chop through the door. Usually I save this for sturdy objects like metal or stone, but wood might be appropriate if the players are trying to dig their way through a iron bound wooden door with a sword or a low level monk tries to punch their way though an solid oak door. It makes the layers stop and think which is always a plus. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | Both are appropriate for different circumstances
------------------------------------------------
The description of how the player wishes to open the door is key. Typically if they wish to *'Smash down a door'* - i.e. break it off of it's hinges, **a strength check would be the appropriate choice**, with a DC determined by the DM according to the description of the door.
If the PC wishes to directly **attack and damage the door** itself, then AC should be used to determine if they're capable of dealing sufficient damage.
One caveat of letting a PC use AC to attack a door however, is that they'd eventually be able to break even the strongest of doors with enough attacks. If you don't wish the door to be eventually broken into by anybody - a strength check is a single determination of whether a PC is capable of it or not. | In Moments of Building Tension
------------------------------
Whilst it may be better to abstract the damage as User Kyyshack said in a comment:
>
> If they roll an attack, what will players do if they don't get through in the first hit? Nothing has really changed so they'll just hit the door again. And Again. And Again. Until the door is broken. That's super boring and wastes time. It's much better to abstract that boring time away behind a single roll against a DC that will answer your question of "Do they break through quickly enough to catch the monsters off guard?"
>
>
>
Using the rules for Object AC and Hit Points could be useful to help build tension. Rather than having the PC’s roll over and over again, you could have *monsters* roll to see if they damage a door the PC’s are on the other side of. Seeing creatures claw through a door or ripping boards off it would create more tension than if they rolled a nat 20 and broke it down in a single turn. The former option might allow players more time to react to the issue and respond to it, such as by barricading the door, escaping, preparing an ambush, etc.
Additionally, having rickety old damaged doors or furniture can help to establish a theme. If players find a door that has already been damaged, they may want to investigate what caused it, and if that thing is still around. For example, if they found a door with a large axe wound in the middle of it like something out The Shining, players may wonder who was trying to get into this room, and why? Or, if they stumbled upon a door with a dozen puncture wounds in it like it was repeatedly stabbed by a dagger, they may investigate the cause - or not, but they’ll learn pretty quickly what caused those holes when they get hit in the back of the head by a falling flail trap.
Partial Opening
---------------
Thanks to user Jared Posch for highlighting the idea of accessibility in their comment:
>
> I would look at the accessibility of the lock, aka, can the players actually attack the lock. A door locked with a wooden beam would mean the beam is behind the door, so unless a player can accurately swing his sword down the middle, I'd say they don't do damage
>
>
>
Rather than players having to completely open a door (such as by destroying it completely or by bashing through the door with a DC Strength check), players might partially damage a door.
* For example, players might cut a hole around the locking mechanism to open a door, leaving it damaged but mostly intact - perhaps only removing 1 or 2 HP from the door.
* Or, players may cut a hole in the door, creating an opening large enough for a Small creature to go through (or a Medium sized creature if they squeeze through the hole). This could be useful if they know they are being chased by Large creatures as it would slow them down. Alternatively, Small creatures like Kobolds might make holes in locked doors as it would slow down Medium sized creatures, hinger Large creatures but would not affect Small creatures like themselves (or they could make Tiny holes so they could squeeze through but larger creatures wouldn’t be able to).
* Players may even put a hole in the door to gain access to the lock or door bar on the other side, allowing the door to be easily unlocked.
Treat the door as though it was made up of smaller objects. So, whilst you may need to remove 18 HP to destroy a Medium sized resilient door completely, you may only take off 5 HP to put a Tiny hole in it or 10 to put a Small hole in it.
Reinforced Doors
----------------
User guildsbounty helpfully pointed out:
>
> Perhaps worth noting: some published adventures explicitly call out that a properly fortified door cannot be kicked in with a Strength Check, and must instead be destroyed by attacking it. The most recent example being in [Ghosts of Saltmarsh.](http://dndbeyond.com/sources/gos/tammerauts-fate#ReinforcingtheDoors)
>
>
>
Having this clear distinction for Reinforced doors could be quite a useful tool. It may force players to make a decision between completely breaking this door, which would be very noisy and may take a long while, or finding another way through it. Here is what the Ghosts of Saltmarsh says about reinforced doors, page 157:
>
> It takes a character 1 hour to gather the required materials and reinforce one door. The time is cut in half if another character helps.
> A reinforced door cannot be broken through with a Strength check, but must be battered down (AC 15, 30 hit points, immunity to poison and psychic damage)
>
>
>
Note that this rule is assuming the door is made out of wood, is being reinforced with wooden planks and nails and these materials are readily available.
A possible way to calculate the health of a reinforced door is to add the health of the reinforcing objects to it and use the highest AC. For example, a Medium Resilient wood door (AC 15, HP 20) is being reinforced with Small Resilient planks of wood (AC 15, HP 10). The highest AC is 15 so the door has an AC of 15, 20 HP plus 10 HP equals 30 HP, giving us AC 15, HP 30 for the reinforced door in question. If we were using steel bars to reinforce the door instead, as they have an AC of 19, we would instead have AC 19, HP 30 for the reinforced door.
So then, one possible situation where you would use AC and HP over a DC check is when a door has been reinforced, either by the players or by the inhabitants of a dungeon.
Hitting Creatures Behind Cover
------------------------------
*This follows up from the idea of partial opening. I got a bit carried away but this highlights how object AC could be used in a completely different way than how a DC check is used:*
A creature can use any suitably large object as cover from an attack. A creature gains bonuses to their AC and Dexterity saving throws depending on the level of cover. A creature in total cover gains the bonus of it not being able to be targeted directly.
If, for the purposes of an attack, we treat the door as a creature, we can use the Cleave Through Creatures optional rule in the DMG page 272:
>
> When a melee attack reduces an undamaged creature to 0 hit points, any excess damage from that attack might carry over to another creature nearby. The attacker targets another creature within reach and, if the original attack roll can hit it, applies any remaining damage to it
>
>
>
So, using the example of a door, its a Medium sized resilient object made of wood, so it has 15 AC and 18 HP. However, we are targeting a Tiny section of it, so the AC is 15 and the HP is only 5. The attacker rolls a 16 and deals 7 damage, this hits the Tiny section of the door and reduces it to 0 HP. As we are using the Cleave Through Creatures rule, the attacker still has 2 damage left over which can be used to hit a creature within range (such as one who was standing right behind the door).
Because the weapon has now gone through the cover, the creature is no longer in cover for the purpose of this attack - just to be clear, any bonuses for cover (such as increased AC, better Dex Saving Throws or being untargetable) the creature had are being ignored by this attack.
If the 16 rolled by the attacker earlier to hit the door is enough to hit the creature behind the door (without any bonuses from cover) they will take the remaining 2 damage. If the creature had an AC of 17 though they would manage to avoid any damage.
This rule would make more sense when applied against a creature behind a fragile material, such as glass. (Due to glass only having an AC of 13 and being fragile, a Tiny section of that might only have 2 HP, meaning more damage is transferred to the target). It also makes sense thematically, Rules as Written would say standing behind a glass window or a curtain or even pulling the bedsheets over your head would count as cover, they might even count as Total cover, preventing the creature from being targetted. However, by using the Cleave Through Creatures rule in this way, we can make things more realistic “that window will not stop this arrow going through”, “those curtains or those bedsheets aren’t going to stop my sword from stabbing you”. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | In my interpretation, the AC VS DC thing depends on how the PC would like to open the door.
DC would mean the character wants to keep the door whole, but just get rid of whatever would stop the door from opening (like the small metal part of a lock sliding into the side of a wall or a wooden bar behind it). This might leave the door damaged, but still usable (depending on the lock method).
AC would mean a player attacks the door, so they would just physically destroy it, which I would just describe as a player trying to return a wooden door back to some planks with nails sticking out or something similar. | I always change it based on what the door is made of and what the players is doing.
If the player says they are going to shoulder check the door that is obviously a strength check if they say they are going to use an axe to chop through the door that is attacking the door. I never let my players just say "I am going to try to break the door down" my immediate response is "How? How are you trying to break it"
But I limit what the players can do (or at least what works, hey you can *try* anything) based on the door material. You are not chopping through an iron door no matter how many times you hit it with the axe, the object damage rules support this with something called a [damage threshold and damage immunities](https://roll20.net/compendium/dnd5e/Objects#content). For instance I always rule slashing don't work on stone or at least not unless you are doing at least 30 points of damage with each attack, so generally a strength checks are all that is possible. A stone door might be possible to break with a hammer or heavy pick but almost no other weapon is going to leave a mark but a strength check is always possible even if impossibly high. this mechanic is great for mitigating what I call tomfoolery, like players attempting to cut a rope with a sling or club or trying to smash down a wooden door with a rapier.
A homebrew thing I sometimes do is say every attack does 1 point of damage to the weapon or 1d2-1 if it is an very sturdy weapon, this keeps players from just always relying on breaking things down, now they might destroy their weapon if they get unlikely with their rolls to chop through the door. Usually I save this for sturdy objects like metal or stone, but wood might be appropriate if the players are trying to dig their way through a iron bound wooden door with a sword or a low level monk tries to punch their way though an solid oak door. It makes the layers stop and think which is always a plus. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | In my interpretation, the AC VS DC thing depends on how the PC would like to open the door.
DC would mean the character wants to keep the door whole, but just get rid of whatever would stop the door from opening (like the small metal part of a lock sliding into the side of a wall or a wooden bar behind it). This might leave the door damaged, but still usable (depending on the lock method).
AC would mean a player attacks the door, so they would just physically destroy it, which I would just describe as a player trying to return a wooden door back to some planks with nails sticking out or something similar. | Both are appropriate for different circumstances
------------------------------------------------
The description of how the player wishes to open the door is key. Typically if they wish to *'Smash down a door'* - i.e. break it off of it's hinges, **a strength check would be the appropriate choice**, with a DC determined by the DM according to the description of the door.
If the PC wishes to directly **attack and damage the door** itself, then AC should be used to determine if they're capable of dealing sufficient damage.
One caveat of letting a PC use AC to attack a door however, is that they'd eventually be able to break even the strongest of doors with enough attacks. If you don't wish the door to be eventually broken into by anybody - a strength check is a single determination of whether a PC is capable of it or not. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | Both are appropriate for different circumstances
------------------------------------------------
The description of how the player wishes to open the door is key. Typically if they wish to *'Smash down a door'* - i.e. break it off of it's hinges, **a strength check would be the appropriate choice**, with a DC determined by the DM according to the description of the door.
If the PC wishes to directly **attack and damage the door** itself, then AC should be used to determine if they're capable of dealing sufficient damage.
One caveat of letting a PC use AC to attack a door however, is that they'd eventually be able to break even the strongest of doors with enough attacks. If you don't wish the door to be eventually broken into by anybody - a strength check is a single determination of whether a PC is capable of it or not. | They both solve the same problem
================================
Both DC and AC handle the same situation, they just have different ways of handling it. There is no right or wrong choice in which to do. The choice should be made considering what feels right for the encounter, what the DM/players prefer, and the skill set of the party involved.
### When to use DC
DC tends to be the simpler solution. Typically breaking down a door requires one roll per attempt and without HP there are less numbers to keep track of. This makes the encounters more streamlined and feel fluid. I have found that using DC tends to be more *cinematic* and players who enjoy the role-play prefer this option.
Against stronger doors you could even create a situation with sequential DCs they need to beat to break it down. For example, an iron door would be much harder to break down by brute force, but that won't stop the barbarian from trying! Set the door with 3 DCs to beat. I opt for starting with a high DC then lowering the following checks as the door takes mores damage. The first cause the door to bulge, the second breaks the hinges and bends the door, the third rips the door off the hinges and sends it flying into the room.
### When to use AC
AC has more factors to consider. Treating a door as an object you have to consider its HP, its AC, and any damage reductions it may have. It also helps when your party overall has a low strength save and beating strength DCs is difficult and takes multiple attempts. This also enables casters and non-melee characters to help break down the door. Players who enjoy number crunching or parties with low strength checks would likely prefer this solution.
When you have stronger doors and it is unrealistic to break them down with brute strength, it's more appropriated to stat the wall with AC/HP. Giving a door more HP, a higher AC, or modifying its damage reduction is an easy way to increase their difficulty.
Also I've ran sessions with people who hold grudges against doors and watching the HP of a door whittle down until it eventually breaks gives them an odd sense of satisfaction.
---
*This answer is based on encounters in sessions I have ran or played in. My opinion based on my personal experiences and are by no means a large study. There are times when I use both methods, but my preference is to use DC.* |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | It depends on the Situation
---------------------------
Is there a *penalty for failure*, and how detailed do we *really* need to be?
### Scenario 1
If your party is in the middle of a combat and needs to break through a door, then how long it takes them matters just as much as how hard they hit. There is definitely a penalty for failure here, and as it is combat, and thus a tense situation where every action matters, we want to be detailed. Thus, use AC and hit points.
### Scenario 2
If your party is not threatened, has plenty of time, and there is no penalty for failure, you don't even need to roll. Look at the proposed DC, look at the characters and how they intend to do it and make a judgement call. If they have any chance of success, they'll get there eventually so just narrate it happening. If there is no chance of them achieving it, perhaps because they're all Strength 8 wizards with just their fists against a locked iron door, then you just tell them they have no chance.
### Scenario 3
But what if there is a penalty for failure? Maybe there's some unsuspecting monsters on the other side, who could be taken by surprise if you successfully kick the door down on the first attempt, but will be able to react if it takes longer. We could make attacks against the door until it breaks, and decide that if the players do not break the door in X turns then the monsters will have had time to prepare a defence. But in practice, all this will turn into is a bunch of meaningless dice throws. Nothing has changed from the players' point of view, so they're just going to keep hitting the door again, and again, and again, until the door breaks. That is a boring waste of precious table time.
So instead, roll against the DC. If your players make the roll, they did it quickly enough that the monsters are still napping, playing cards or whatever. If they fail, they had to hit the thing enough times that the monsters were able to ready a defence.
### In conclusion
Don't roll the dice any more than you need to. If there is no penalty for failure and a chance to succeed, give it to them. If the failure doesn't get any worse if they repeatedly fail, just roll once against the DC. If it really does matter exactly how long it takes to break the door, and you really need to know exactly how many hits it will take then, and only then, use AC and hit points.
A caveat is if your players want to give the door an opportunistic kick, just to see if it'll open, without investing all the time necessary to guarantee that the door breaks. In this case, roll the DC once. If they make it, great! If they don't then anyone on the other side knows they are there, so you don't need to bother rolling again. | In Moments of Building Tension
------------------------------
Whilst it may be better to abstract the damage as User Kyyshack said in a comment:
>
> If they roll an attack, what will players do if they don't get through in the first hit? Nothing has really changed so they'll just hit the door again. And Again. And Again. Until the door is broken. That's super boring and wastes time. It's much better to abstract that boring time away behind a single roll against a DC that will answer your question of "Do they break through quickly enough to catch the monsters off guard?"
>
>
>
Using the rules for Object AC and Hit Points could be useful to help build tension. Rather than having the PC’s roll over and over again, you could have *monsters* roll to see if they damage a door the PC’s are on the other side of. Seeing creatures claw through a door or ripping boards off it would create more tension than if they rolled a nat 20 and broke it down in a single turn. The former option might allow players more time to react to the issue and respond to it, such as by barricading the door, escaping, preparing an ambush, etc.
Additionally, having rickety old damaged doors or furniture can help to establish a theme. If players find a door that has already been damaged, they may want to investigate what caused it, and if that thing is still around. For example, if they found a door with a large axe wound in the middle of it like something out The Shining, players may wonder who was trying to get into this room, and why? Or, if they stumbled upon a door with a dozen puncture wounds in it like it was repeatedly stabbed by a dagger, they may investigate the cause - or not, but they’ll learn pretty quickly what caused those holes when they get hit in the back of the head by a falling flail trap.
Partial Opening
---------------
Thanks to user Jared Posch for highlighting the idea of accessibility in their comment:
>
> I would look at the accessibility of the lock, aka, can the players actually attack the lock. A door locked with a wooden beam would mean the beam is behind the door, so unless a player can accurately swing his sword down the middle, I'd say they don't do damage
>
>
>
Rather than players having to completely open a door (such as by destroying it completely or by bashing through the door with a DC Strength check), players might partially damage a door.
* For example, players might cut a hole around the locking mechanism to open a door, leaving it damaged but mostly intact - perhaps only removing 1 or 2 HP from the door.
* Or, players may cut a hole in the door, creating an opening large enough for a Small creature to go through (or a Medium sized creature if they squeeze through the hole). This could be useful if they know they are being chased by Large creatures as it would slow them down. Alternatively, Small creatures like Kobolds might make holes in locked doors as it would slow down Medium sized creatures, hinger Large creatures but would not affect Small creatures like themselves (or they could make Tiny holes so they could squeeze through but larger creatures wouldn’t be able to).
* Players may even put a hole in the door to gain access to the lock or door bar on the other side, allowing the door to be easily unlocked.
Treat the door as though it was made up of smaller objects. So, whilst you may need to remove 18 HP to destroy a Medium sized resilient door completely, you may only take off 5 HP to put a Tiny hole in it or 10 to put a Small hole in it.
Reinforced Doors
----------------
User guildsbounty helpfully pointed out:
>
> Perhaps worth noting: some published adventures explicitly call out that a properly fortified door cannot be kicked in with a Strength Check, and must instead be destroyed by attacking it. The most recent example being in [Ghosts of Saltmarsh.](http://dndbeyond.com/sources/gos/tammerauts-fate#ReinforcingtheDoors)
>
>
>
Having this clear distinction for Reinforced doors could be quite a useful tool. It may force players to make a decision between completely breaking this door, which would be very noisy and may take a long while, or finding another way through it. Here is what the Ghosts of Saltmarsh says about reinforced doors, page 157:
>
> It takes a character 1 hour to gather the required materials and reinforce one door. The time is cut in half if another character helps.
> A reinforced door cannot be broken through with a Strength check, but must be battered down (AC 15, 30 hit points, immunity to poison and psychic damage)
>
>
>
Note that this rule is assuming the door is made out of wood, is being reinforced with wooden planks and nails and these materials are readily available.
A possible way to calculate the health of a reinforced door is to add the health of the reinforcing objects to it and use the highest AC. For example, a Medium Resilient wood door (AC 15, HP 20) is being reinforced with Small Resilient planks of wood (AC 15, HP 10). The highest AC is 15 so the door has an AC of 15, 20 HP plus 10 HP equals 30 HP, giving us AC 15, HP 30 for the reinforced door in question. If we were using steel bars to reinforce the door instead, as they have an AC of 19, we would instead have AC 19, HP 30 for the reinforced door.
So then, one possible situation where you would use AC and HP over a DC check is when a door has been reinforced, either by the players or by the inhabitants of a dungeon.
Hitting Creatures Behind Cover
------------------------------
*This follows up from the idea of partial opening. I got a bit carried away but this highlights how object AC could be used in a completely different way than how a DC check is used:*
A creature can use any suitably large object as cover from an attack. A creature gains bonuses to their AC and Dexterity saving throws depending on the level of cover. A creature in total cover gains the bonus of it not being able to be targeted directly.
If, for the purposes of an attack, we treat the door as a creature, we can use the Cleave Through Creatures optional rule in the DMG page 272:
>
> When a melee attack reduces an undamaged creature to 0 hit points, any excess damage from that attack might carry over to another creature nearby. The attacker targets another creature within reach and, if the original attack roll can hit it, applies any remaining damage to it
>
>
>
So, using the example of a door, its a Medium sized resilient object made of wood, so it has 15 AC and 18 HP. However, we are targeting a Tiny section of it, so the AC is 15 and the HP is only 5. The attacker rolls a 16 and deals 7 damage, this hits the Tiny section of the door and reduces it to 0 HP. As we are using the Cleave Through Creatures rule, the attacker still has 2 damage left over which can be used to hit a creature within range (such as one who was standing right behind the door).
Because the weapon has now gone through the cover, the creature is no longer in cover for the purpose of this attack - just to be clear, any bonuses for cover (such as increased AC, better Dex Saving Throws or being untargetable) the creature had are being ignored by this attack.
If the 16 rolled by the attacker earlier to hit the door is enough to hit the creature behind the door (without any bonuses from cover) they will take the remaining 2 damage. If the creature had an AC of 17 though they would manage to avoid any damage.
This rule would make more sense when applied against a creature behind a fragile material, such as glass. (Due to glass only having an AC of 13 and being fragile, a Tiny section of that might only have 2 HP, meaning more damage is transferred to the target). It also makes sense thematically, Rules as Written would say standing behind a glass window or a curtain or even pulling the bedsheets over your head would count as cover, they might even count as Total cover, preventing the creature from being targetted. However, by using the Cleave Through Creatures rule in this way, we can make things more realistic “that window will not stop this arrow going through”, “those curtains or those bedsheets aren’t going to stop my sword from stabbing you”. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | Both are appropriate for different circumstances
------------------------------------------------
The description of how the player wishes to open the door is key. Typically if they wish to *'Smash down a door'* - i.e. break it off of it's hinges, **a strength check would be the appropriate choice**, with a DC determined by the DM according to the description of the door.
If the PC wishes to directly **attack and damage the door** itself, then AC should be used to determine if they're capable of dealing sufficient damage.
One caveat of letting a PC use AC to attack a door however, is that they'd eventually be able to break even the strongest of doors with enough attacks. If you don't wish the door to be eventually broken into by anybody - a strength check is a single determination of whether a PC is capable of it or not. | I always change it based on what the door is made of and what the players is doing.
If the player says they are going to shoulder check the door that is obviously a strength check if they say they are going to use an axe to chop through the door that is attacking the door. I never let my players just say "I am going to try to break the door down" my immediate response is "How? How are you trying to break it"
But I limit what the players can do (or at least what works, hey you can *try* anything) based on the door material. You are not chopping through an iron door no matter how many times you hit it with the axe, the object damage rules support this with something called a [damage threshold and damage immunities](https://roll20.net/compendium/dnd5e/Objects#content). For instance I always rule slashing don't work on stone or at least not unless you are doing at least 30 points of damage with each attack, so generally a strength checks are all that is possible. A stone door might be possible to break with a hammer or heavy pick but almost no other weapon is going to leave a mark but a strength check is always possible even if impossibly high. this mechanic is great for mitigating what I call tomfoolery, like players attempting to cut a rope with a sling or club or trying to smash down a wooden door with a rapier.
A homebrew thing I sometimes do is say every attack does 1 point of damage to the weapon or 1d2-1 if it is an very sturdy weapon, this keeps players from just always relying on breaking things down, now they might destroy their weapon if they get unlikely with their rolls to chop through the door. Usually I save this for sturdy objects like metal or stone, but wood might be appropriate if the players are trying to dig their way through a iron bound wooden door with a sword or a low level monk tries to punch their way though an solid oak door. It makes the layers stop and think which is always a plus. |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | In my interpretation, the AC VS DC thing depends on how the PC would like to open the door.
DC would mean the character wants to keep the door whole, but just get rid of whatever would stop the door from opening (like the small metal part of a lock sliding into the side of a wall or a wooden bar behind it). This might leave the door damaged, but still usable (depending on the lock method).
AC would mean a player attacks the door, so they would just physically destroy it, which I would just describe as a player trying to return a wooden door back to some planks with nails sticking out or something similar. | They both solve the same problem
================================
Both DC and AC handle the same situation, they just have different ways of handling it. There is no right or wrong choice in which to do. The choice should be made considering what feels right for the encounter, what the DM/players prefer, and the skill set of the party involved.
### When to use DC
DC tends to be the simpler solution. Typically breaking down a door requires one roll per attempt and without HP there are less numbers to keep track of. This makes the encounters more streamlined and feel fluid. I have found that using DC tends to be more *cinematic* and players who enjoy the role-play prefer this option.
Against stronger doors you could even create a situation with sequential DCs they need to beat to break it down. For example, an iron door would be much harder to break down by brute force, but that won't stop the barbarian from trying! Set the door with 3 DCs to beat. I opt for starting with a high DC then lowering the following checks as the door takes mores damage. The first cause the door to bulge, the second breaks the hinges and bends the door, the third rips the door off the hinges and sends it flying into the room.
### When to use AC
AC has more factors to consider. Treating a door as an object you have to consider its HP, its AC, and any damage reductions it may have. It also helps when your party overall has a low strength save and beating strength DCs is difficult and takes multiple attempts. This also enables casters and non-melee characters to help break down the door. Players who enjoy number crunching or parties with low strength checks would likely prefer this solution.
When you have stronger doors and it is unrealistic to break them down with brute strength, it's more appropriated to stat the wall with AC/HP. Giving a door more HP, a higher AC, or modifying its damage reduction is an easy way to increase their difficulty.
Also I've ran sessions with people who hold grudges against doors and watching the HP of a door whittle down until it eventually breaks gives them an odd sense of satisfaction.
---
*This answer is based on encounters in sessions I have ran or played in. My opinion based on my personal experiences and are by no means a large study. There are times when I use both methods, but my preference is to use DC.* |
148,590 | It is not uncommon for players to encounter a door that resists being opened - the door may be stuck, barred, locked, barricaded, etc. A locked door could be unlocked by finding a key or passing a Difficulty Check to pick the lock, or it could be broken down.
In the D&D 5e Dungeon Master’s Guide page 237, the examples for when a strength ability check might be used are: “Smash down a door, move a boulder, use a spike to wedge a door shut”. Which seems fine - set a DC and see if the player can beat it with Strength check. This seems to be confirmed by the Player’s Handbook page 176, again in reference to when a Strength check may be used: “Force open a stuck, locked, or barred door”.
However, page 246 of the DMG also details object Armour Class and Hit Points. One could argue that a door is considered to be an object (at least, as much as a *wall* is considered to be an object by the book). Lets say the door is made of wood, its a medium sized object and it is resilient, so it has an AC of 15 and 18 Hit Points. When the door reaches 0 HP, it opens.
When would it be appropriate to use the AC and hit points of a door to determine if it opens versus setting a DC Strength check?
For the purposes of this question, assume there is always a chance for success and a risk of failure, there are no automatic successes or failures. Also assume that the players are determined to break the door, they are not interested in looking for ways around it - the door will be broken and open eventually, it is more a case of what method should be used to determine when the door opens.
---
*Note that although this question is specifically asking about breaking doors, it would apply to any situation where it might be appropriate to use either an AC or a DC to break something. I have simply used doors as my example as they are one of the most likely and most common things a player may try to break.* | 2019/05/24 | [
"https://rpg.stackexchange.com/questions/148590",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53100/"
] | It depends on the Situation
---------------------------
Is there a *penalty for failure*, and how detailed do we *really* need to be?
### Scenario 1
If your party is in the middle of a combat and needs to break through a door, then how long it takes them matters just as much as how hard they hit. There is definitely a penalty for failure here, and as it is combat, and thus a tense situation where every action matters, we want to be detailed. Thus, use AC and hit points.
### Scenario 2
If your party is not threatened, has plenty of time, and there is no penalty for failure, you don't even need to roll. Look at the proposed DC, look at the characters and how they intend to do it and make a judgement call. If they have any chance of success, they'll get there eventually so just narrate it happening. If there is no chance of them achieving it, perhaps because they're all Strength 8 wizards with just their fists against a locked iron door, then you just tell them they have no chance.
### Scenario 3
But what if there is a penalty for failure? Maybe there's some unsuspecting monsters on the other side, who could be taken by surprise if you successfully kick the door down on the first attempt, but will be able to react if it takes longer. We could make attacks against the door until it breaks, and decide that if the players do not break the door in X turns then the monsters will have had time to prepare a defence. But in practice, all this will turn into is a bunch of meaningless dice throws. Nothing has changed from the players' point of view, so they're just going to keep hitting the door again, and again, and again, until the door breaks. That is a boring waste of precious table time.
So instead, roll against the DC. If your players make the roll, they did it quickly enough that the monsters are still napping, playing cards or whatever. If they fail, they had to hit the thing enough times that the monsters were able to ready a defence.
### In conclusion
Don't roll the dice any more than you need to. If there is no penalty for failure and a chance to succeed, give it to them. If the failure doesn't get any worse if they repeatedly fail, just roll once against the DC. If it really does matter exactly how long it takes to break the door, and you really need to know exactly how many hits it will take then, and only then, use AC and hit points.
A caveat is if your players want to give the door an opportunistic kick, just to see if it'll open, without investing all the time necessary to guarantee that the door breaks. In this case, roll the DC once. If they make it, great! If they don't then anyone on the other side knows they are there, so you don't need to bother rolling again. | They both solve the same problem
================================
Both DC and AC handle the same situation, they just have different ways of handling it. There is no right or wrong choice in which to do. The choice should be made considering what feels right for the encounter, what the DM/players prefer, and the skill set of the party involved.
### When to use DC
DC tends to be the simpler solution. Typically breaking down a door requires one roll per attempt and without HP there are less numbers to keep track of. This makes the encounters more streamlined and feel fluid. I have found that using DC tends to be more *cinematic* and players who enjoy the role-play prefer this option.
Against stronger doors you could even create a situation with sequential DCs they need to beat to break it down. For example, an iron door would be much harder to break down by brute force, but that won't stop the barbarian from trying! Set the door with 3 DCs to beat. I opt for starting with a high DC then lowering the following checks as the door takes mores damage. The first cause the door to bulge, the second breaks the hinges and bends the door, the third rips the door off the hinges and sends it flying into the room.
### When to use AC
AC has more factors to consider. Treating a door as an object you have to consider its HP, its AC, and any damage reductions it may have. It also helps when your party overall has a low strength save and beating strength DCs is difficult and takes multiple attempts. This also enables casters and non-melee characters to help break down the door. Players who enjoy number crunching or parties with low strength checks would likely prefer this solution.
When you have stronger doors and it is unrealistic to break them down with brute strength, it's more appropriated to stat the wall with AC/HP. Giving a door more HP, a higher AC, or modifying its damage reduction is an easy way to increase their difficulty.
Also I've ran sessions with people who hold grudges against doors and watching the HP of a door whittle down until it eventually breaks gives them an odd sense of satisfaction.
---
*This answer is based on encounters in sessions I have ran or played in. My opinion based on my personal experiences and are by no means a large study. There are times when I use both methods, but my preference is to use DC.* |
69,693,962 | Using the packages ggplot2, dplyr and scales, I make the code the following plot
```
grafico_4 <- ggplot() +
ggtitle("Grafico variado") +
theme(plot.title = element_text(size = 10)) +
theme(panel.background = element_rect(fill='white', colour='white')) +
theme( axis.line = element_line(colour = "black", size = 0.5)) +
scale_y_discrete(limits = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")) +
scale_x_discrete(limits = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", "")) +
geom_hline(yintercept = 5, linetype = "dotted") +
ylab("")
```
[](https://i.stack.imgur.com/9XZc4.png)
But why do I get a line between "uno" and "dos" and not between "cinco" and "siete", "siete" and "nueve", and after "nueve"? How do I get the lines to appear? | 2021/10/24 | [
"https://Stackoverflow.com/questions/69693962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17029008/"
] | Following two have solved the issue:
* Increase default SHM (shared memory) for CUDA to 10g (I think 1g would have worked as well). You can do this in docker run command by passing `--shm-size=10g`. I also pass `--ulimit memlock=-1`.
* `export NCCL_P2P_LEVEL=NVL`.
**Debugging Tips**
To check current SHM,
```
df -h
# see the row for shm
```
To see NCCL debug messages:
```
export NCCL_DEBUG=INFO
```
Run p2p bandwidth test for GPU to GPU communication link:
```
cd /usr/local/cuda/samples/1_Utilities/p2pBandwidthLatencyTest
sudo make
./p2pBandwidthLatencyTest
```
For A6000 4 GPU box this prints:
[](https://i.stack.imgur.com/Mo2Zi.png)
The matrix shows bandwith betweeb each pair of GPU and with P2P, it should be high. | For me, the problem turned out to be the `torchrun` command for PyTorch 1.10.1. I only needed to switch to the `python -m torch.distributed.launch` command and everything worked. I spent many hours on the StackOverflow and the PyTorch Forum but no one mentioned this solution, so I'm sharing it to save people time.
`torchrun` seems to be working fine for PyTorch 1.11 and above. |
69,693,962 | Using the packages ggplot2, dplyr and scales, I make the code the following plot
```
grafico_4 <- ggplot() +
ggtitle("Grafico variado") +
theme(plot.title = element_text(size = 10)) +
theme(panel.background = element_rect(fill='white', colour='white')) +
theme( axis.line = element_line(colour = "black", size = 0.5)) +
scale_y_discrete(limits = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")) +
scale_x_discrete(limits = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", "")) +
geom_hline(yintercept = 5, linetype = "dotted") +
ylab("")
```
[](https://i.stack.imgur.com/9XZc4.png)
But why do I get a line between "uno" and "dos" and not between "cinco" and "siete", "siete" and "nueve", and after "nueve"? How do I get the lines to appear? | 2021/10/24 | [
"https://Stackoverflow.com/questions/69693962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17029008/"
] | Following two have solved the issue:
* Increase default SHM (shared memory) for CUDA to 10g (I think 1g would have worked as well). You can do this in docker run command by passing `--shm-size=10g`. I also pass `--ulimit memlock=-1`.
* `export NCCL_P2P_LEVEL=NVL`.
**Debugging Tips**
To check current SHM,
```
df -h
# see the row for shm
```
To see NCCL debug messages:
```
export NCCL_DEBUG=INFO
```
Run p2p bandwidth test for GPU to GPU communication link:
```
cd /usr/local/cuda/samples/1_Utilities/p2pBandwidthLatencyTest
sudo make
./p2pBandwidthLatencyTest
```
For A6000 4 GPU box this prints:
[](https://i.stack.imgur.com/Mo2Zi.png)
The matrix shows bandwith betweeb each pair of GPU and with P2P, it should be high. | <https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group>
set timeout param in torch.distributed.init\_process\_group(), default is 30 mins
```
torch.distributed.init_process_group(backend, init_method=None, timeout=datetime.timedelta(seconds=1800), world_size=- 1, rank=- 1, store=None, group_name='', pg_options=None)
``` |
71,614,897 | I am trying to open a folder that I opened before, but it crashed.
I can open other projects, and restarting the computer didn't help.
Maybe it's because I had a big file opened (400mb) in this folder, but I cant close this file because the vscode crashing every time when I tried open the workspace..
<https://github.com/microsoft/vscode/issues/126127>
<https://github.com/microsoft/vscode/issues/130375>
[](https://i.stack.imgur.com/8MZZm.png) | 2022/03/25 | [
"https://Stackoverflow.com/questions/71614897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10787867/"
] | I had the same problem.
Just delete the folders under `%appdata%/code/backups/` and restart VS. | I solved the problem by restarting my computer and then opening VS code from a different folder.
To open large JSON files, I use Dadroit JSON Viewer, thus preventing the problem from repeating itself. |
71,614,897 | I am trying to open a folder that I opened before, but it crashed.
I can open other projects, and restarting the computer didn't help.
Maybe it's because I had a big file opened (400mb) in this folder, but I cant close this file because the vscode crashing every time when I tried open the workspace..
<https://github.com/microsoft/vscode/issues/126127>
<https://github.com/microsoft/vscode/issues/130375>
[](https://i.stack.imgur.com/8MZZm.png) | 2022/03/25 | [
"https://Stackoverflow.com/questions/71614897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10787867/"
] | I had the same problem.
Just delete the folders under `%appdata%/code/backups/` and restart VS. | It's easy than you think, you just need to update your laptop. and try to use Vs code again you will see that it works. |
71,614,897 | I am trying to open a folder that I opened before, but it crashed.
I can open other projects, and restarting the computer didn't help.
Maybe it's because I had a big file opened (400mb) in this folder, but I cant close this file because the vscode crashing every time when I tried open the workspace..
<https://github.com/microsoft/vscode/issues/126127>
<https://github.com/microsoft/vscode/issues/130375>
[](https://i.stack.imgur.com/8MZZm.png) | 2022/03/25 | [
"https://Stackoverflow.com/questions/71614897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10787867/"
] | I solved the problem by restarting my computer and then opening VS code from a different folder.
To open large JSON files, I use Dadroit JSON Viewer, thus preventing the problem from repeating itself. | It's easy than you think, you just need to update your laptop. and try to use Vs code again you will see that it works. |
30,132,568 | I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.
For example, given this JSON tree
```
{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah"
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}
```
I would like to extract something like [file1,file2,file3,file3,package1,package2,package3,package4]
Basically just a listing of keys that I can use for a text search index.
I know I can get a listing of keys on the outer most objects using something like
```
SELECT DISTINCT(json_object_keys(data))
```
And I know it's possible to to recursively climb through the tree using something like
```
WITH RECURSIVE data()
```
but i'm having trouble putting the two together.
Can anyone help? | 2015/05/08 | [
"https://Stackoverflow.com/questions/30132568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573616/"
] | The trick is to add some final condition testing using `json_typeof` at the right place.
You should also be using `jsonb` if you don't care about object key order.
Here is my working environment:
```
CREATE TABLE test (
id SERIAL PRIMARY KEY,
doc JSON
);
INSERT INTO test (doc) VALUES ('{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah",
"prop" : {
"clap": "clap"
}
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}');
```
The recursion is stopped when the second query does not return any rows. This is done by passing an empty object to `json_each`.
```
WITH RECURSIVE doc_key_and_value_recursive(key, value) AS (
SELECT
t.key,
t.value
FROM test, json_each(test.doc) AS t
UNION ALL
SELECT
t.key,
t.value
FROM doc_key_and_value_recursive,
json_each(CASE
WHEN json_typeof(doc_key_and_value_recursive.value) <> 'object' THEN '{}' :: JSON
ELSE doc_key_and_value_recursive.value
END) AS t
)
SELECT *
FROM doc_key_and_value_recursive
WHERE json_typeof(doc_key_and_value_recursive.value) <> 'object';
``` | A little more concise version that you can just test with:
```
WITH RECURSIVE reports (key, value) AS (
SELECT
NULL as key,
'{"k1": {"k2": "v1"}, "k3": {"k4": "v2"}, "k5": "v3"}'::JSONB as value
UNION ALL
SELECT
jsonb_object_keys(value)as key,
value->jsonb_object_keys(value) as value
FROM
reports
WHERE
jsonb_typeof(value) = 'object'
)
SELECT
*
FROM
reports;
```
This will return a list that you then need to group with distinct. |
30,132,568 | I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.
For example, given this JSON tree
```
{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah"
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}
```
I would like to extract something like [file1,file2,file3,file3,package1,package2,package3,package4]
Basically just a listing of keys that I can use for a text search index.
I know I can get a listing of keys on the outer most objects using something like
```
SELECT DISTINCT(json_object_keys(data))
```
And I know it's possible to to recursively climb through the tree using something like
```
WITH RECURSIVE data()
```
but i'm having trouble putting the two together.
Can anyone help? | 2015/05/08 | [
"https://Stackoverflow.com/questions/30132568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573616/"
] | The trick is to add some final condition testing using `json_typeof` at the right place.
You should also be using `jsonb` if you don't care about object key order.
Here is my working environment:
```
CREATE TABLE test (
id SERIAL PRIMARY KEY,
doc JSON
);
INSERT INTO test (doc) VALUES ('{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah",
"prop" : {
"clap": "clap"
}
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}');
```
The recursion is stopped when the second query does not return any rows. This is done by passing an empty object to `json_each`.
```
WITH RECURSIVE doc_key_and_value_recursive(key, value) AS (
SELECT
t.key,
t.value
FROM test, json_each(test.doc) AS t
UNION ALL
SELECT
t.key,
t.value
FROM doc_key_and_value_recursive,
json_each(CASE
WHEN json_typeof(doc_key_and_value_recursive.value) <> 'object' THEN '{}' :: JSON
ELSE doc_key_and_value_recursive.value
END) AS t
)
SELECT *
FROM doc_key_and_value_recursive
WHERE json_typeof(doc_key_and_value_recursive.value) <> 'object';
``` | I wrote a function to do this:
```
CREATE OR REPLACE FUNCTION public.jsonb_keys_recursive(_value jsonb)
RETURNS TABLE(key text)
LANGUAGE sql
AS $function$
WITH RECURSIVE _tree (key, value) AS (
SELECT
NULL AS key,
_value AS value
UNION ALL
(WITH typed_values AS (SELECT jsonb_typeof(value) as typeof, value FROM _tree)
SELECT v.*
FROM typed_values, LATERAL jsonb_each(value) v
WHERE typeof = 'object'
UNION ALL
SELECT NULL, element
FROM typed_values, LATERAL jsonb_array_elements(value) element
WHERE typeof = 'array'
)
)
SELECT DISTINCT key
FROM _tree
WHERE key IS NOT NULL
$function$;
```
For an example, try:
```
SELECT jsonb_keys_recursive('{"A":[[[{"C":"B"}]]],"X":"Y"}');
```
Note that the other two answers don't find keys within objects inside arrays, my solution does. (The question didn't give any examples of arrays at all, so finding keys inside arrays may not have been what the original asker needed, but it was what I needed.) |
30,132,568 | I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.
For example, given this JSON tree
```
{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah"
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}
```
I would like to extract something like [file1,file2,file3,file3,package1,package2,package3,package4]
Basically just a listing of keys that I can use for a text search index.
I know I can get a listing of keys on the outer most objects using something like
```
SELECT DISTINCT(json_object_keys(data))
```
And I know it's possible to to recursively climb through the tree using something like
```
WITH RECURSIVE data()
```
but i'm having trouble putting the two together.
Can anyone help? | 2015/05/08 | [
"https://Stackoverflow.com/questions/30132568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573616/"
] | The trick is to add some final condition testing using `json_typeof` at the right place.
You should also be using `jsonb` if you don't care about object key order.
Here is my working environment:
```
CREATE TABLE test (
id SERIAL PRIMARY KEY,
doc JSON
);
INSERT INTO test (doc) VALUES ('{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah",
"prop" : {
"clap": "clap"
}
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}');
```
The recursion is stopped when the second query does not return any rows. This is done by passing an empty object to `json_each`.
```
WITH RECURSIVE doc_key_and_value_recursive(key, value) AS (
SELECT
t.key,
t.value
FROM test, json_each(test.doc) AS t
UNION ALL
SELECT
t.key,
t.value
FROM doc_key_and_value_recursive,
json_each(CASE
WHEN json_typeof(doc_key_and_value_recursive.value) <> 'object' THEN '{}' :: JSON
ELSE doc_key_and_value_recursive.value
END) AS t
)
SELECT *
FROM doc_key_and_value_recursive
WHERE json_typeof(doc_key_and_value_recursive.value) <> 'object';
``` | @Simon's answer above is great, but for my similar case building JSON objects diff, I want to have keys path like in JSONpath form, and not only last name, including array indexes and also values.
So, on example `{"A":[[[{"C":"B"}, {"D":"E"}]]],"X":"Y", "F": {"G": "H"}}` I need not only keys `X`, `D`, `G`, `C`, `F`, `A`, but values on each path like `.A[0][0][0].C` = 'B'.
There are also some minor enhancements like:
1. Providing data type of value
2. Provide value itself, without extra quotes
I hope it will be helpful for someone also:
```
WITH RECURSIVE _tree (key, value, type) AS (
SELECT
NULL as key
,'{"A":[[[{"C":"B"}, {"D":"E"}]]],"X":"Y", "F": {"G": "H"}}'::jsonb as value
,'object'
UNION ALL
(
WITH typed_values AS (
SELECT key, jsonb_typeof(value) as typeof, value FROM _tree
)
SELECT CONCAT(tv.key, '.', v.key), v.value, jsonb_typeof(v.value)
FROM typed_values as tv, LATERAL jsonb_each(value) v
WHERE typeof = 'object'
UNION ALL
SELECT CONCAT(tv.key, '[', n-1, ']'), element.val, jsonb_typeof(element.val)
FROM typed_values as tv, LATERAL jsonb_array_elements(value) WITH ORDINALITY as element (val, n)
WHERE typeof = 'array'
)
)
SELECT DISTINCT key, value #>> '{}' as value, type
FROM _tree
WHERE key IS NOT NULL
ORDER BY key
```
[Dbfiddle to run](https://www.db-fiddle.com/f/4Rvsd7cFLvjBTZbvBtT81E/1). |
30,132,568 | I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.
For example, given this JSON tree
```
{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah"
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}
```
I would like to extract something like [file1,file2,file3,file3,package1,package2,package3,package4]
Basically just a listing of keys that I can use for a text search index.
I know I can get a listing of keys on the outer most objects using something like
```
SELECT DISTINCT(json_object_keys(data))
```
And I know it's possible to to recursively climb through the tree using something like
```
WITH RECURSIVE data()
```
but i'm having trouble putting the two together.
Can anyone help? | 2015/05/08 | [
"https://Stackoverflow.com/questions/30132568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573616/"
] | I wrote a function to do this:
```
CREATE OR REPLACE FUNCTION public.jsonb_keys_recursive(_value jsonb)
RETURNS TABLE(key text)
LANGUAGE sql
AS $function$
WITH RECURSIVE _tree (key, value) AS (
SELECT
NULL AS key,
_value AS value
UNION ALL
(WITH typed_values AS (SELECT jsonb_typeof(value) as typeof, value FROM _tree)
SELECT v.*
FROM typed_values, LATERAL jsonb_each(value) v
WHERE typeof = 'object'
UNION ALL
SELECT NULL, element
FROM typed_values, LATERAL jsonb_array_elements(value) element
WHERE typeof = 'array'
)
)
SELECT DISTINCT key
FROM _tree
WHERE key IS NOT NULL
$function$;
```
For an example, try:
```
SELECT jsonb_keys_recursive('{"A":[[[{"C":"B"}]]],"X":"Y"}');
```
Note that the other two answers don't find keys within objects inside arrays, my solution does. (The question didn't give any examples of arrays at all, so finding keys inside arrays may not have been what the original asker needed, but it was what I needed.) | A little more concise version that you can just test with:
```
WITH RECURSIVE reports (key, value) AS (
SELECT
NULL as key,
'{"k1": {"k2": "v1"}, "k3": {"k4": "v2"}, "k5": "v3"}'::JSONB as value
UNION ALL
SELECT
jsonb_object_keys(value)as key,
value->jsonb_object_keys(value) as value
FROM
reports
WHERE
jsonb_typeof(value) = 'object'
)
SELECT
*
FROM
reports;
```
This will return a list that you then need to group with distinct. |
30,132,568 | I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.
For example, given this JSON tree
```
{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah"
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}
```
I would like to extract something like [file1,file2,file3,file3,package1,package2,package3,package4]
Basically just a listing of keys that I can use for a text search index.
I know I can get a listing of keys on the outer most objects using something like
```
SELECT DISTINCT(json_object_keys(data))
```
And I know it's possible to to recursively climb through the tree using something like
```
WITH RECURSIVE data()
```
but i'm having trouble putting the two together.
Can anyone help? | 2015/05/08 | [
"https://Stackoverflow.com/questions/30132568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573616/"
] | @Simon's answer above is great, but for my similar case building JSON objects diff, I want to have keys path like in JSONpath form, and not only last name, including array indexes and also values.
So, on example `{"A":[[[{"C":"B"}, {"D":"E"}]]],"X":"Y", "F": {"G": "H"}}` I need not only keys `X`, `D`, `G`, `C`, `F`, `A`, but values on each path like `.A[0][0][0].C` = 'B'.
There are also some minor enhancements like:
1. Providing data type of value
2. Provide value itself, without extra quotes
I hope it will be helpful for someone also:
```
WITH RECURSIVE _tree (key, value, type) AS (
SELECT
NULL as key
,'{"A":[[[{"C":"B"}, {"D":"E"}]]],"X":"Y", "F": {"G": "H"}}'::jsonb as value
,'object'
UNION ALL
(
WITH typed_values AS (
SELECT key, jsonb_typeof(value) as typeof, value FROM _tree
)
SELECT CONCAT(tv.key, '.', v.key), v.value, jsonb_typeof(v.value)
FROM typed_values as tv, LATERAL jsonb_each(value) v
WHERE typeof = 'object'
UNION ALL
SELECT CONCAT(tv.key, '[', n-1, ']'), element.val, jsonb_typeof(element.val)
FROM typed_values as tv, LATERAL jsonb_array_elements(value) WITH ORDINALITY as element (val, n)
WHERE typeof = 'array'
)
)
SELECT DISTINCT key, value #>> '{}' as value, type
FROM _tree
WHERE key IS NOT NULL
ORDER BY key
```
[Dbfiddle to run](https://www.db-fiddle.com/f/4Rvsd7cFLvjBTZbvBtT81E/1). | A little more concise version that you can just test with:
```
WITH RECURSIVE reports (key, value) AS (
SELECT
NULL as key,
'{"k1": {"k2": "v1"}, "k3": {"k4": "v2"}, "k5": "v3"}'::JSONB as value
UNION ALL
SELECT
jsonb_object_keys(value)as key,
value->jsonb_object_keys(value) as value
FROM
reports
WHERE
jsonb_typeof(value) = 'object'
)
SELECT
*
FROM
reports;
```
This will return a list that you then need to group with distinct. |
30,132,568 | I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.
For example, given this JSON tree
```
{
"files": {
"folder": {
"file1": {
"property": "blah"
},
"file2": {
"property": "blah"
},
"file3": {
"property": "blah"
},
"file4": {
"property": "blah"
}
}
},
"software": {
"apt": {
"package1": {
"version": 1.2
},
"package2": {
"version": 1.2
},
"package3": {
"version": 1.2
},
"package4": {
"version": 1.2
}
}
}
}
```
I would like to extract something like [file1,file2,file3,file3,package1,package2,package3,package4]
Basically just a listing of keys that I can use for a text search index.
I know I can get a listing of keys on the outer most objects using something like
```
SELECT DISTINCT(json_object_keys(data))
```
And I know it's possible to to recursively climb through the tree using something like
```
WITH RECURSIVE data()
```
but i'm having trouble putting the two together.
Can anyone help? | 2015/05/08 | [
"https://Stackoverflow.com/questions/30132568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573616/"
] | I wrote a function to do this:
```
CREATE OR REPLACE FUNCTION public.jsonb_keys_recursive(_value jsonb)
RETURNS TABLE(key text)
LANGUAGE sql
AS $function$
WITH RECURSIVE _tree (key, value) AS (
SELECT
NULL AS key,
_value AS value
UNION ALL
(WITH typed_values AS (SELECT jsonb_typeof(value) as typeof, value FROM _tree)
SELECT v.*
FROM typed_values, LATERAL jsonb_each(value) v
WHERE typeof = 'object'
UNION ALL
SELECT NULL, element
FROM typed_values, LATERAL jsonb_array_elements(value) element
WHERE typeof = 'array'
)
)
SELECT DISTINCT key
FROM _tree
WHERE key IS NOT NULL
$function$;
```
For an example, try:
```
SELECT jsonb_keys_recursive('{"A":[[[{"C":"B"}]]],"X":"Y"}');
```
Note that the other two answers don't find keys within objects inside arrays, my solution does. (The question didn't give any examples of arrays at all, so finding keys inside arrays may not have been what the original asker needed, but it was what I needed.) | @Simon's answer above is great, but for my similar case building JSON objects diff, I want to have keys path like in JSONpath form, and not only last name, including array indexes and also values.
So, on example `{"A":[[[{"C":"B"}, {"D":"E"}]]],"X":"Y", "F": {"G": "H"}}` I need not only keys `X`, `D`, `G`, `C`, `F`, `A`, but values on each path like `.A[0][0][0].C` = 'B'.
There are also some minor enhancements like:
1. Providing data type of value
2. Provide value itself, without extra quotes
I hope it will be helpful for someone also:
```
WITH RECURSIVE _tree (key, value, type) AS (
SELECT
NULL as key
,'{"A":[[[{"C":"B"}, {"D":"E"}]]],"X":"Y", "F": {"G": "H"}}'::jsonb as value
,'object'
UNION ALL
(
WITH typed_values AS (
SELECT key, jsonb_typeof(value) as typeof, value FROM _tree
)
SELECT CONCAT(tv.key, '.', v.key), v.value, jsonb_typeof(v.value)
FROM typed_values as tv, LATERAL jsonb_each(value) v
WHERE typeof = 'object'
UNION ALL
SELECT CONCAT(tv.key, '[', n-1, ']'), element.val, jsonb_typeof(element.val)
FROM typed_values as tv, LATERAL jsonb_array_elements(value) WITH ORDINALITY as element (val, n)
WHERE typeof = 'array'
)
)
SELECT DISTINCT key, value #>> '{}' as value, type
FROM _tree
WHERE key IS NOT NULL
ORDER BY key
```
[Dbfiddle to run](https://www.db-fiddle.com/f/4Rvsd7cFLvjBTZbvBtT81E/1). |
30,211,962 | I'm following the tutorial from [Interactive Python](http://interactivepython.org/courselib/static/pythonds/BasicDS/linkedlists.html) to make an Ordered List in Python. My code looks like this:
```
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, newnext):
self.next = newnext
class OrderedList:
def __init__(self):
self.head = None
def search(self, item):
found = False
stop = False
current = self.head
while current != None and not found and not stop:
if current.getData() == item:
found = True
elif current.getData() > item:
stop = True
else:
current = current.getNext()
return found
def add(self, item):
previous = None
current = self.head
stop = False
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
def remove(self, item):
previous = None
current = self.head
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext)
def update(self, olddata, newdata):
self.remove(olddata)
self.add(newdata)
def display(self):
current = self.head
print("The contents of this list are: ", end='')
print()
while current:
print(current.data)
current = current.getNext()
myList = OrderedList()
myList.add(5)
myList.add(25)
myList.add(30)
myList.remove(25)
myList.display()
myList.update(5, 30)
myList.display()
```
It keeps telling me my variable current is a function and doesn't have the atrributes for a Node. How can I fix it and what am I doing wrong?
The output I get:
```
The contents of this list are:
5
Traceback (most recent call last):
File "<stdin>", line 92, in <module>
File "<string>", line 88, in <module>
File "<string>", line 80, in display
AttributeError: 'function' object has no attribute 'data'
``` | 2015/05/13 | [
"https://Stackoverflow.com/questions/30211962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4615385/"
] | You assigned the `Node.getNext` *method* to your `Node.next` attribute in your `OrderedList.remove` method:
```
else:
previous.setNext(current.getNext)
```
You can see this by introspecting your `myList.head` attribute:
```
>>> vars(myList.head)
{'data': 5, 'next': <bound method Node.getNext of <__main__.Node object at 0x105a726d8>>}
```
You wanted to *call* the method there; otherwise you'll end up with `Node.getNext()` returning that method references rather than a `Node()` instance.
Fixing that mistake, your code appears to work:
```
The contents of this list are:
5
30
The contents of this list are:
30
30
``` | I think you got the recursive structure of this so-constructed ordered list. So, this is maybe just a typo - correct it like this:
```
class OrderedList:
def __init__(self):
self.head = Node(None)
```
then there is one more typo left, that can be easily found.
Code snipped to comment below:
```
def remove(self, item):
previous = None
current = self.head
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if current == None:
print "Element not found"
return
...
``` |
10,848,000 | I have an document inline script tag with a javascript function but I need to escape the second $ symbol? Why not escaping the both, i.e. the first and the second?
```
$js = "<script>$(function(){\$('#slider').anythingSlider({autoPlay: true, delay: 5000, animationTime: 400, easing: \"easeInOutExpo\"});});</script>";
``` | 2012/06/01 | [
"https://Stackoverflow.com/questions/10848000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340457/"
] | Because you use `"` quote string, and php's variable use `$`, the `$` need to escape inside a double quote string, or php parse will think that to be a variable. | Your second `$` character is preceeded by a curly brace `{`, thus triggers the [complex (curly) syntax](http://bg.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex) for variable expansion. Your first `$` does not have a curly brace, and is not followed by a valid identifier, thus does not need the backslash. |
10,848,000 | I have an document inline script tag with a javascript function but I need to escape the second $ symbol? Why not escaping the both, i.e. the first and the second?
```
$js = "<script>$(function(){\$('#slider').anythingSlider({autoPlay: true, delay: 5000, animationTime: 400, easing: \"easeInOutExpo\"});});</script>";
``` | 2012/06/01 | [
"https://Stackoverflow.com/questions/10848000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340457/"
] | The escaping is for the PHP.
Since you use double Quotes `"..."`, any `$..` terms within will have special meaning for the PHP parser (variable substitution).
Actually, you should also escape the first occurence of `$` in your string, or switch to a single quote string `'...'`. | Your second `$` character is preceeded by a curly brace `{`, thus triggers the [complex (curly) syntax](http://bg.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex) for variable expansion. Your first `$` does not have a curly brace, and is not followed by a valid identifier, thus does not need the backslash. |
60,387,550 | So I have a class called `ClientFactory` that I import into my project using a jar. It looks like this:
```
@Component
public class ClientFactory {
@Autowired
private Client client;
public ClientFactory() {
}
public Client get() {
return this.client;
}
}
```
and my class that uses this looks like:
```
@SpringBootApplication(scanBasePackages = {"path.to.client.*"})
@EnableAutoConfiguration
public class ProjectClient {
@Autowired
public ClientFactory clientFactory;
public ProjectClient() {}
public String getSomething(String something){
Client client = (Client) clientFactory.get();
return "x";
}
}
```
And I call this piece of code from my test class:
```
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Disabled
@TestPropertySource(properties = { //
"some.property=value", //
})
public class SomeTests {
@Autowired
ProjectClient p;
@Test
public void sampleTest() throws Exception {
p.getSomething("sample");
}
}
```
and I get the following error:
```
Field clientFactory in ProjectClient required a bean of type 'ClientFactory' that could not be found.
Action:
Consider defining a bean of type 'ClientFactory' in your configuration.
```
I've tried all combinations of Entity, Component and Package scans but nothing seems to be working. The application simply cannot find that bean, I've googled high and low and can't seem to find a way to get this working - I'm new to Spring boot - please help :( | 2020/02/25 | [
"https://Stackoverflow.com/questions/60387550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474572/"
] | I believe this class isn't compiling properly.
```
@Component
public class ClientFactory {
@Autowired
private Client client;
public Factory() {
}
public Client get() {
return this.client;
}
}
```
While Class name is **ClientFactory** the constructor been defined as **Factory**, which isn't possible for compiler to compile it.
Would you please change **Factory to ClientFactory** *(OR Remove default constructor If you don't have specific use)* and try again | Looks like you have forgotten to add `@RunWith(SpringRunner.class)` on your test class. |
60,387,550 | So I have a class called `ClientFactory` that I import into my project using a jar. It looks like this:
```
@Component
public class ClientFactory {
@Autowired
private Client client;
public ClientFactory() {
}
public Client get() {
return this.client;
}
}
```
and my class that uses this looks like:
```
@SpringBootApplication(scanBasePackages = {"path.to.client.*"})
@EnableAutoConfiguration
public class ProjectClient {
@Autowired
public ClientFactory clientFactory;
public ProjectClient() {}
public String getSomething(String something){
Client client = (Client) clientFactory.get();
return "x";
}
}
```
And I call this piece of code from my test class:
```
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Disabled
@TestPropertySource(properties = { //
"some.property=value", //
})
public class SomeTests {
@Autowired
ProjectClient p;
@Test
public void sampleTest() throws Exception {
p.getSomething("sample");
}
}
```
and I get the following error:
```
Field clientFactory in ProjectClient required a bean of type 'ClientFactory' that could not be found.
Action:
Consider defining a bean of type 'ClientFactory' in your configuration.
```
I've tried all combinations of Entity, Component and Package scans but nothing seems to be working. The application simply cannot find that bean, I've googled high and low and can't seem to find a way to get this working - I'm new to Spring boot - please help :( | 2020/02/25 | [
"https://Stackoverflow.com/questions/60387550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474572/"
] | Create `clientfactory` with bean annotation since you are referring `clientFactory` by importing from jar
```
@Bean
public Clientfactory clientfactory () {
return new Clientfactory ();
}
``` | Looks like you have forgotten to add `@RunWith(SpringRunner.class)` on your test class. |
60,387,550 | So I have a class called `ClientFactory` that I import into my project using a jar. It looks like this:
```
@Component
public class ClientFactory {
@Autowired
private Client client;
public ClientFactory() {
}
public Client get() {
return this.client;
}
}
```
and my class that uses this looks like:
```
@SpringBootApplication(scanBasePackages = {"path.to.client.*"})
@EnableAutoConfiguration
public class ProjectClient {
@Autowired
public ClientFactory clientFactory;
public ProjectClient() {}
public String getSomething(String something){
Client client = (Client) clientFactory.get();
return "x";
}
}
```
And I call this piece of code from my test class:
```
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Disabled
@TestPropertySource(properties = { //
"some.property=value", //
})
public class SomeTests {
@Autowired
ProjectClient p;
@Test
public void sampleTest() throws Exception {
p.getSomething("sample");
}
}
```
and I get the following error:
```
Field clientFactory in ProjectClient required a bean of type 'ClientFactory' that could not be found.
Action:
Consider defining a bean of type 'ClientFactory' in your configuration.
```
I've tried all combinations of Entity, Component and Package scans but nothing seems to be working. The application simply cannot find that bean, I've googled high and low and can't seem to find a way to get this working - I'm new to Spring boot - please help :( | 2020/02/25 | [
"https://Stackoverflow.com/questions/60387550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474572/"
] | It took me too long but I figured it out. I made a change to `ProjectClient` as follows:
```
@Service
@ComponentScan(basePackages = {"path.to.*"})
public class ProjectClient {
```
I'm guessing my path to client was incorrect or undetectable (I used the same path for importing that class). | Looks like you have forgotten to add `@RunWith(SpringRunner.class)` on your test class. |
4,908,594 | I have made some user-defined exceptions and I would like to add an error level to each exception. forexample userInputerror, and internalError. The reason I'm coding this, is because I want to learn about exceptions so that's why I am reinventing the wheel instead of using log4net.
My code looks like this.
I have a class called MyException:
```
namespace ExceptionHandling
{
public class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
```
One of my exceptions is an IntParseException, this class looks like this:
```
namespace ExceptionTester
{
class IntParseException : MyException
{
string dataToParse;
public IntParseException(string dataToParse)
: base(" [ERROR] Could not parse " + dataToParse + " to int")
{
this.dataToParse = dataToParse;
}
public IntParseException(string dataToParse, Exception innerexception)
: base(" [ERROR] Could not parse " + dataToParse + " to int", innerexception)
{
this.dataToParse = dataToParse;
}
}
```
}
In my mainform, I am handling my exception like this:
```
private void btnSave_Click(object sender, EventArgs e)
{
try
{
try
{
int.Parse(txtNumber.Text);
}
catch (Exception ex)
{
throw new IntParseException(txtNumber.Text, ex);
}
}
catch (Exception ex)
{
LogWriter lw = new LogWriter(ex.Source, ex.TargetSite.ToString(), ex.Message);
logwindow.upDateLogWindow();
MessageBox.Show("Please enter a number");
}
}
```
I'm logging my exceptions and that class looks liked this:
```
namespace ExceptionTester
{
class LogWriter
{
public LogWriter(string exSource, string exTargetSite, string exMessage)
{
StreamWriter SW;
SW = File.AppendText(@"logfile.txt");
string timeStamp = "[" + DateTime.Now + "] ";
string source = "An error occured in the application ";
string targetSite = ", while executing the method: ";
SW.WriteLine(timeStamp + source + exSource + targetSite +exTargetSite + exMessage);
SW.Flush();
SW.Close();
}
}
}
```
So my question is, how do I add an enum type to my exceptions which would make it possible for me to chose which kinds of exceptions I want to log. forexample, at somepoint I would like to log all exceptions but at another time I only want to log userInputErrors. | 2011/02/05 | [
"https://Stackoverflow.com/questions/4908594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | BTW, Microsoft no longer recommends that you derive from `ApplicationException`. Derive directly from `Exception`, instead.
Also, in your logging, be certain to log the entire exception. Use ex.ToString(), not ex.Message, etc. This will guarantee you see everything the exception class wants you to see, including all inner exceptions. | If you're just trying to log certain exceptions, why not just make that decision based on what type of exception is thrown, and forego this reinvention of the wheel as you call it?
```
try
{
// do stuff that might throw exception
}
catch(ExceptionType1 ex1)
{
// Ignore
}
catch(ExceptionType2 ex2)
{
// Log
}
```
However, it would be trivial to add an enum to your custom exception, though I DO NOT CONDONE THIS HORSE HOCKEY!
```
enum ExceptionLevel
{
One, Two, Three
}
class MyException : ApplicationException
{
ExceptionLevel ExceptionLevel;
}
``` |
4,908,594 | I have made some user-defined exceptions and I would like to add an error level to each exception. forexample userInputerror, and internalError. The reason I'm coding this, is because I want to learn about exceptions so that's why I am reinventing the wheel instead of using log4net.
My code looks like this.
I have a class called MyException:
```
namespace ExceptionHandling
{
public class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
```
One of my exceptions is an IntParseException, this class looks like this:
```
namespace ExceptionTester
{
class IntParseException : MyException
{
string dataToParse;
public IntParseException(string dataToParse)
: base(" [ERROR] Could not parse " + dataToParse + " to int")
{
this.dataToParse = dataToParse;
}
public IntParseException(string dataToParse, Exception innerexception)
: base(" [ERROR] Could not parse " + dataToParse + " to int", innerexception)
{
this.dataToParse = dataToParse;
}
}
```
}
In my mainform, I am handling my exception like this:
```
private void btnSave_Click(object sender, EventArgs e)
{
try
{
try
{
int.Parse(txtNumber.Text);
}
catch (Exception ex)
{
throw new IntParseException(txtNumber.Text, ex);
}
}
catch (Exception ex)
{
LogWriter lw = new LogWriter(ex.Source, ex.TargetSite.ToString(), ex.Message);
logwindow.upDateLogWindow();
MessageBox.Show("Please enter a number");
}
}
```
I'm logging my exceptions and that class looks liked this:
```
namespace ExceptionTester
{
class LogWriter
{
public LogWriter(string exSource, string exTargetSite, string exMessage)
{
StreamWriter SW;
SW = File.AppendText(@"logfile.txt");
string timeStamp = "[" + DateTime.Now + "] ";
string source = "An error occured in the application ";
string targetSite = ", while executing the method: ";
SW.WriteLine(timeStamp + source + exSource + targetSite +exTargetSite + exMessage);
SW.Flush();
SW.Close();
}
}
}
```
So my question is, how do I add an enum type to my exceptions which would make it possible for me to chose which kinds of exceptions I want to log. forexample, at somepoint I would like to log all exceptions but at another time I only want to log userInputErrors. | 2011/02/05 | [
"https://Stackoverflow.com/questions/4908594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | BTW, Microsoft no longer recommends that you derive from `ApplicationException`. Derive directly from `Exception`, instead.
Also, in your logging, be certain to log the entire exception. Use ex.ToString(), not ex.Message, etc. This will guarantee you see everything the exception class wants you to see, including all inner exceptions. | I suggest creating a new base exception class inheriting from Application Exception, which include the enum:s
```
public enum ErrorLevel { UserInputError, DatabaseError, OtherError... };
public class BaseException : ApplicationException {
protected ErrorLevel _errorLevel;
...
}
```
Derive all your exception from this base class, and assign the level as needed - maybe in the constructors, or using a parameter passed from the app. |
4,682 | I would like my browser to launch Gmail when I click on a `mailto` link in a website.
At the moment I don't have any mail clients configured at all, which results in the following:
* IE: displays the message
>
> Could not perform this operation because the default mail client is not properly installed.
>
>
* Chrome: nothing happens
* Firefox: nothing happens
Note: Running Windows 7. | 2010/07/25 | [
"https://webapps.stackexchange.com/questions/4682",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/342/"
] | You can install [Google Talk](http://www.google.com/talk/) and from settings check the: `Open Gmail when I click on email links`.

(it's been a while since I stopped using Windows so I don't know how can you do it manually) | Use [Google Pack](http://pack.google.com/intl/en-gb/pack_installer.html) and download the Google Apps that way - works here. |
4,682 | I would like my browser to launch Gmail when I click on a `mailto` link in a website.
At the moment I don't have any mail clients configured at all, which results in the following:
* IE: displays the message
>
> Could not perform this operation because the default mail client is not properly installed.
>
>
* Chrome: nothing happens
* Firefox: nothing happens
Note: Running Windows 7. | 2010/07/25 | [
"https://webapps.stackexchange.com/questions/4682",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/342/"
] | If you have Google Talk or the Google Notifier installed, both of these have settings that allow GMail to be used as the default mail program.
For Internet Explorer, you'll need to use one of the options above.
For Firefox, you can use [GMailTo](http://userscripts.org/scripts/show/5722) or change the default client Firefox uses in the [settings](http://www.ghacks.net/2008/07/04/make-gmail-the-default-firefox-3-mail-client/).
For Chrome, you have to use an extension that supports it. Better Gmail has a bunch of other features for GMail that let you do this. There is an official [Send From GMail](https://chrome.google.com/extensions/detail/pgphcomnlaojlmmcjmiddhdapjpbgeoc) extension, and if you don't like that that adds a button to the toolbar, there is [Send Using GMail](https://chrome.google.com/extensions/detail/ahldefgplekckalfcolhhnljbbgaiboc) which doesn't add that button. | Use [Google Pack](http://pack.google.com/intl/en-gb/pack_installer.html) and download the Google Apps that way - works here. |
4,682 | I would like my browser to launch Gmail when I click on a `mailto` link in a website.
At the moment I don't have any mail clients configured at all, which results in the following:
* IE: displays the message
>
> Could not perform this operation because the default mail client is not properly installed.
>
>
* Chrome: nothing happens
* Firefox: nothing happens
Note: Running Windows 7. | 2010/07/25 | [
"https://webapps.stackexchange.com/questions/4682",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/342/"
] | If you have Google Talk or the Google Notifier installed, both of these have settings that allow GMail to be used as the default mail program.
For Internet Explorer, you'll need to use one of the options above.
For Firefox, you can use [GMailTo](http://userscripts.org/scripts/show/5722) or change the default client Firefox uses in the [settings](http://www.ghacks.net/2008/07/04/make-gmail-the-default-firefox-3-mail-client/).
For Chrome, you have to use an extension that supports it. Better Gmail has a bunch of other features for GMail that let you do this. There is an official [Send From GMail](https://chrome.google.com/extensions/detail/pgphcomnlaojlmmcjmiddhdapjpbgeoc) extension, and if you don't like that that adds a button to the toolbar, there is [Send Using GMail](https://chrome.google.com/extensions/detail/ahldefgplekckalfcolhhnljbbgaiboc) which doesn't add that button. | You can install [Google Talk](http://www.google.com/talk/) and from settings check the: `Open Gmail when I click on email links`.

(it's been a while since I stopped using Windows so I don't know how can you do it manually) |
9,393,834 | I'm using CanCan in a project to manage different role level on each entity for each project.
I'm doing this:
```
# encoding: utf-8
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.is_admin == true
can :manage, :all
else
can :read, :all
Project.all.each do |project|
current_role_name = user.roles.find_by_project_id(project.id).role_name.name
if current_role_name.eql?'Auteur senior'
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
elsif current_role_name.eql?'Auteur junior'
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
elsif current_role_name.eql?'Équipe phylogéniste'
can :manage, [Attachment], :project_id => project.id
can :manage, [Text, Asset], :project_id => project.id, :user_level => current_role_name
end
end
end
end
end
```
It works when I check the user role\_name but after when I want to use condition like this:
```
can :update, Text, :project_id => project.id, :user_level => current_role_name
```
The condition doesn't have any effect. How can I make it work? | 2012/02/22 | [
"https://Stackoverflow.com/questions/9393834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616095/"
] | I finally found the solution :
In concerned controller I replaced authorize\_resource by load\_and\_authorize\_resource and that's it. | What I usely do is:
**1- defining roles in my User class and affect them to users.**
```
class User
# CanCan roles ( see Users::Ability)
ROLES = %w[auteur_senior auteur_junior]
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject do |r|
((roles_mask || 0) & 2**ROLES.index(r)).zero?
end
end
def is?(role)
roles.include?(role.to_s)
end
# define all bollean set/get methods for roles
ROLES.each do |r|
define_method "is_#{r}" do
self.roles += [r]
self
end
define_method "is_#{r}?" do
roles.include?(r)
self
end
end
end
```
**2-In the ability I affect the capabilities of each roles**
```
class Ability
include CanCan::Ability
def initialize(user)
@user = user || User.new # for guest
@user.roles.each { |role| send(role) }
end
def auteur_junior
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
end
def auteur_scenior
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
end
end
``` |
9,393,834 | I'm using CanCan in a project to manage different role level on each entity for each project.
I'm doing this:
```
# encoding: utf-8
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.is_admin == true
can :manage, :all
else
can :read, :all
Project.all.each do |project|
current_role_name = user.roles.find_by_project_id(project.id).role_name.name
if current_role_name.eql?'Auteur senior'
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
elsif current_role_name.eql?'Auteur junior'
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
elsif current_role_name.eql?'Équipe phylogéniste'
can :manage, [Attachment], :project_id => project.id
can :manage, [Text, Asset], :project_id => project.id, :user_level => current_role_name
end
end
end
end
end
```
It works when I check the user role\_name but after when I want to use condition like this:
```
can :update, Text, :project_id => project.id, :user_level => current_role_name
```
The condition doesn't have any effect. How can I make it work? | 2012/02/22 | [
"https://Stackoverflow.com/questions/9393834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616095/"
] | What I usely do is:
**1- defining roles in my User class and affect them to users.**
```
class User
# CanCan roles ( see Users::Ability)
ROLES = %w[auteur_senior auteur_junior]
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject do |r|
((roles_mask || 0) & 2**ROLES.index(r)).zero?
end
end
def is?(role)
roles.include?(role.to_s)
end
# define all bollean set/get methods for roles
ROLES.each do |r|
define_method "is_#{r}" do
self.roles += [r]
self
end
define_method "is_#{r}?" do
roles.include?(r)
self
end
end
end
```
**2-In the ability I affect the capabilities of each roles**
```
class Ability
include CanCan::Ability
def initialize(user)
@user = user || User.new # for guest
@user.roles.each { |role| send(role) }
end
def auteur_junior
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
end
def auteur_scenior
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
end
end
``` | The `authorize_resource` method calls `authorize!` on the class unless it is passed an instance. Without using `load_resource` or `load_and_authorize_resource`, you're passing nil to the `authorize_resource` before\_filter.
[Example from the CanCan documentation](http://www.rubydoc.info/github/ryanb/cancan/CanCan%2FControllerAdditions%2FClassMethods%3Aauthorize_resource):
```
#authorize_resource(*args) ⇒ Object
authorize!(params[:action].to_sym, @article || Article)
```
If you want to load records from the database with your own method (instead of CanCan's `load_resource`) and have more control, then you can create your own method like `load_thing` and call it with `prepend_before_filter :load_thing`. **This will load the record into the instance variable before `authorize_resource` is called, ensuring the instance variable isn't nil and the rules specified in the ability file are checked.** |
9,393,834 | I'm using CanCan in a project to manage different role level on each entity for each project.
I'm doing this:
```
# encoding: utf-8
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.is_admin == true
can :manage, :all
else
can :read, :all
Project.all.each do |project|
current_role_name = user.roles.find_by_project_id(project.id).role_name.name
if current_role_name.eql?'Auteur senior'
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
elsif current_role_name.eql?'Auteur junior'
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
elsif current_role_name.eql?'Équipe phylogéniste'
can :manage, [Attachment], :project_id => project.id
can :manage, [Text, Asset], :project_id => project.id, :user_level => current_role_name
end
end
end
end
end
```
It works when I check the user role\_name but after when I want to use condition like this:
```
can :update, Text, :project_id => project.id, :user_level => current_role_name
```
The condition doesn't have any effect. How can I make it work? | 2012/02/22 | [
"https://Stackoverflow.com/questions/9393834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616095/"
] | I finally found the solution :
In concerned controller I replaced authorize\_resource by load\_and\_authorize\_resource and that's it. | The `authorize_resource` method calls `authorize!` on the class unless it is passed an instance. Without using `load_resource` or `load_and_authorize_resource`, you're passing nil to the `authorize_resource` before\_filter.
[Example from the CanCan documentation](http://www.rubydoc.info/github/ryanb/cancan/CanCan%2FControllerAdditions%2FClassMethods%3Aauthorize_resource):
```
#authorize_resource(*args) ⇒ Object
authorize!(params[:action].to_sym, @article || Article)
```
If you want to load records from the database with your own method (instead of CanCan's `load_resource`) and have more control, then you can create your own method like `load_thing` and call it with `prepend_before_filter :load_thing`. **This will load the record into the instance variable before `authorize_resource` is called, ensuring the instance variable isn't nil and the rules specified in the ability file are checked.** |
1,072,261 | I have a local repository I'm working on and its remote is hosted on GitHub. I recently created a branch and started working on it, making several commits and now wish to push the branch to GitHub and be able to pull it to another cloned repository. How do I do this? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1072261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] | As you have set up the remotes already, the command is just
```
git push origin branch-name
```
on the first push.
Afterward, using `git push origin` would push all branches with the matching name on remote. | Make sure that your remote URL is using SSH syntax and not just Git protocol syntax. If you run,
```
git remote show origin
```
the URL printed should look something like,
```
git@github.com:yourname/projectname.git
```
You need the URL too to look like that if you want to be able to push. If you are just a public user (without write access) the URL will look like,
```
git://github.com/yourname/projectname.git
```
If yours looks like the latter then you can manually edit it in your projects `.git/config` file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.