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 |
|---|---|---|---|---|---|
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | De la Villa's "100 Endgames you must know", though apparently a good book seems to have been plagued by an abundance of typos and mistakes as [detailed in this blogpost.](http://streathambrixtonchess.blogspot.com.es/2012/08/sixty-memorable-annotations.html)
So although the culprit in this case has been the 2nd edition, maybe it does make sense to go for the latest edition. Here you can look at [the errata page](https://www.newinchess.com/support/?PageID=600) which presumably contains errors that have now been corrected, although as I mentioned some of these corrections probably already happened in the third edition. | I have the book on Chessable (popular site for reading chess books like this one):
>
> <https://www.chessable.com/endgame-book/100-endgames-you-must-know/5193/>
>
>
>
[](https://i.stack.imgur.com/jTMne.png)
The difference in edition come from improved annotations and error checking. That's common for all books (chess or not). If you already have the 3rd edition, there's no point to get the newer edition.
Please note the edition is not specified in the screenshot because it's always the latest edition. I'd recommend to get an ebook version (e.g. Chessable or other publishers). New In Chess updates their ebooks for free, you will get a free update when they release the 5th, 6th edition etc. |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | I have the book on Chessable (popular site for reading chess books like this one):
>
> <https://www.chessable.com/endgame-book/100-endgames-you-must-know/5193/>
>
>
>
[](https://i.stack.imgur.com/jTMne.png)
The difference in edition come from improved annotations and error checking. That's common for all books (chess or not). If you already have the 3rd edition, there's no point to get the newer edition.
Please note the edition is not specified in the screenshot because it's always the latest edition. I'd recommend to get an ebook version (e.g. Chessable or other publishers). New In Chess updates their ebooks for free, you will get a free update when they release the 5th, 6th edition etc. | I know this answer is coming late, but as someone who had the 3rd edition and upgrated to the 4th edition I can answer this definitely. The ONLY difference in the new edition is that diagrams have an indicator of who is to move, and glancing at the text below the diagram it's very easy to see who is to move if you can't already figure it out based on the particular ending you are studying, if you already have the 3rd and you want this "feature" just go through the book with a pencil and mark every diagram with W/B for who has the move, everything else in the book word for word is IDENITCAL, yes I went through each page and did not see ANY difference whatsoever. Those that said that updated versions where usually money grabs nailed this one completely. The publisher New In Chess was extremely deceptive selling this as a new version complete with a new book cover. This could have been done in a new printing, shame on New in Chess. |
27,792,302 | I'm trying to add JSF to my webstarterapp.
I have created an JSF managed bean, but when compiling the app using the provided `build.xml`, I get the errors:
```
[javac] /Users/snowch/.../Customer.java:8: error: package javax.faces.bean does not exist
[javac] import javax.faces.bean.ManagedBean;
[javac] ^
[javac] /Users/snowch/.../Customer.java:9: error: package javax.faces.bean does not exist
[javac] import javax.faces.bean.RequestScoped;
[javac] ^
[javac] /Users/snowch/.../Customer.java:15: error: cannot find symbol
[javac] @ManagedBean
[javac] ^
[javac] symbol: class ManagedBean
[javac] /Users/snowch/.../Customer.java:16: error: cannot find symbol
[javac] @RequestScoped
[javac] ^
[javac] symbol: class RequestScoped
[javac] 4 errors
[javac] 4 warnings
```
It looks like I need to add the jsf jar to my `dep-jar` folder as it currently isn't there:
```
snowch:csjavatest snowch$ tree dep-jar/
dep-jar/
└── com.ibm.ws.javaee.jaxrs.1.1_1.0.1.jar
0 directories, 1 file
```
**Question:** Where can I download the appropriate version of the jsf library jar file? | 2015/01/06 | [
"https://Stackoverflow.com/questions/27792302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] | Below developer works article can help you (it has everything to get started with JSF2) along with required download details of lib files for Bluemix:
<http://www.ibm.com/developerworks/library/j-richfaces4/>
Although I had never worked on these things,hoping that it this article info may help you. | In the end, I updated the `build.xml` file to add a `pathelement` for `javax.faces.jar` that was sitting in my glassfish installation folder:
```
<path id="classpathDir">
<pathelement location="bin"/>
<pathelement location="dep-jar/com.ibm.ws.javaee.jaxrs.1.1_1.0.1.jar"/>
<!- added \/ -->
<pathelement location=
"/Applications/NetBeans/glassfish-4.1//glassfish/modules/javax.faces.jar"/>
<!- added /\ -->
</path>
``` |
379,988 | I'm trying to make a database and so far, I've been using strings to store my entries from a text file into an array, but this just isn't working out. Thus, I began thinking of a new way of doing it.
What I want to do:
Lets say I have a text file with the following database...
John Smith 00001 jsmith@email pw1
Rob Deniro 00002 rdeniro@email pw2
Joe Pesci 00004 jpesci@email 307 pw4
Joaq Phoenix 00005 jphoe@email 208 pw5
Alright, so basically what I'm stuck at is making this "inheritance" friendly. What's the best way to go about storing each entry? Individual strings? I've been thinking that the best way is to store each individual character until a whitespace occurs and then storing it into a string, but I'm not sure how that could be done. | 2008/12/19 | [
"https://Stackoverflow.com/questions/379988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Usually the term "database" is reserved to the standard notion of a relational database such as MySQL, MS SQL Server, Oracle etc'
So this begs the question why don't you use a standard relational database?
you might want to try looking up [TinySQL](http://www.jepstone.net/tinySQL/) | Read one line at a time with [`ifstream`](http://www.cplusplus.com/reference/iostream/ifstream/) and then use [`strtok`](http://www.cplusplus.com/reference/clibrary/cstring/strtok.html) to split each line, use the whitespace as the delimiter. You should use `string` except for the numeric values, which you can save as an `int` or a `long` if you need to support big values. It's also more wise to store the passwords in an encrypted way if you want security.
You might want to look for another solution to store your data instead of plain text for various reasons: Space, performance, security, ... It might be a good idea to try to use binary database files. |
379,988 | I'm trying to make a database and so far, I've been using strings to store my entries from a text file into an array, but this just isn't working out. Thus, I began thinking of a new way of doing it.
What I want to do:
Lets say I have a text file with the following database...
John Smith 00001 jsmith@email pw1
Rob Deniro 00002 rdeniro@email pw2
Joe Pesci 00004 jpesci@email 307 pw4
Joaq Phoenix 00005 jphoe@email 208 pw5
Alright, so basically what I'm stuck at is making this "inheritance" friendly. What's the best way to go about storing each entry? Individual strings? I've been thinking that the best way is to store each individual character until a whitespace occurs and then storing it into a string, but I'm not sure how that could be done. | 2008/12/19 | [
"https://Stackoverflow.com/questions/379988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As TomWij says, you do ifstream then strtok, but I'd recommend you escape your strings with "", not just spaces, that way you can store "something like this, for example a note about the user", that's how its done with CSV (comma separated values).
```
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)
{
std::string csvLine;
// read every line from the stream
while( std::getline(input, csvLine) )
{
std::istringstream csvStream(csvLine);
std::vector<std::string> csvColumn;
std::string csvElement;
// read every element from the line that is seperated by commas
// and put it into the vector or strings
while( std::getline(csvStream, csvElement, ',') )
{
csvColumn.push_back(csvElement);
}
output.push_back(csvColumn);
}
}
int main()
{
std::fstream file("file.csv", ios::in);
if(!file.is_open())
{
std::cout << "File not found!\n";
return 1;
}
// typedef to save typing for the following object
typedef std::vector< std::vector<std::string> > csvVector;
csvVector csvData;
readCSV(file, csvData);
// print out read data to prove reading worked
for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
{
for(std::vector<std::string>::iterator j = i->begin(); j != i->end(); ++j)
{
std::cout << *j << ", ";
}
std::cout << "\n";
}
}
```
Which brings me to the real solution, why don't you use a CSV library like [CSV module](http://www.ioplex.com/~miallen/libmba/dl/src/csv.c) or better yet, [SQLite](http://www.sqlite.org/), SQLite is dead easy to install and use, and its all around better than coding a database by hand, besides it shouldn't take you more than 1 hour to get [SQLite](http://www.sqlite.org/) into your codebase, since its API is REALLY easy.
```
#include <stdio.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
exit(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
``` | Read one line at a time with [`ifstream`](http://www.cplusplus.com/reference/iostream/ifstream/) and then use [`strtok`](http://www.cplusplus.com/reference/clibrary/cstring/strtok.html) to split each line, use the whitespace as the delimiter. You should use `string` except for the numeric values, which you can save as an `int` or a `long` if you need to support big values. It's also more wise to store the passwords in an encrypted way if you want security.
You might want to look for another solution to store your data instead of plain text for various reasons: Space, performance, security, ... It might be a good idea to try to use binary database files. |
379,988 | I'm trying to make a database and so far, I've been using strings to store my entries from a text file into an array, but this just isn't working out. Thus, I began thinking of a new way of doing it.
What I want to do:
Lets say I have a text file with the following database...
John Smith 00001 jsmith@email pw1
Rob Deniro 00002 rdeniro@email pw2
Joe Pesci 00004 jpesci@email 307 pw4
Joaq Phoenix 00005 jphoe@email 208 pw5
Alright, so basically what I'm stuck at is making this "inheritance" friendly. What's the best way to go about storing each entry? Individual strings? I've been thinking that the best way is to store each individual character until a whitespace occurs and then storing it into a string, but I'm not sure how that could be done. | 2008/12/19 | [
"https://Stackoverflow.com/questions/379988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As TomWij says, you do ifstream then strtok, but I'd recommend you escape your strings with "", not just spaces, that way you can store "something like this, for example a note about the user", that's how its done with CSV (comma separated values).
```
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)
{
std::string csvLine;
// read every line from the stream
while( std::getline(input, csvLine) )
{
std::istringstream csvStream(csvLine);
std::vector<std::string> csvColumn;
std::string csvElement;
// read every element from the line that is seperated by commas
// and put it into the vector or strings
while( std::getline(csvStream, csvElement, ',') )
{
csvColumn.push_back(csvElement);
}
output.push_back(csvColumn);
}
}
int main()
{
std::fstream file("file.csv", ios::in);
if(!file.is_open())
{
std::cout << "File not found!\n";
return 1;
}
// typedef to save typing for the following object
typedef std::vector< std::vector<std::string> > csvVector;
csvVector csvData;
readCSV(file, csvData);
// print out read data to prove reading worked
for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
{
for(std::vector<std::string>::iterator j = i->begin(); j != i->end(); ++j)
{
std::cout << *j << ", ";
}
std::cout << "\n";
}
}
```
Which brings me to the real solution, why don't you use a CSV library like [CSV module](http://www.ioplex.com/~miallen/libmba/dl/src/csv.c) or better yet, [SQLite](http://www.sqlite.org/), SQLite is dead easy to install and use, and its all around better than coding a database by hand, besides it shouldn't take you more than 1 hour to get [SQLite](http://www.sqlite.org/) into your codebase, since its API is REALLY easy.
```
#include <stdio.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
exit(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
``` | Usually the term "database" is reserved to the standard notion of a relational database such as MySQL, MS SQL Server, Oracle etc'
So this begs the question why don't you use a standard relational database?
you might want to try looking up [TinySQL](http://www.jepstone.net/tinySQL/) |
379,988 | I'm trying to make a database and so far, I've been using strings to store my entries from a text file into an array, but this just isn't working out. Thus, I began thinking of a new way of doing it.
What I want to do:
Lets say I have a text file with the following database...
John Smith 00001 jsmith@email pw1
Rob Deniro 00002 rdeniro@email pw2
Joe Pesci 00004 jpesci@email 307 pw4
Joaq Phoenix 00005 jphoe@email 208 pw5
Alright, so basically what I'm stuck at is making this "inheritance" friendly. What's the best way to go about storing each entry? Individual strings? I've been thinking that the best way is to store each individual character until a whitespace occurs and then storing it into a string, but I'm not sure how that could be done. | 2008/12/19 | [
"https://Stackoverflow.com/questions/379988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Usually the term "database" is reserved to the standard notion of a relational database such as MySQL, MS SQL Server, Oracle etc'
So this begs the question why don't you use a standard relational database?
you might want to try looking up [TinySQL](http://www.jepstone.net/tinySQL/) | ```
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
int main(int argc, char *argv[])
{
char Name[100];
char FTE[100];
cout<<"What is the file name?\n";
cin>>FTE;
ifstream myfile (FTE);
while(1)
{
myfile.getline(Name, 30, '|');
cout<<line;
cin.ignore();
}
}
```
all this does is read all your text entries seperated by the '|' Character. Good for making Flat File Databases in C++ and other using same methods. |
379,988 | I'm trying to make a database and so far, I've been using strings to store my entries from a text file into an array, but this just isn't working out. Thus, I began thinking of a new way of doing it.
What I want to do:
Lets say I have a text file with the following database...
John Smith 00001 jsmith@email pw1
Rob Deniro 00002 rdeniro@email pw2
Joe Pesci 00004 jpesci@email 307 pw4
Joaq Phoenix 00005 jphoe@email 208 pw5
Alright, so basically what I'm stuck at is making this "inheritance" friendly. What's the best way to go about storing each entry? Individual strings? I've been thinking that the best way is to store each individual character until a whitespace occurs and then storing it into a string, but I'm not sure how that could be done. | 2008/12/19 | [
"https://Stackoverflow.com/questions/379988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As TomWij says, you do ifstream then strtok, but I'd recommend you escape your strings with "", not just spaces, that way you can store "something like this, for example a note about the user", that's how its done with CSV (comma separated values).
```
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)
{
std::string csvLine;
// read every line from the stream
while( std::getline(input, csvLine) )
{
std::istringstream csvStream(csvLine);
std::vector<std::string> csvColumn;
std::string csvElement;
// read every element from the line that is seperated by commas
// and put it into the vector or strings
while( std::getline(csvStream, csvElement, ',') )
{
csvColumn.push_back(csvElement);
}
output.push_back(csvColumn);
}
}
int main()
{
std::fstream file("file.csv", ios::in);
if(!file.is_open())
{
std::cout << "File not found!\n";
return 1;
}
// typedef to save typing for the following object
typedef std::vector< std::vector<std::string> > csvVector;
csvVector csvData;
readCSV(file, csvData);
// print out read data to prove reading worked
for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
{
for(std::vector<std::string>::iterator j = i->begin(); j != i->end(); ++j)
{
std::cout << *j << ", ";
}
std::cout << "\n";
}
}
```
Which brings me to the real solution, why don't you use a CSV library like [CSV module](http://www.ioplex.com/~miallen/libmba/dl/src/csv.c) or better yet, [SQLite](http://www.sqlite.org/), SQLite is dead easy to install and use, and its all around better than coding a database by hand, besides it shouldn't take you more than 1 hour to get [SQLite](http://www.sqlite.org/) into your codebase, since its API is REALLY easy.
```
#include <stdio.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
exit(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
``` | ```
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
int main(int argc, char *argv[])
{
char Name[100];
char FTE[100];
cout<<"What is the file name?\n";
cin>>FTE;
ifstream myfile (FTE);
while(1)
{
myfile.getline(Name, 30, '|');
cout<<line;
cin.ignore();
}
}
```
all this does is read all your text entries seperated by the '|' Character. Good for making Flat File Databases in C++ and other using same methods. |
43,609,774 | I have a java servlet that sends a json object to a jsp page in a javascript variabile with array format.
Here is my servlet ( a part of it):
```
List<HistoryLeavesScalar> returnedPastInfo = SaveDAO.getPastInformation(username);
JSONArray jsonArray = new JSONArray(returnedPastInfo);
String s = jsonArray.toString();
System.out.println("\n\n"+"JSON ARRAY is : "+s);
HttpSession session = request.getSession(true);
session.setAttribute("jsonArray",jsonArray);
this.getServletContext().getRequestDispatcher("/calendar.jsp")
.forward(request, response);
```
that system.out.print JSON is something like this in my console:
[{"endDate":"2017-04-22","req":"2017-04-19","nr":2,"type":"CO","startDate":"2017-04-20","Dep":"2017-04-19"},{"endDate":"2017-04-22","req":"2017-04-20","nr":3,"type":"CM","startDate":"2017-04-20","Dep":"2017-04-19"}]
This Json Array I want to be visible in javascript tag like this in that format only: ( this is calendar.jsp - a part of it)
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="javax.servlet.jsp.jstl.core.*"%>
<%@ page import="javax.servlet.jsp.el.*" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<script type="text/javascript">
var USER_DAYS = [
<c:forEach items="${jsonArray}" var="jsonArray">
{
id: '${jsonArray.nr}',
date: '${jsonArray.req}',
title: '${jsonArray.type}',
startDate: '${jsonArray.startDate',
endDate: '${jsonArray.endDate',
allDay: true,
className: 'done'
}
</c:forEach>
];
</script>
```
I don't know how to access the values from that json that comes from the servlet in USER\_DAYS variable (javascript). How to put the values from json in id, date, title, startDate, endDate.
I don't know if jstl works in a javascript tag. I don't know how to print that values ( whatever they are - it can contain many information, all in that format).
I want to mention that, if I change the javascript variable into somthing like this: it works just fine. But these are values which I have handwritten, but now I want them dynamically...and this information must come from servlet into calendar.jsp.
```
var USER_DAYS = [
{
id: 1,
date: '2017-04-05',
title: 'CO',
start: new Date(2017, 3, 5),
end: new Date(2017, 3, 7),
allDay: true,
className: 'done'
},
```
Can someone help me? | 2017/04/25 | [
"https://Stackoverflow.com/questions/43609774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6337109/"
] | You already have it as string:
```
String s = jsonArray.toString();
```
Store `s` in session instead of `jsonArray`;
```
session.setAttribute("jsonArray", s);
```
And print it in the servlet:
```
var USER_DAYS = ${jsonArray};
```
---
**MY TEST**
Java servlet (with sample data):
[](https://i.stack.imgur.com/GOIUI.png)
`bingo.jsp`:
[](https://i.stack.imgur.com/rESPQ.png)
HTML result:
[](https://i.stack.imgur.com/gA2En.png)
Rendered result:
[](https://i.stack.imgur.com/Z8eH3.png)
It works. | you can write like this
```
<script>
var DAYS = '${jsonArray}';
if(DAYS.length > 0 ){
var USER_DAYS = {
id: DAYS[0].nr,
date: DAYS[0].req,
title: DAYS[0].type,
startDate: new Date(DAYS[0].startDate),
endDate: new Date(DAYS[0].endDate),
allDay: true,
className: 'done'
};
}
</script>
``` |
43,609,774 | I have a java servlet that sends a json object to a jsp page in a javascript variabile with array format.
Here is my servlet ( a part of it):
```
List<HistoryLeavesScalar> returnedPastInfo = SaveDAO.getPastInformation(username);
JSONArray jsonArray = new JSONArray(returnedPastInfo);
String s = jsonArray.toString();
System.out.println("\n\n"+"JSON ARRAY is : "+s);
HttpSession session = request.getSession(true);
session.setAttribute("jsonArray",jsonArray);
this.getServletContext().getRequestDispatcher("/calendar.jsp")
.forward(request, response);
```
that system.out.print JSON is something like this in my console:
[{"endDate":"2017-04-22","req":"2017-04-19","nr":2,"type":"CO","startDate":"2017-04-20","Dep":"2017-04-19"},{"endDate":"2017-04-22","req":"2017-04-20","nr":3,"type":"CM","startDate":"2017-04-20","Dep":"2017-04-19"}]
This Json Array I want to be visible in javascript tag like this in that format only: ( this is calendar.jsp - a part of it)
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="javax.servlet.jsp.jstl.core.*"%>
<%@ page import="javax.servlet.jsp.el.*" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<script type="text/javascript">
var USER_DAYS = [
<c:forEach items="${jsonArray}" var="jsonArray">
{
id: '${jsonArray.nr}',
date: '${jsonArray.req}',
title: '${jsonArray.type}',
startDate: '${jsonArray.startDate',
endDate: '${jsonArray.endDate',
allDay: true,
className: 'done'
}
</c:forEach>
];
</script>
```
I don't know how to access the values from that json that comes from the servlet in USER\_DAYS variable (javascript). How to put the values from json in id, date, title, startDate, endDate.
I don't know if jstl works in a javascript tag. I don't know how to print that values ( whatever they are - it can contain many information, all in that format).
I want to mention that, if I change the javascript variable into somthing like this: it works just fine. But these are values which I have handwritten, but now I want them dynamically...and this information must come from servlet into calendar.jsp.
```
var USER_DAYS = [
{
id: 1,
date: '2017-04-05',
title: 'CO',
start: new Date(2017, 3, 5),
end: new Date(2017, 3, 7),
allDay: true,
className: 'done'
},
```
Can someone help me? | 2017/04/25 | [
"https://Stackoverflow.com/questions/43609774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6337109/"
] | You already have it as string:
```
String s = jsonArray.toString();
```
Store `s` in session instead of `jsonArray`;
```
session.setAttribute("jsonArray", s);
```
And print it in the servlet:
```
var USER_DAYS = ${jsonArray};
```
---
**MY TEST**
Java servlet (with sample data):
[](https://i.stack.imgur.com/GOIUI.png)
`bingo.jsp`:
[](https://i.stack.imgur.com/rESPQ.png)
HTML result:
[](https://i.stack.imgur.com/gA2En.png)
Rendered result:
[](https://i.stack.imgur.com/Z8eH3.png)
It works. | You can parse your `jsonString` to javascript `JSON` object. Then you want to change some of the object key's of your `json` object, delete one more extra key `[e.g "Dep":"2017-04-19"]` and at last want add two key's with values in your final json object.
```
allDay: true,
className: 'done'
```
Here is the solution.set data as a json string.
```
session.setAttribute("jsonArray",jsonArray.toString());
```
In your jsp
```
var USER_DAYS = JSON.parse('${jsonArray}');
```
This will make a `JSON` object named `USER_DAYS`.
And at last modify your JSON object,
```js
var USER_DAYS = JSON.parse('[{"endDate":"2017-04-22","req":"2017-04-19","nr":2,"type":"CO","startDate":"2017-04-20","Dep":"2017-04-19"},{"endDate":"2017-04-22","req":"2017-04-20","nr":3,"type":"CM","startDate":"2017-04-20","Dep":"2017-04-19"}]');
console.log('Original JSON = ' +JSON.stringify(USER_DAYS));
USER_DAYS.forEach(function(e) {
e.id = e.nr;
delete e.nr;
e.date = e.req;
delete e.req;
e.title=e.type;
delete e.type;
e.allDay= true;
e.className='done';
delete e.Dep;
});
console.log('Modified JSON = '+JSON.stringify(USER_DAYS));
```
See the `[JSFIDDLE](https://jsfiddle.net/ataur63/fw0b0h2s/1/)` |
43,487,492 | I'm using the terminal which is integrated in Visual Studio Code. When I scroll up it shows the previous lines, but they are not enough for me. I need to see more lines.
How can I increase the total number of lines that are displayed by the terminal in VS Code? | 2017/04/19 | [
"https://Stackoverflow.com/questions/43487492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470116/"
] | There is a way to change number of lines for that you have to go:
>
> file-->preferences-->configuration
>
>
>
Then, it will open file `settings.json` you should to search `Integrated terminal` and then you search for `terminal.integrated.scrollback` copy and paste this sentence on your user configuration so like this:
[](https://i.stack.imgur.com/RNpWm.png)
Change numbers of line as you want. That is it. | 1. Go to `File -> Preferences -> Settings`
[](https://i.stack.imgur.com/oiieb.jpg)
2. Search for `terminal` and open `settings.json`
[](https://i.stack.imgur.com/J9yQg.jpg)
3. Add new line to `settings.json`
```
"terminal.integrated.scrollback": 100000000,
```
[](https://i.stack.imgur.com/RsoNU.png) |
43,487,492 | I'm using the terminal which is integrated in Visual Studio Code. When I scroll up it shows the previous lines, but they are not enough for me. I need to see more lines.
How can I increase the total number of lines that are displayed by the terminal in VS Code? | 2017/04/19 | [
"https://Stackoverflow.com/questions/43487492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470116/"
] | There is a way to change number of lines for that you have to go:
>
> file-->preferences-->configuration
>
>
>
Then, it will open file `settings.json` you should to search `Integrated terminal` and then you search for `terminal.integrated.scrollback` copy and paste this sentence on your user configuration so like this:
[](https://i.stack.imgur.com/RNpWm.png)
Change numbers of line as you want. That is it. | Visual Studio Code Version 1.47.3, You can do it in Files --> Preferences --> Settings then select Feature/Terminal menu. Find the "Integrated:**Scrollback**" property and change it. Save the settings.
[](https://i.stack.imgur.com/ijU2Q.png) |
43,487,492 | I'm using the terminal which is integrated in Visual Studio Code. When I scroll up it shows the previous lines, but they are not enough for me. I need to see more lines.
How can I increase the total number of lines that are displayed by the terminal in VS Code? | 2017/04/19 | [
"https://Stackoverflow.com/questions/43487492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470116/"
] | 1. Go to `File -> Preferences -> Settings`
[](https://i.stack.imgur.com/oiieb.jpg)
2. Search for `terminal` and open `settings.json`
[](https://i.stack.imgur.com/J9yQg.jpg)
3. Add new line to `settings.json`
```
"terminal.integrated.scrollback": 100000000,
```
[](https://i.stack.imgur.com/RsoNU.png) | Visual Studio Code Version 1.47.3, You can do it in Files --> Preferences --> Settings then select Feature/Terminal menu. Find the "Integrated:**Scrollback**" property and change it. Save the settings.
[](https://i.stack.imgur.com/ijU2Q.png) |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | Not with a raw C compiler unfortunately. You should try a lint tool, as splint, that might help you about this (I'm not sure, though). | >
> Is there any way to still get warnings for 0-literals
>
>
>
I don't know about one, an anyway you don't want that. The constant numeric value 0, when assigned to a pointer, is implicitly treated as `NULL` without casting it to a pointer type. |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | GCC supports a [`nonnull` attribute on function parameters](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes) that can do what you want (as long as the `-Wnonnull` warning option is enabled):
```
void* foo( int* cannot_be_null) __attribute((nonnull (1))) ;
int main(int argc, char *argv[])
{
int x;
foo(&x);
foo(0); // line 13 - generates a -Wnonnull warning
return 0;
}
```
When compiled using `gcc -c -Wnonnull test.c` I get:
```
test.c: In function 'main':
test.c:13:5: warning: null argument where non-null required (argument 1) [-Wnonnull]
```
You can force this to be an error with `-Werror=nonnull`.
Note that this warning is only thrown when the null pointer literal (another name for `0`) is used - the following code doesn't trigger the warning:
```
int* p = NULL;
foo(p);
``` | >
> Is there any way to still get warnings for 0-literals
>
>
>
I don't know about one, an anyway you don't want that. The constant numeric value 0, when assigned to a pointer, is implicitly treated as `NULL` without casting it to a pointer type. |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | Not with a raw C compiler unfortunately. You should try a lint tool, as splint, that might help you about this (I'm not sure, though). | I think conversion to null probably fairly intrinsic to the compiler - It should be easy however to statically check for these cases as they are fairly unique.
If you are expecting to pass null and not (int)0, use an explicit NULL enum or define, and then anything matching the pattern YourFunction(0); (allowing for white space) is definitely invalid. Grep could be used quite easily for this if you want to go low-tech. Various lint tools might be able to do this as Fabien suggested.
I always try to remember when coding that if you can, make wrong things look as wrong as possible, that way you can detect them all the more easily. |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | GCC supports a [`nonnull` attribute on function parameters](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes) that can do what you want (as long as the `-Wnonnull` warning option is enabled):
```
void* foo( int* cannot_be_null) __attribute((nonnull (1))) ;
int main(int argc, char *argv[])
{
int x;
foo(&x);
foo(0); // line 13 - generates a -Wnonnull warning
return 0;
}
```
When compiled using `gcc -c -Wnonnull test.c` I get:
```
test.c: In function 'main':
test.c:13:5: warning: null argument where non-null required (argument 1) [-Wnonnull]
```
You can force this to be an error with `-Werror=nonnull`.
Note that this warning is only thrown when the null pointer literal (another name for `0`) is used - the following code doesn't trigger the warning:
```
int* p = NULL;
foo(p);
``` | Not with a raw C compiler unfortunately. You should try a lint tool, as splint, that might help you about this (I'm not sure, though). |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | Not with a raw C compiler unfortunately. You should try a lint tool, as splint, that might help you about this (I'm not sure, though). | This question is similar to the question. `Should I use symbolic names like TRUE and FALSE for Boolean constants, or plain 1 and 0?`
C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's.
It is only in pointer contexts that NULL and 0 are equivalent. NULL should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void \*)0), which will not work at all in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition
```
#define NUL '\0'
```
if you must.
This information is from this [link](http://c-faq.com/null/nullor0.html) |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | GCC supports a [`nonnull` attribute on function parameters](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes) that can do what you want (as long as the `-Wnonnull` warning option is enabled):
```
void* foo( int* cannot_be_null) __attribute((nonnull (1))) ;
int main(int argc, char *argv[])
{
int x;
foo(&x);
foo(0); // line 13 - generates a -Wnonnull warning
return 0;
}
```
When compiled using `gcc -c -Wnonnull test.c` I get:
```
test.c: In function 'main':
test.c:13:5: warning: null argument where non-null required (argument 1) [-Wnonnull]
```
You can force this to be an error with `-Werror=nonnull`.
Note that this warning is only thrown when the null pointer literal (another name for `0`) is used - the following code doesn't trigger the warning:
```
int* p = NULL;
foo(p);
``` | I think conversion to null probably fairly intrinsic to the compiler - It should be easy however to statically check for these cases as they are fairly unique.
If you are expecting to pass null and not (int)0, use an explicit NULL enum or define, and then anything matching the pattern YourFunction(0); (allowing for white space) is definitely invalid. Grep could be used quite easily for this if you want to go low-tech. Various lint tools might be able to do this as Fabien suggested.
I always try to remember when coding that if you can, make wrong things look as wrong as possible, that way you can detect them all the more easily. |
14,610,581 | I dont understand why in the parent process my data is not set to what its set to in my child process. I create the shared\_data struct variable before I fork my program so it should be shared memory, correct?
Here is the code:
```
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}
``` | 2013/01/30 | [
"https://Stackoverflow.com/questions/14610581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763669/"
] | GCC supports a [`nonnull` attribute on function parameters](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes) that can do what you want (as long as the `-Wnonnull` warning option is enabled):
```
void* foo( int* cannot_be_null) __attribute((nonnull (1))) ;
int main(int argc, char *argv[])
{
int x;
foo(&x);
foo(0); // line 13 - generates a -Wnonnull warning
return 0;
}
```
When compiled using `gcc -c -Wnonnull test.c` I get:
```
test.c: In function 'main':
test.c:13:5: warning: null argument where non-null required (argument 1) [-Wnonnull]
```
You can force this to be an error with `-Werror=nonnull`.
Note that this warning is only thrown when the null pointer literal (another name for `0`) is used - the following code doesn't trigger the warning:
```
int* p = NULL;
foo(p);
``` | This question is similar to the question. `Should I use symbolic names like TRUE and FALSE for Boolean constants, or plain 1 and 0?`
C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's.
It is only in pointer contexts that NULL and 0 are equivalent. NULL should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void \*)0), which will not work at all in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition
```
#define NUL '\0'
```
if you must.
This information is from this [link](http://c-faq.com/null/nullor0.html) |
393,673 | Let's say I wanted to identify individuals who are taking an excessive amount of the blood clotting drug warfarin relative to their peers. To do this, I'm considering building a regression model that uses patient level data such as sex, age, and health status as factors and their actual drug dosage as the response. After model training, I'd apply the model to new data to generate predicted dosage values and compare those to the actual dosage. Patients who have an actual dosage higher than the predicted dosage would then be flagged as candidates for dose reduction.
Is this a reasonable plan? Essentially I'd be relying on the residuals to identify the patients who should be taking a reduced dosage. | 2019/02/21 | [
"https://stats.stackexchange.com/questions/393673",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/238529/"
] | I think you can go for one of these approaches:
1. cluster your data based on the specified features and then you will be able to identify
each group/cluster average, maximum, minimum, ....etc drug dosage. then you can judge any
instance by how far it is from it`s cluster mean(far by n-Standard deviations) then
decide that the instances that fall 3-sd(Standard deviations) are anomaly and need to be
adjusted.
2. Use Anomaly detection techniques which will help you detect different/extreme behavior in data. | I think you are right: regression (linear or otherwise) may be the way to go. The only exception would be the case is which dosage is limited to a small amount of fixed values, in which case I would consider classification instead
But remember, you model will only be as good as your data, so make sure you have abundant high quality data for the fitting process.
Also, when flagging candidates for dose reduction, take into account the amount of the difference ("actual"-"expected") and how it compares to the standard deviation among your sample population.
I hope this helped! |
24,470,664 | Okay, I'm obviously an extreme newbie, so be gentle. As I'm learning Javascript, I'm creating a quiz to better help me retain and practice the information. The following is a sample of my code so far(the actual array has been shortened for this question).
I works fine for what it is at this point in my learning progress, except that I can't seem to use Math.floor(Math.random()) to create a non-linear q & a experience.
```
var qAndA = [["What starts a variable?", "var"],
["What creates a popup with text and an OK button?", "alert()"],
["What is the sign for a modulo?", "%"]];
function askQuestion(qAndA) {
var answer = prompt(qAndA[0], " ");
if (answer === qAndA[1]) {
alert("yes");
} else {
alert("No, the answer is " + qAndA[1]);
}
}
for (i = 0; i < qAndA.length; i++) {
askQuestion(qAndA[i]);
}
```
I've looked at all the potential answers here and elsewhere, but nothing addresses this speicific point.
Can anyone out there help me? | 2014/06/28 | [
"https://Stackoverflow.com/questions/24470664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786587/"
] | Easiest way to select a random element in an array:
```
var randomIndex = Math.floor(Math.random() * qAndA.length)
var randomQuestion = qAndA[randomIndex]
```
Now put that in a loop:
```
var questionsToAsk = qAndA.length
for (i = 0; i < questionsToAsk; i++) {
var randomIndex = Math.floor(Math.random() * qAndA.length)
var randomQuestion = qAndA[randomIndex]
askQuestion(randomQuestion);
}
``` | It's faster to use `| 0` as in
```
const randomIndex = Math.random() * qAndA.length | 0;
const randomQuestion = qAndA[randomIndex];
```
The `| 0` is a binary *or* of 0 which the JavaScript spec effectively says the result is converted to an integer before the `|` happens. Note that `| 0` is not the same as `Math.floor`. `| 0` rounds to 0 whereas `Math.floor` rounds down.
```
| 0 Math.floor
------+------+------------
2.5 | 2 | 2
1.5 | 1 | 1
0.5 | 0 | 0
-0.5 | 0 | -1
-1.5 | =1 | -2
-2.5 | -2 | -3
``` |
33,437,891 | I'm doing a clone of a DIV element on button click, I'm able to change the value of ID of the DIV element I'm cloning. But is it possible to change the id of the inner element.
In the below code I'm changing the Id of `#selection` while cloning, I need to dynamically change the id `#select`.
```
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
```
The JS below
```
$(function() {
//on click
$("body").on("click", ".btn-primary", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length++,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
//append clone on the end
$("#selections").append(clone);
});
});
``` | 2015/10/30 | [
"https://Stackoverflow.com/questions/33437891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245234/"
] | Yes.. its totally possible as follows:
```
var clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","select-"+length);
//append clone on the end
$("#selections").append(clone);
``` | You need to change all children's ID manually.
Either change it for only one like that:
```
//clone first element with new id
clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","whateverID");
```
Or change all children using something like that: [jQuery changing the id attribute of all the children](https://stackoverflow.com/questions/12426397/jquery-changing-the-id-attribute-of-all-the-children) |
33,437,891 | I'm doing a clone of a DIV element on button click, I'm able to change the value of ID of the DIV element I'm cloning. But is it possible to change the id of the inner element.
In the below code I'm changing the Id of `#selection` while cloning, I need to dynamically change the id `#select`.
```
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
```
The JS below
```
$(function() {
//on click
$("body").on("click", ".btn-primary", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length++,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
//append clone on the end
$("#selections").append(clone);
});
});
``` | 2015/10/30 | [
"https://Stackoverflow.com/questions/33437891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245234/"
] | Yes.. its totally possible as follows:
```
var clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","select-"+length);
//append clone on the end
$("#selections").append(clone);
``` | Use the class `.show-tick` and the `.children()` method to locate the element:
```
clone.children('.show-tick').attr('id', 'select-' + length);
```
```js
$(function() {
//on click
$(".btn-primary").on("click", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
``` |
33,437,891 | I'm doing a clone of a DIV element on button click, I'm able to change the value of ID of the DIV element I'm cloning. But is it possible to change the id of the inner element.
In the below code I'm changing the Id of `#selection` while cloning, I need to dynamically change the id `#select`.
```
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
```
The JS below
```
$(function() {
//on click
$("body").on("click", ".btn-primary", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length++,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
//append clone on the end
$("#selections").append(clone);
});
});
``` | 2015/10/30 | [
"https://Stackoverflow.com/questions/33437891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245234/"
] | Yes.. its totally possible as follows:
```
var clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","select-"+length);
//append clone on the end
$("#selections").append(clone);
``` | I had a similar need to change the id of the clone and all its children. Posting my solution to help someone in the future. I wanted to change the ids and the names of all the children of the clone.
```
$("#form").on('click', '.clone', function (e) {
e.preventDefault();
var myid = this.id; // id of section we are cloning i.e. section_1
myid = myid.split('_');
var num = 0;
// count existing sections
$('.form_section').each(function(){
num++;
});
num++; // new number for clone
var newid = 'section_'+num;
// make and change id of the clone
var clone = $( "#section_"+myid[1] ).clone().attr("id", newid);
// get clone children
clone.children().find('input,textarea,button,a,select').attr('id', function( i, val ){
var oldid = val;
var newid = val + num;
clone.find("#"+val).attr("id", newid);
clone.find("#"+newid).attr("name", newid);
});
clone.appendTo( ".sections" );
});
``` |
33,437,891 | I'm doing a clone of a DIV element on button click, I'm able to change the value of ID of the DIV element I'm cloning. But is it possible to change the id of the inner element.
In the below code I'm changing the Id of `#selection` while cloning, I need to dynamically change the id `#select`.
```
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
```
The JS below
```
$(function() {
//on click
$("body").on("click", ".btn-primary", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length++,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
//append clone on the end
$("#selections").append(clone);
});
});
``` | 2015/10/30 | [
"https://Stackoverflow.com/questions/33437891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245234/"
] | Use the class `.show-tick` and the `.children()` method to locate the element:
```
clone.children('.show-tick').attr('id', 'select-' + length);
```
```js
$(function() {
//on click
$(".btn-primary").on("click", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
``` | You need to change all children's ID manually.
Either change it for only one like that:
```
//clone first element with new id
clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","whateverID");
```
Or change all children using something like that: [jQuery changing the id attribute of all the children](https://stackoverflow.com/questions/12426397/jquery-changing-the-id-attribute-of-all-the-children) |
33,437,891 | I'm doing a clone of a DIV element on button click, I'm able to change the value of ID of the DIV element I'm cloning. But is it possible to change the id of the inner element.
In the below code I'm changing the Id of `#selection` while cloning, I need to dynamically change the id `#select`.
```
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
Add new selection
</button>
```
The JS below
```
$(function() {
//on click
$("body").on("click", ".btn-primary", function() {
alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length++,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
//append clone on the end
$("#selections").append(clone);
});
});
``` | 2015/10/30 | [
"https://Stackoverflow.com/questions/33437891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245234/"
] | I had a similar need to change the id of the clone and all its children. Posting my solution to help someone in the future. I wanted to change the ids and the names of all the children of the clone.
```
$("#form").on('click', '.clone', function (e) {
e.preventDefault();
var myid = this.id; // id of section we are cloning i.e. section_1
myid = myid.split('_');
var num = 0;
// count existing sections
$('.form_section').each(function(){
num++;
});
num++; // new number for clone
var newid = 'section_'+num;
// make and change id of the clone
var clone = $( "#section_"+myid[1] ).clone().attr("id", newid);
// get clone children
clone.children().find('input,textarea,button,a,select').attr('id', function( i, val ){
var oldid = val;
var newid = val + num;
clone.find("#"+val).attr("id", newid);
clone.find("#"+newid).attr("name", newid);
});
clone.appendTo( ".sections" );
});
``` | You need to change all children's ID manually.
Either change it for only one like that:
```
//clone first element with new id
clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","whateverID");
```
Or change all children using something like that: [jQuery changing the id attribute of all the children](https://stackoverflow.com/questions/12426397/jquery-changing-the-id-attribute-of-all-the-children) |
41,008,229 | I am working on a website where the nav is search form. Basically you can only search for letters. If you search for "A" I want that submit redirects you to a.html, if you search for "B" to redirect you to b.html, and so on. Is this possible? Can I do this with css and javascript? | 2016/12/07 | [
"https://Stackoverflow.com/questions/41008229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7259984/"
] | Okay, if you're looking for an explanation of why the code works the way it does, it goes something like this. Given the following code:
```
len([]) -> 0;
len([_|T]) -> 1 + len(T).
```
If you were to call `len/1` like `len([a,b,c])`, then you can think of it executing like:
* call `len([a,b,c])`
* does `[a,b,c]` match `[]`? no
* does `[a,b,c]` match `[_|T]`? yes, yielding `_ = a` and `T = [b,c]`
* call `len([b,c])`
+ does `[b,c]` match `[]`? no
+ does `[b,c]` match `[_|T]`? yes, yielding `_ = b` and `T = [c]`
+ call `len([c])`
- does `[c]` match `[]`? no
- does `[c]` match `[_|T]`? yes, yielding `_ = c` and `T = []`
- call `len([])`
* does `[]` match `[]`? yes
* `len([])` returns 0
- `len([c])` returns 1 + 0
+ `len([b,c])` returns 1 + 1
* `len([a,b,c])` returns 1 + 2
Does that make sense? | Erlang has a debugger call `im()`
try to use it |
30,841,525 | While running through bamboo(CI), my script is getting failed where all "upload file link" is not starting with the input tag. I am using Auto IT for uploading the file which is working fine locally and when I am trying to run through Bamboo on remote machine it is getting failed there.
So want to upload file from back-end where i don't want to click upload button.
Sendkeys() tried but not helpful in this scenario.
Thnaks in advance | 2015/06/15 | [
"https://Stackoverflow.com/questions/30841525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5010571/"
] | As you are using PrimeFaces 5.2, you can check all the skinning CSS classes in the current [PrimeFaces User Guide](http://www.primefaces.org/docs/guide/primefaces_user_guide_5_2.pdf) and page 411, in particular, which gives you details about `p:selectBooleanCheckbox`
>
> **.ui-chkbox** Main container element.
>
> **.ui-chkbox-box** Container of checkbox icon.
>
> **.ui-chkbox-icon** Checkbox icon.
>
> **.ui-chkbox-label** Checkbox label.
>
>
> | I managed to solve this same problem using these CSS codes:
```
.indivcheckbox .ui-chkbox-icon {
background-position-x: -66px;
background-position-y: -147px;
}
.indivcheckbox .ui-icon-check {
width: 12px;
height: 12px;
}
```
While my component is this:
```
<p:selectBooleanCheckbox styleClass="indivcheckbox" />
```
Basically you just make the box small and then adjust the check icon by tinkering on the background-position-(x/y) to center it in.
Hope it helps. |
62,815,597 | ```
import re
for _ in range(int(input())):
s=input() #input alphanumeric string
print(sum(map(int,re.findall('\d+',s))))
``` | 2020/07/09 | [
"https://Stackoverflow.com/questions/62815597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13898585/"
] | Sure you can do it with map:
```
Promise.all([productVariant1, productVariant2].map((productVariant, i) => {
return fetch("https://cors-anywhere.herokuapp.com/https://api.myurl.com/verify", {
body: `link=${productVariant}&license_key=${licenseKey}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
}).then(data => console.log(`Promise ${i} done`))
})
).then(data => {
console.log("all promises done")
})
``` | You could create a function:
```js
function Fetch(body) {
return fetch("https://cors-anywhere.herokuapp.com/https://api.myurl.com/verify", {
body,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
}).then(doSomething)
}
// And then
Promise.all([
Fetch(`link=${productVariant2}&license_key=${licenseKey}`),
Fetch(`link=${productVariant2}&license_key=${licenseKey}`)
]).then(responses => {
// do something with responses
})
```
Or if the **only** thing you're changing |
15,380,874 | Is it possible to create a contact form that sends the answers by email with *only* HTML5 and JavaScript? And if it is, how do I do it? | 2013/03/13 | [
"https://Stackoverflow.com/questions/15380874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2140042/"
] | Not only you don't need to do this, you simply can't (`String` is `final`). | If your intention is to use `String` in your `Switch` statement then it's better to use
[ENUM TYPE](http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) |
47,649 | During the First age and before, Arda was flat. I'm not certain how flat it was, but wouldn't this imply that one could see great distances, as far as the nearest mountain that was higher than your vantage point? If you were high enough (and had very keen eyes), couldn't you see to the edge of the world?
Were there any references to this, such as watchtowers being able to see much greater distances, or seeing lands that are impossibly far away? | 2014/01/07 | [
"https://scifi.stackexchange.com/questions/47649",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/16157/"
] | How flat was the world? Here's an old map from the [Ambarkanta](http://en.wikipedia.org/wiki/The_Shaping_of_Middle-earth) of the 1930s demonstrating exactly how flat the world was - which was actually quite curved indeed.

Of course, we're talking about a strictly mythical period in Middle-earth's history here, so normal laws of physics shouldn't be considered to apply.
As to whether or not one could see vast distances, the main reference is the (supposed) ability to see Eressea from Numenor, which is mentioned in the Akallabeth:
>
> ...at times, when all the air was clear and the sun was in the east, they would look out and descry far off in the west a city white-shining on a distant shore, and a great harbour and a tower.
>
>
> For in those days the Numenoreans were far-sighted; yet even so it was only the keenest eyes among them that could see this vision, from the Meneltarma, maybe, or from some tall ship that lay off their western coast as far as it was lawful for them to go.
>
>
>
Of course, Tolkien doesn't actually say anything about how far this distance was, so it's difficult to form a final judgement based on this passage.
The words "when all the air was clear" are relevant, however, because the distance one can see is not just dependent on the distance to the horizon, but also on clarity of the air, as Richard mentions in his answer. | From "[AskAMathematician](http://www.askamathematician.com/2012/08/q-if-earth-was-flat-would-there-be-the-horizon-if-so-what-would-it-look-like-if-the-earth-was-flat-and-had-infinite-area-would-that-change-the-answer/)";
>
> For someone around 5’6″ tall, if the Earth were perfectly flat the
> horizon would be about 0.04° higher. That’s about the width of a
> (mechanical) pencil lead held at arm’s length. Unless you have short
> arms, in which case you’ll need to shave down the lead a little.
>
>
>
So, even assuming a completely flat plane your view would basically be unchanged from your current view of the horizon. Imagine looking out at the sea and seeing the horizon a millimetre lower.
Now, If you factor in mountains and hills then the absolute farthest you could see would be the level of the **highest object** in your eyeline. You could, in principle see all the way to [Cori Celesti](http://discworld.wikia.com/wiki/Cori_Celesti) but your view would then be moderated by any clouds, fog, dust or heat-haze that occludes your view.
[Theoretically](http://www.summitpost.org/phpBB3/longest-lines-of-sight-photographed-t44409.html) if you were on the highest object on the entire disk, you could see a very long way (several hundred miles or more) but your depth of vision would be massively small unless you wanted to look at things that are very very large. |
47,649 | During the First age and before, Arda was flat. I'm not certain how flat it was, but wouldn't this imply that one could see great distances, as far as the nearest mountain that was higher than your vantage point? If you were high enough (and had very keen eyes), couldn't you see to the edge of the world?
Were there any references to this, such as watchtowers being able to see much greater distances, or seeing lands that are impossibly far away? | 2014/01/07 | [
"https://scifi.stackexchange.com/questions/47649",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/16157/"
] | From "[AskAMathematician](http://www.askamathematician.com/2012/08/q-if-earth-was-flat-would-there-be-the-horizon-if-so-what-would-it-look-like-if-the-earth-was-flat-and-had-infinite-area-would-that-change-the-answer/)";
>
> For someone around 5’6″ tall, if the Earth were perfectly flat the
> horizon would be about 0.04° higher. That’s about the width of a
> (mechanical) pencil lead held at arm’s length. Unless you have short
> arms, in which case you’ll need to shave down the lead a little.
>
>
>
So, even assuming a completely flat plane your view would basically be unchanged from your current view of the horizon. Imagine looking out at the sea and seeing the horizon a millimetre lower.
Now, If you factor in mountains and hills then the absolute farthest you could see would be the level of the **highest object** in your eyeline. You could, in principle see all the way to [Cori Celesti](http://discworld.wikia.com/wiki/Cori_Celesti) but your view would then be moderated by any clouds, fog, dust or heat-haze that occludes your view.
[Theoretically](http://www.summitpost.org/phpBB3/longest-lines-of-sight-photographed-t44409.html) if you were on the highest object on the entire disk, you could see a very long way (several hundred miles or more) but your depth of vision would be massively small unless you wanted to look at things that are very very large. | Even under extremely clear conditions, it's unusual to see more than a couple of hundred kilometers.
This is due to a variety of very complex effects, but visibility is limited by scattered light in the lower atmosphere due to particles, moisture, etc.
<http://mintaka.sdsu.edu/GF/explain/atmos_refr/horizon.html>
Except in cases of significant contrast, which may allow you to identify that contrast from further away.
So ultimately, what you can see would be largely unchanged. |
47,649 | During the First age and before, Arda was flat. I'm not certain how flat it was, but wouldn't this imply that one could see great distances, as far as the nearest mountain that was higher than your vantage point? If you were high enough (and had very keen eyes), couldn't you see to the edge of the world?
Were there any references to this, such as watchtowers being able to see much greater distances, or seeing lands that are impossibly far away? | 2014/01/07 | [
"https://scifi.stackexchange.com/questions/47649",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/16157/"
] | From "[AskAMathematician](http://www.askamathematician.com/2012/08/q-if-earth-was-flat-would-there-be-the-horizon-if-so-what-would-it-look-like-if-the-earth-was-flat-and-had-infinite-area-would-that-change-the-answer/)";
>
> For someone around 5’6″ tall, if the Earth were perfectly flat the
> horizon would be about 0.04° higher. That’s about the width of a
> (mechanical) pencil lead held at arm’s length. Unless you have short
> arms, in which case you’ll need to shave down the lead a little.
>
>
>
So, even assuming a completely flat plane your view would basically be unchanged from your current view of the horizon. Imagine looking out at the sea and seeing the horizon a millimetre lower.
Now, If you factor in mountains and hills then the absolute farthest you could see would be the level of the **highest object** in your eyeline. You could, in principle see all the way to [Cori Celesti](http://discworld.wikia.com/wiki/Cori_Celesti) but your view would then be moderated by any clouds, fog, dust or heat-haze that occludes your view.
[Theoretically](http://www.summitpost.org/phpBB3/longest-lines-of-sight-photographed-t44409.html) if you were on the highest object on the entire disk, you could see a very long way (several hundred miles or more) but your depth of vision would be massively small unless you wanted to look at things that are very very large. | Near where I live is a mountain peak with an elevation of almost 7,000 ft.
About 100 miles to the west is another peak with an elevation of over 10,000 ft.
On a clear day, from the nearer peak, the taller peak is visible, though it does have a significant blue tint. On a hazy day, the mountain can be completely hidden.
Given greater distance, eventually everything would blend in with the sky, regardless of clarity of the air. |
47,649 | During the First age and before, Arda was flat. I'm not certain how flat it was, but wouldn't this imply that one could see great distances, as far as the nearest mountain that was higher than your vantage point? If you were high enough (and had very keen eyes), couldn't you see to the edge of the world?
Were there any references to this, such as watchtowers being able to see much greater distances, or seeing lands that are impossibly far away? | 2014/01/07 | [
"https://scifi.stackexchange.com/questions/47649",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/16157/"
] | How flat was the world? Here's an old map from the [Ambarkanta](http://en.wikipedia.org/wiki/The_Shaping_of_Middle-earth) of the 1930s demonstrating exactly how flat the world was - which was actually quite curved indeed.

Of course, we're talking about a strictly mythical period in Middle-earth's history here, so normal laws of physics shouldn't be considered to apply.
As to whether or not one could see vast distances, the main reference is the (supposed) ability to see Eressea from Numenor, which is mentioned in the Akallabeth:
>
> ...at times, when all the air was clear and the sun was in the east, they would look out and descry far off in the west a city white-shining on a distant shore, and a great harbour and a tower.
>
>
> For in those days the Numenoreans were far-sighted; yet even so it was only the keenest eyes among them that could see this vision, from the Meneltarma, maybe, or from some tall ship that lay off their western coast as far as it was lawful for them to go.
>
>
>
Of course, Tolkien doesn't actually say anything about how far this distance was, so it's difficult to form a final judgement based on this passage.
The words "when all the air was clear" are relevant, however, because the distance one can see is not just dependent on the distance to the horizon, but also on clarity of the air, as Richard mentions in his answer. | Even under extremely clear conditions, it's unusual to see more than a couple of hundred kilometers.
This is due to a variety of very complex effects, but visibility is limited by scattered light in the lower atmosphere due to particles, moisture, etc.
<http://mintaka.sdsu.edu/GF/explain/atmos_refr/horizon.html>
Except in cases of significant contrast, which may allow you to identify that contrast from further away.
So ultimately, what you can see would be largely unchanged. |
47,649 | During the First age and before, Arda was flat. I'm not certain how flat it was, but wouldn't this imply that one could see great distances, as far as the nearest mountain that was higher than your vantage point? If you were high enough (and had very keen eyes), couldn't you see to the edge of the world?
Were there any references to this, such as watchtowers being able to see much greater distances, or seeing lands that are impossibly far away? | 2014/01/07 | [
"https://scifi.stackexchange.com/questions/47649",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/16157/"
] | How flat was the world? Here's an old map from the [Ambarkanta](http://en.wikipedia.org/wiki/The_Shaping_of_Middle-earth) of the 1930s demonstrating exactly how flat the world was - which was actually quite curved indeed.

Of course, we're talking about a strictly mythical period in Middle-earth's history here, so normal laws of physics shouldn't be considered to apply.
As to whether or not one could see vast distances, the main reference is the (supposed) ability to see Eressea from Numenor, which is mentioned in the Akallabeth:
>
> ...at times, when all the air was clear and the sun was in the east, they would look out and descry far off in the west a city white-shining on a distant shore, and a great harbour and a tower.
>
>
> For in those days the Numenoreans were far-sighted; yet even so it was only the keenest eyes among them that could see this vision, from the Meneltarma, maybe, or from some tall ship that lay off their western coast as far as it was lawful for them to go.
>
>
>
Of course, Tolkien doesn't actually say anything about how far this distance was, so it's difficult to form a final judgement based on this passage.
The words "when all the air was clear" are relevant, however, because the distance one can see is not just dependent on the distance to the horizon, but also on clarity of the air, as Richard mentions in his answer. | Near where I live is a mountain peak with an elevation of almost 7,000 ft.
About 100 miles to the west is another peak with an elevation of over 10,000 ft.
On a clear day, from the nearer peak, the taller peak is visible, though it does have a significant blue tint. On a hazy day, the mountain can be completely hidden.
Given greater distance, eventually everything would blend in with the sky, regardless of clarity of the air. |
41,543,974 | ```html
<div class="block-update-card status" ng-show="isShow">
<div class="update-card-body">
<div class="update-card-body">
<p><textarea name="feedback" spellcheck="false" placeholder="Discription" ></textarea></p>
</div>
</div>
<div class="card-action-pellet btn-toolbar pull-right" role="toolbar">
<div class="btn-group fa fa-mail-reply"></div>
<div class="btn-group fa fa-bell"></div>
<div class="btn-group fa fa-trash"></div>
<div class="btn-group fa fa-photo"></div>
</div>
</div>
```
am working on sticky project i want to know how the sticky save without save button | 2017/01/09 | [
"https://Stackoverflow.com/questions/41543974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7393472/"
] | Use `getattr` for accessing members of the module:
```
func = getattr(globals()['file_that_have_abc'], 'abc')
func()
```
of course, you can drop the `globals` here if you don't *need* to look up the module too. | You just need to use the `globals()` call to access the variables in your current module. For other modules, just use the name you imported the module with - and to retrieve functions/classes/variables from there from their names as strings, use the `getattr` function.
For example:
```
import math
func = `sin`
getattr(math, func)(0)
``` |
49,625,859 | The docker daemon isn't starting anymore on my computer (Linux / Centos 7), and I strongly suspect that a container that is set to auto-restart is to blame in this case. If I start the daemon manually, the last line I see is "Loading containers: start", and then it just hangs.
What I'd like to do is to start the daemon without starting *any* containers. But I can't find any option to do that. Is there any option in docker to start the daemon without also starting containers set to automatically restart? If not, is there a way to remove the containers manually that doesn't require the docker daemon running? | 2018/04/03 | [
"https://Stackoverflow.com/questions/49625859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/347857/"
] | You have the order of the text and the style tag in the wrong way around.
>
>
> ```
> h('label', "Hello: ", {style: { fontWeight: "1500"}}),
>
> ```
>
>
Should be:
```
h('label', {style: { fontWeight: "1500"}}, "Hello: "),
```
Also, 1500 is an invalid value for `font-weight`, this is inside the initial revision of your question, it should be 900 at most, example:
```js
new Vue({
render: function(h) {
return h('div', { style: {} }, [
h('label', {style: { fontWeight: "900" }}, "Hello: "),
h('label', "world")
])
},
}).$mount("#app")
```
```html
<script type="text/javascript" src="https://unpkg.com/vue@2.1.3/dist/vue.runtime.js"></script>
<div id="app"></div>
``` | You should put the params in the correct order:
```
h('label', {style: { fontWeight: "500"}}, "Hello: "),
```
Or you can pass the innerHTML like bellow:
```
h('div', { style: {} }, [
h('label', { domProps: { innerHTML:"Hello: " }, style: { fontWeight: "500"}}),
h('label', "world")
])
```
for [detail](https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth). |
215,164 | I have the following in a child theme's functions.php file:
```
<?php
function theme_child_add_scripts() {
wp_register_script(
'script',
get_stylesheet_directory_uri() . '/js/script.js',
array( 'jquery' ),
null,
false
);
wp_enqueue_script( 'script' )
}
add_action('wp_enqueue_scripts', 'theme_child_add_scripts');
```
script.js isn't included on the page and there's no network request going out to get it. What could be going wrong? It's unclear whether the child theme's functions.php file is even being executed.
edit: It seems that the functions.php file is not being executed *at all*, because I put a die('foo') at the top of the file and the page loaded normally. Why would this be happening?
In styles.css:
```
/*
Theme Name: Theme-child
Template: Theme
*/
``` | 2016/01/20 | [
"https://wordpress.stackexchange.com/questions/215164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87192/"
] | Our problem was that our style.css file was in a css folder inside the child theme directory, not at the root of the child theme. When we placed a style.css file at the root and included the comment block with theme name and template it picked up the functions.php file as expected. | I had a problem with a code that executed perfectly in the theme functions.php but not in the child theme's (that's how I found this page). I found a non-tech solution, using the free plug in Code Snippets the code executed perfectly. I was looking for a php solution, but this has saved me a bit of time. |
15,713 | I recently came across an article printed in our school magazine, which read, "I studied that a year ago". But, doesn't "I studied that a year back" sound better?
What's your say? | 2011/03/09 | [
"https://english.stackexchange.com/questions/15713",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4924/"
] | I would think that "a year ago" is the phrase normally used.
Looking at the data reported by the *Corpus of Contemporary American*, I can create the [following chart](https://i.stack.imgur.com/VTbyC.png).

"Year ago" and "years ago" are the most used phrases, at least in American English.
Looking at what reported by the *British National Corpus*, I obtain the following [data](https://i.stack.imgur.com/P8yQG.png).

"Year ago" and "years ago" are still the most used phrases, compared to "year back" and "years back".
Differently from what reported from the *Corpus of Contemporary American*, "year back" and "years back" are not used in academic contexts. | **A year ago** would be the regular way to say it; **a year back** is a colloquial way of saying the same. |
15,713 | I recently came across an article printed in our school magazine, which read, "I studied that a year ago". But, doesn't "I studied that a year back" sound better?
What's your say? | 2011/03/09 | [
"https://english.stackexchange.com/questions/15713",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4924/"
] | **A year ago** would be the regular way to say it; **a year back** is a colloquial way of saying the same. | "I studied that a year ago" sounds better. |
15,713 | I recently came across an article printed in our school magazine, which read, "I studied that a year ago". But, doesn't "I studied that a year back" sound better?
What's your say? | 2011/03/09 | [
"https://english.stackexchange.com/questions/15713",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4924/"
] | **A year ago** would be the regular way to say it; **a year back** is a colloquial way of saying the same. | It would be proper to say *ago* when it is time specific, otherwise, *back*.
* “A few years back” is a more correct form than “a few years ago”.
* “A hundred years ago” is a more correct form than “a hundred years back”. |
15,713 | I recently came across an article printed in our school magazine, which read, "I studied that a year ago". But, doesn't "I studied that a year back" sound better?
What's your say? | 2011/03/09 | [
"https://english.stackexchange.com/questions/15713",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4924/"
] | I would think that "a year ago" is the phrase normally used.
Looking at the data reported by the *Corpus of Contemporary American*, I can create the [following chart](https://i.stack.imgur.com/VTbyC.png).

"Year ago" and "years ago" are the most used phrases, at least in American English.
Looking at what reported by the *British National Corpus*, I obtain the following [data](https://i.stack.imgur.com/P8yQG.png).

"Year ago" and "years ago" are still the most used phrases, compared to "year back" and "years back".
Differently from what reported from the *Corpus of Contemporary American*, "year back" and "years back" are not used in academic contexts. | "I studied that a year ago" sounds better. |
15,713 | I recently came across an article printed in our school magazine, which read, "I studied that a year ago". But, doesn't "I studied that a year back" sound better?
What's your say? | 2011/03/09 | [
"https://english.stackexchange.com/questions/15713",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4924/"
] | I would think that "a year ago" is the phrase normally used.
Looking at the data reported by the *Corpus of Contemporary American*, I can create the [following chart](https://i.stack.imgur.com/VTbyC.png).

"Year ago" and "years ago" are the most used phrases, at least in American English.
Looking at what reported by the *British National Corpus*, I obtain the following [data](https://i.stack.imgur.com/P8yQG.png).

"Year ago" and "years ago" are still the most used phrases, compared to "year back" and "years back".
Differently from what reported from the *Corpus of Contemporary American*, "year back" and "years back" are not used in academic contexts. | It would be proper to say *ago* when it is time specific, otherwise, *back*.
* “A few years back” is a more correct form than “a few years ago”.
* “A hundred years ago” is a more correct form than “a hundred years back”. |
15,713 | I recently came across an article printed in our school magazine, which read, "I studied that a year ago". But, doesn't "I studied that a year back" sound better?
What's your say? | 2011/03/09 | [
"https://english.stackexchange.com/questions/15713",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4924/"
] | "I studied that a year ago" sounds better. | It would be proper to say *ago* when it is time specific, otherwise, *back*.
* “A few years back” is a more correct form than “a few years ago”.
* “A hundred years ago” is a more correct form than “a hundred years back”. |
126,883 | I need to get the order information (shipping details, item SKU's) in order to send it over to the Amazon API for easy FBA shipping. Ideally I will be able to capture this information upon a successful payment. How do you get this information? | 2016/07/21 | [
"https://magento.stackexchange.com/questions/126883",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/42464/"
] | You can use below code to get details in success.phtml file. It will work for magentoce2.1 also.
```
<?php
$lid = $this->getOrderId();
echo "Order ID:".$lid."<br/>";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('Magento\Sales\Model\Order')->load($lid);
$totall = $order->getGrandTotal();
echo "Order Total:".$totall."<br/>";
$shippingAddress = $order->getShippingAddress();
echo "Telephone No:".$shippingAddress->getTelephone()."<br/>";
echo "postcode".$shippingAddress->getPostcode()."<br/>";
$items = $order->getAllItems();
foreach($items as $i):
$_product =
$objectManager->create('Magento\Catalog\Model\Product')->load($i->getProductId())->getSku();
echo "product sku:".$_product."<br/>";
endforeach;
?>
```
**Kindly note that I do not recommend using object manager like this directly. I insist please create your block and pass detail from there and you can retrieve in this file.** | ```
//Use this Class to get order id
protected $_checkoutSession;
\Magento\Checkout\Model\Session $checkoutSession,
$this->_checkoutSession = $checkoutSession;
// Use this method to get ID
public function getRealOrderId()
{
$lastorderId = $this->_checkoutSession->getLastOrderId();
return $lastorderId;
}
// Use this in your phtml
<?php
$lid = $block->getRealOrderId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('Magento\Sales\Model\Order')->load($lid);
$totall = $order->getGrandTotal();
echo "Order Total:".$totall."<br/>";
$shippingAddress = $order->getShippingAddress();
echo "Telephone No:".$shippingAddress->getTelephone()."<br/>";
echo "postcode".$shippingAddress->getPostcode()."<br/>";
$items = $order->getAllItems();
foreach($items as $i):
$_product =
$objectManager->create('Magento\Catalog\Model\Product')->load($i->getProductId())->getSku();
echo "product sku:".$_product."<br/>";
endforeach;?>
``` |
46,674,355 | I am trying to connect 2 or more Raspberry Pi 3 boards over bluetooth. I am looking for options to set security while pairing. I am using Raspian-stretch(Latest one available). Bluez version available on RPI-3 is 5.23(as shown from bluetoothd -v command).
I am using headless version. I want the pairing to be secured(meaing there should be some kind of authentication i can set like PIN(4 digits) or Passkey(6 digits)) without the user logged into it. So if i have to connect my phone to the RPI, i dont have to login to RPI inorder to enter the PIN/Passkey.
Then i would like to set up bluetooth PAN network so that i can communicate to between devices connected to PAN network.
I want pair the device/s using a PIN which is available in a file in the system or somewhere i can point it to. Say for example, pin.txt file in /temp/ directory or by running an agent to set the PIN. I read from other posts that bluez5.x got rid of the bluetooth-agent which was used in earlier version of bluez to do the things i could acomplish.
Agents in bluetoothctl such as DisplayOnly, KeyboardDisplay,NoInputNoOutput, DisplayYesNo,KeyboardOnly,on either sets a dynamic passkey which has to be entered manually or confirmation the passkey or just lets any device to pair and connect without any authntication in case of NoInputNoOutput.
Here is the link which i found of this forum stating that the agent is no longer available:
<https://www.raspberrypi.org/forums/viewtopic.php?t=133961>
I also refers to some examples that shows pairing of devices but doesnt address what i am looking for.
There is no info available on manpage too.
<https://manpages.debian.org/stretch/bluez/bluetoothctl.1.en.html>
Here is something i found about the commands but still not what i am looking for.
<https://wiki.archlinux.org/index.php/Bluetooth>
I have also posted this Raspberry Pi forum. Here is the link:
<https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=195090>
Any help or suggestion to get around this or links to documnets i could refer to is appreciated.
Thanks in advance. | 2017/10/10 | [
"https://Stackoverflow.com/questions/46674355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940662/"
] | I was able to get this working with the test scripts.
For anyone who is interested to know the details, please refer to my post on Raspberry Pi forum. Below is the link.
<https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=195090&p=1221455#p1221455> | First you have to configurate sspmode 0, for pin request: hciconfig hci0 sspmode 0
And using bt-agent aplicattion (you can run as deamon too):
bt-agent -c NoInputNoOutput -p /root/bluethooth.cfg
Edit the file configuration, you can put tha mac address and the pin: For example: XX:XX:XX:XX:XX:XX 1234
Or if you want a pin to all the device the same pin code, for example 1234, edit the file like this: \* 1234
This work for me! |
46,674,355 | I am trying to connect 2 or more Raspberry Pi 3 boards over bluetooth. I am looking for options to set security while pairing. I am using Raspian-stretch(Latest one available). Bluez version available on RPI-3 is 5.23(as shown from bluetoothd -v command).
I am using headless version. I want the pairing to be secured(meaing there should be some kind of authentication i can set like PIN(4 digits) or Passkey(6 digits)) without the user logged into it. So if i have to connect my phone to the RPI, i dont have to login to RPI inorder to enter the PIN/Passkey.
Then i would like to set up bluetooth PAN network so that i can communicate to between devices connected to PAN network.
I want pair the device/s using a PIN which is available in a file in the system or somewhere i can point it to. Say for example, pin.txt file in /temp/ directory or by running an agent to set the PIN. I read from other posts that bluez5.x got rid of the bluetooth-agent which was used in earlier version of bluez to do the things i could acomplish.
Agents in bluetoothctl such as DisplayOnly, KeyboardDisplay,NoInputNoOutput, DisplayYesNo,KeyboardOnly,on either sets a dynamic passkey which has to be entered manually or confirmation the passkey or just lets any device to pair and connect without any authntication in case of NoInputNoOutput.
Here is the link which i found of this forum stating that the agent is no longer available:
<https://www.raspberrypi.org/forums/viewtopic.php?t=133961>
I also refers to some examples that shows pairing of devices but doesnt address what i am looking for.
There is no info available on manpage too.
<https://manpages.debian.org/stretch/bluez/bluetoothctl.1.en.html>
Here is something i found about the commands but still not what i am looking for.
<https://wiki.archlinux.org/index.php/Bluetooth>
I have also posted this Raspberry Pi forum. Here is the link:
<https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=195090>
Any help or suggestion to get around this or links to documnets i could refer to is appreciated.
Thanks in advance. | 2017/10/10 | [
"https://Stackoverflow.com/questions/46674355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940662/"
] | After few days fiddling with BlueZ 5 this is what I've got.
Using BlueZ **5.50** & Raspbian Stretch (Pi Zero W):
Start bluetoothd with **--compat**:
>
> append to **ExecStart** line in **/etc/systemd/system/dbus-org.bluez.service**
>
>
>
or
>
> in rc.local: sudo bluetoothd --compat &
>
>
>
---
The next steps are handled by code posted below but to clarify, hciconfig needs to be set to:
>
> sudo hciconfig hci0 sspmode **0**
>
>
>
**Note #1:** With 'sspmode **1**' when pairing from Android you will get a prompt for PIN but afterwards Pi autogenerates 6-digit passkey and pairing failes.
**Note #2:** **hciconfig hci0** can't be set with **auth** or **encrypt** those will actually register **agent DisplayOnly** (we will be creating agent in next step) as **KeyboardDisplay** (sudo btmon to verify) and pairing won't use predefined PIN. Not sure if there is a reason why DisplayOnly can't use auth, encrypt (might have something to do with them setting security mode 3).
Afterwards we will use **bluetoothctl**:
```
pi@raspberrypi:~ $ bluetoothctl
Agent registered
[bluetooth]# agent off
Agent unregistered
[bluetooth]# agent DisplayOnly
Agent registered
[bluetooth]# default-agent
Default agent request successful
[bluetooth]# discoverable on
Changing discoverable on succeeded
[CHG] Controller 11:22:33:44:55:66 Discoverable: yes
[bluetooth]# pairable on
Changing pairable on succeeded
[CHG] Controller 11:22:33:44:55:66 Pairable: yes
// Initiate pairing on remote device //
[NEW] Device AA:BB:CC:DD:EE:FF Android_phone
// Enter any PIN on Device AA:BB:CC:DD:EE:FF
Request PIN code
// retype your PIN below (on Pi)
[agent] Enter PIN code: <your PIN>
[CHG] Device AA:BB:CC:DD:EE:FF Class: 0x005a020c
...
[CHG] Device AA:BB:CC:DD:EE:FF Paired: yes
[bluetooth]# quit
```
**Note #3:** Registering agent using pexpect (just a note if you try to run the code posted below) with BlueZ 5.43 (default version in Stretch) is hit and miss
---
Below is a Python 2.7 code that sets sspmode and handles pairing with pregenerated PIN:
```html
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function # import print from python3: end=""
import time
import re
import pexpect # sudo apt-get install python-pexpect
import subprocess
import random
# !!! make sure bluetoothd runs in --compat mode before executing this script !!!
def pair_with_pin(start_time, pin, time_limit=60): # int(time.time()), pin - \d{4}, time_limit - approximate pairing window time in seconds, it might take up to 2x (nested timeout conditions)
"exectutes pairing with entered PIN on bluetooth adapter side"
pairing_status = False
try:
subprocess.call(['sudo','hciconfig','hci0','sspmode', '0'])
# bluetoothctl
child = pexpect.spawn('bluetoothctl')
child.expect("#")
child.sendline('agent off') # might be unnecessary
child.expect("unregistered")
child.sendline('agent DisplayOnly')
child.expect("Agent registered")
child.sendline('pairable on')
child.expect("pairable on succeeded")
child.sendline('discoverable on')
child.expect("discoverable on succeeded")
child.sendline('default-agent')
print ('Please input PIN: ' + pin)
# waiting for Phone to send a pairing request...
child.expect('Enter PIN code:', timeout = time_limit ) # timeout <= PAIRING_TIME_LIMIT to keep some kind of logic
while int(time.time()) < start_time + time_limit: # allow multiple pairing attempts during pairing window
child.sendline(pin)
i = child.expect(['Paired: yes', 'Enter PIN code:'], timeout = time_limit)
if i == 0: # found 'Paired: yes' == successful pairing
trust_mac = 'trust ' + re.search(r'(?:[0-9a-fA-F]:?){12}.+$', child.before).group(0) # extract MAC from last line, one with 'Paired: Yes'
child.sendline(trust_mac) # optionally add device to trusted
child.expect('trust succeeded', timeout = 10)
pairing_status = True
break
#else: # i == 1
# print('wrong PIN, retrying if time will allow')
except pexpect.EOF:
print ('!!!!!!!! EOF')
except pexpect.TIMEOUT:
print ('!!!!!!!! TIMEOUT')
# hide Pi's bluetooth for security reasons
child.sendline('pairable off')
child.expect("pairable off succeeded")
child.sendline('discoverable off')
child.expect("discoverable off succeeded")
child.close()
return pairing_status
#main program body
PAIRING_TIME_LIMIT = 60
BT_PIN = random.randint(1000,10000) # generate random 4-digit PIN 1000..9999
status = pair_with_pin(int(time.time()), str(BT_PIN), PAIRING_TIME_LIMIT)
if status == True:
print('Pairing successful')
```
**Final note:** After successful pairing it **might** be posibble to turn encryption on, try:
>
> hciconfig hci0 encrypt
>
>
>
or
>
> hcitool enc $BDADD
>
>
> | First you have to configurate sspmode 0, for pin request: hciconfig hci0 sspmode 0
And using bt-agent aplicattion (you can run as deamon too):
bt-agent -c NoInputNoOutput -p /root/bluethooth.cfg
Edit the file configuration, you can put tha mac address and the pin: For example: XX:XX:XX:XX:XX:XX 1234
Or if you want a pin to all the device the same pin code, for example 1234, edit the file like this: \* 1234
This work for me! |
273,587 | I'm trying to send data by STM32f103 to an Arduino board using UART. Data isn't received properly. The code is generated using STM32CUBEMX and here is the part I added:
STM32 code (Transmit):
```
uint8_t Test[] = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 \n"; //Data to send
HAL_UART_Transmit(&huart1,Test,sizeof(Test),10);// Sending in normal mode
HAL_Delay(1000);
HAL_UART_Transmit_DMA(&huart1,Test,sizeof(Test));// Sending in DMA mode
HAL_Delay(1000);
/* USART1 init function */
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
}
```
the received data is:
```
{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1}
enter code here
```
in both DMA and normal modes the received data is pretty similar. The UART baud rate is 115200.
Why is my data being truncated? Is it an array bounds problem? Or am I hitting the limit of my buffer?
Edit:
Arduino Code (Receive):
```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 9); // RX, TX ports
void setup() {
// set the data baud rate
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect.
}
mySerial.begin(115200);
}
void loop() {
if (mySerial.available()) {
Serial.write(mySerial.read());
}
}
```
Data transmission works good between two Arduino boards. | 2016/12/07 | [
"https://electronics.stackexchange.com/questions/273587",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/109413/"
] | You receive ~67 characters, which at 10 bits/character, is 670 bits.
Given that your timeout (parameter 4) is set to 10ms or 0.01 s, the average bit rate seems to be around 67000 bit/s. My guess is that you are transmitting at 115200 baud with some inter-character delay giving an effective bit rate of 67000 bit/s.
Therefore, after 67 characters, 10ms expires and the transmit routine returns.
To fix, increase the value of parameter 4 - the timeout value, to at least 20.
Also check that your CPU clock frequency is correctly defined in your project setup code and measure it to ensure it's within 2.5% of the intended value. | The higher a baud rate goes, the faster data is sent/received, but there are limits to how fast data can be transferred. You usually won’t see speeds exceeding 115200 - that’s fast for most microcontrollers. Get too high, and you’ll begin to see errors on the receiving end, as clocks and sampling periods just can’t keep up.
Test lower baud rate. |
273,587 | I'm trying to send data by STM32f103 to an Arduino board using UART. Data isn't received properly. The code is generated using STM32CUBEMX and here is the part I added:
STM32 code (Transmit):
```
uint8_t Test[] = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 \n"; //Data to send
HAL_UART_Transmit(&huart1,Test,sizeof(Test),10);// Sending in normal mode
HAL_Delay(1000);
HAL_UART_Transmit_DMA(&huart1,Test,sizeof(Test));// Sending in DMA mode
HAL_Delay(1000);
/* USART1 init function */
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
}
```
the received data is:
```
{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1}
enter code here
```
in both DMA and normal modes the received data is pretty similar. The UART baud rate is 115200.
Why is my data being truncated? Is it an array bounds problem? Or am I hitting the limit of my buffer?
Edit:
Arduino Code (Receive):
```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 9); // RX, TX ports
void setup() {
// set the data baud rate
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect.
}
mySerial.begin(115200);
}
void loop() {
if (mySerial.available()) {
Serial.write(mySerial.read());
}
}
```
Data transmission works good between two Arduino boards. | 2016/12/07 | [
"https://electronics.stackexchange.com/questions/273587",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/109413/"
] | You receive ~67 characters, which at 10 bits/character, is 670 bits.
Given that your timeout (parameter 4) is set to 10ms or 0.01 s, the average bit rate seems to be around 67000 bit/s. My guess is that you are transmitting at 115200 baud with some inter-character delay giving an effective bit rate of 67000 bit/s.
Therefore, after 67 characters, 10ms expires and the transmit routine returns.
To fix, increase the value of parameter 4 - the timeout value, to at least 20.
Also check that your CPU clock frequency is correctly defined in your project setup code and measure it to ensure it's within 2.5% of the intended value. | Arduino's SoftwareSerial library cannot operate with high UART rates. Never use it with speeds higher than 38400 on Uno/Nano boards for example. If you still want 115200 try HardwareSerial instead. |
5,312,306 | I want to insert a result in mysql, i use this query:
```
$sql= "INSERT into {test} WHERE Id = $currentID (soortstage)VALUES('%s')";
```
that is the error:
```
* user warning:
You have an error in your SQL syntax;
check the manual that corresponds to
your MySQL server version for the
right syntax to use near `WHERE Id =
(Soortstage)VALUES('132')'` at line 1
query: `INSERT into test WHERE Id =
(Soortstage)VALUES('132') in
C:\xampp\htdocs\testplanning\modules\planning\planning.module on line 425.`
* warning:
Invalid argument supplied for
foreach() in
`C:\xampp\htdocs\testplanning\includes\form.inc
on line 1213.`
```
Have someone a idea? Thanks! | 2011/03/15 | [
"https://Stackoverflow.com/questions/5312306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642760/"
] | You might be looking for [REPLACE](http://dev.mysql.com/doc/refman/5.1/en/replace.html), which will either UPDATE or INSERT based on whether or not the primary ID of the record exists.
`REPLACE INTO {test} WHERE Id = $currentID (soortstage) VALUES('%s')`
But, frankly, you mention Drupal, which has a nice helper for this: <http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_write_record/6> | You need an update query
```
$sql= "UPDATE {test} SET soortstage = '%s' WHERE Id = $currentID ";
``` |
33,133,645 | I'm trying to secure my webapp by using nginx base authentication.
What I'm looking for is a way to force the browser to show my custom html login page instead of the default login popup but still handle the authorization process.
I try to omit the 'WWW-Authenticate' header and the popup wasn't display but I've no idea how to force the browser to add the 'Authorization' header for each request.
hereby nginx.conf:
```
location /{
auth_basic "Restricted";
auth_basic_user_file htpasswd;
proxy_pass http://tomcat:8080/;
error_page 401 /login.html;
}
location = /login.html {
root html;
more_clear_headers 'WWW-Authenticate';
}
``` | 2015/10/14 | [
"https://Stackoverflow.com/questions/33133645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446392/"
] | \*has\* to be a better way to accomplish this, but i managed to do it with X-Accel-Redirect and php, here's how:
i wanted to have a custom login page for folder /foo/ (and recursively all its content)
... first i renamed the on-disk folder `/var/www/html/foo` to `/var/www/html/internal_foo` , then i added to nginx config:
```
location ~ /internal_foo {
internal;
# even if this is the default root, the internal-directive seems to prevent inheriting the root directive, so have to explicitly specify it here...
root /var/www/html;
}
location ~ /foo {
try_files "" /foo.php$is_args$args;
}
```
then i created a `/var/www/html/foo.php` with the contents:
```
<?php
// warning: script vulnerable to timing attack which can disclose existence of files. (realpath() is not constant-time)
if(is_authorised()){
$translated="/internal_foo/".urldecode(substr($_SERVER['REQUEST_URI'],strlen("/foo/")));
$file=__DIR__.$translated;
$file=realpath($file);
if(false===$file){http_response_code(404);exit();}
if(0!==strpos($file,__DIR__.DIRECTORY_SEPARATOR."internal_foo")){
// probably a hacker attempting ../../../etc/passwd schenanigans.
http_response_code(400);
exit();
}
header("X-accel-redirect: ".$translated);
}else{
show_loginpage();
}
```
and voila, if a user is authorized, the request is sent to nginx, otherwise `show_loginpage();` is executed (where you can put your custom login page), mission accomplished :) | If you really want to do this. The easiest way is to put the username and password into the url. Basic Authentication supports this. Change all requests to the format below and it will work:
```
"http://" + username + ":" + password + "@example.com"
``` |
33,133,645 | I'm trying to secure my webapp by using nginx base authentication.
What I'm looking for is a way to force the browser to show my custom html login page instead of the default login popup but still handle the authorization process.
I try to omit the 'WWW-Authenticate' header and the popup wasn't display but I've no idea how to force the browser to add the 'Authorization' header for each request.
hereby nginx.conf:
```
location /{
auth_basic "Restricted";
auth_basic_user_file htpasswd;
proxy_pass http://tomcat:8080/;
error_page 401 /login.html;
}
location = /login.html {
root html;
more_clear_headers 'WWW-Authenticate';
}
``` | 2015/10/14 | [
"https://Stackoverflow.com/questions/33133645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446392/"
] | You need to add `proxy_intercept_errors on;` or you will not be able to define `error_page`. Otherwise NGINX just passes the HTTP 401 response back to the client.
```
location /{
auth_basic "Restricted";
auth_basic_user_file htpasswd;
proxy_pass http://tomcat:8080/;
proxy_intercept_errors on;
error_page 401 /login.html;
}
location = /login.html {
root html;
more_clear_headers 'WWW-Authenticate';
}
```
>
> Syntax: proxy\_intercept\_errors on | off;
>
> Default: proxy\_intercept\_errors off;
>
> Context: http, server, location
>
> Determines whether proxied responses with codes greater than or equal to 300 should be passed to a client or be intercepted and redirected to nginx for processing with the error\_page directive.
>
>
> | If you really want to do this. The easiest way is to put the username and password into the url. Basic Authentication supports this. Change all requests to the format below and it will work:
```
"http://" + username + ":" + password + "@example.com"
``` |
33,133,645 | I'm trying to secure my webapp by using nginx base authentication.
What I'm looking for is a way to force the browser to show my custom html login page instead of the default login popup but still handle the authorization process.
I try to omit the 'WWW-Authenticate' header and the popup wasn't display but I've no idea how to force the browser to add the 'Authorization' header for each request.
hereby nginx.conf:
```
location /{
auth_basic "Restricted";
auth_basic_user_file htpasswd;
proxy_pass http://tomcat:8080/;
error_page 401 /login.html;
}
location = /login.html {
root html;
more_clear_headers 'WWW-Authenticate';
}
``` | 2015/10/14 | [
"https://Stackoverflow.com/questions/33133645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446392/"
] | You need to add `proxy_intercept_errors on;` or you will not be able to define `error_page`. Otherwise NGINX just passes the HTTP 401 response back to the client.
```
location /{
auth_basic "Restricted";
auth_basic_user_file htpasswd;
proxy_pass http://tomcat:8080/;
proxy_intercept_errors on;
error_page 401 /login.html;
}
location = /login.html {
root html;
more_clear_headers 'WWW-Authenticate';
}
```
>
> Syntax: proxy\_intercept\_errors on | off;
>
> Default: proxy\_intercept\_errors off;
>
> Context: http, server, location
>
> Determines whether proxied responses with codes greater than or equal to 300 should be passed to a client or be intercepted and redirected to nginx for processing with the error\_page directive.
>
>
> | \*has\* to be a better way to accomplish this, but i managed to do it with X-Accel-Redirect and php, here's how:
i wanted to have a custom login page for folder /foo/ (and recursively all its content)
... first i renamed the on-disk folder `/var/www/html/foo` to `/var/www/html/internal_foo` , then i added to nginx config:
```
location ~ /internal_foo {
internal;
# even if this is the default root, the internal-directive seems to prevent inheriting the root directive, so have to explicitly specify it here...
root /var/www/html;
}
location ~ /foo {
try_files "" /foo.php$is_args$args;
}
```
then i created a `/var/www/html/foo.php` with the contents:
```
<?php
// warning: script vulnerable to timing attack which can disclose existence of files. (realpath() is not constant-time)
if(is_authorised()){
$translated="/internal_foo/".urldecode(substr($_SERVER['REQUEST_URI'],strlen("/foo/")));
$file=__DIR__.$translated;
$file=realpath($file);
if(false===$file){http_response_code(404);exit();}
if(0!==strpos($file,__DIR__.DIRECTORY_SEPARATOR."internal_foo")){
// probably a hacker attempting ../../../etc/passwd schenanigans.
http_response_code(400);
exit();
}
header("X-accel-redirect: ".$translated);
}else{
show_loginpage();
}
```
and voila, if a user is authorized, the request is sent to nginx, otherwise `show_loginpage();` is executed (where you can put your custom login page), mission accomplished :) |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Large commercial jets operate within a much wider range of weights than most GA aircraft do, and since Vy varies with weight, it wouldn't make sense to publish "a" single Vy speed for them. The crew can get a best rate or best angle of climb speed from the FMC (which "knows" the current weight of the aircraft, based on current fuel & an entered Zero Fuel Weight).
From an empty aircraft with minimum fuel to a loaded aircraft with max fuel, the weight probably won't quite double for most commercial jet aircraft, but the one might be 170% or more of the other. With that much range, any single Vy you publish would be way far off in a lot of cases. On a GA aircraft, without an FMC and operating in a much narrower weight range, publishing a single speed makes much more sense as the delta between published and actual becomes smaller and the consequence of being a couple knots off is probably slight. | Actually modern jets in general do have massive excess thrust. One big reason is due to safety requirements to handle engine loss. Vy is a big issue while on a single engine or piston props. With two turbofans/turboprops running and at low altitudes, they "climb like a rocket" compared with single piston and even twin pistons with big engines.
Additional reasons for the substantial thrust to weight is necessary acceleration for short runway takeoffs and just as importantly to still have excess thrust to climb way up there where the air is thin and high subsonic cruise can be achieved. Up there the airframe and the engine are both more efficient, but due to lost thrust with altitude, you need big powerful engines.
Remember that for jets and high performance turboprops, 3000-4000fpm climbs are common. It just doesn't take long until the terrain is no longer and issue and its more important to get to the destination faster and also save fuel. Flying on Vy typically wastes fuel, because you are running the engine at max continuous power/thrust, while not getting neither the best forward nor the best vertical speeds.
Big jets prefer to climb at speeds above 250KIAS, so they hit the 250KIAS below 10000ft limit.
But strictly speaking, what would be used as Vy, to clear critical terrain right after takeoff, something in the V2+20 to V2+50 range would be used. V2 might actually produce a better angle of climb, but its very uncomfortable to fly that close in case an engine quits. Even then this is used for as short a period as possible. V2+30 requires the aircraft has flaps deployed and is flying at half the speed it would like to go. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Large commercial jets operate within a much wider range of weights than most GA aircraft do, and since Vy varies with weight, it wouldn't make sense to publish "a" single Vy speed for them. The crew can get a best rate or best angle of climb speed from the FMC (which "knows" the current weight of the aircraft, based on current fuel & an entered Zero Fuel Weight).
From an empty aircraft with minimum fuel to a loaded aircraft with max fuel, the weight probably won't quite double for most commercial jet aircraft, but the one might be 170% or more of the other. With that much range, any single Vy you publish would be way far off in a lot of cases. On a GA aircraft, without an FMC and operating in a much narrower weight range, publishing a single speed makes much more sense as the delta between published and actual becomes smaller and the consequence of being a couple knots off is probably slight. | Airplanes certificated under FAR Part 25 (Transport Category Airplanes) must meet far more complex and regulated takeoff performance criteria than can be reduced to a (light aircraft) Vy or Vx (Vyse or Vxse) speed.
If you're taking off in a Cessna 310 and interested in gaining altitude as quickly as possible (rate) then having a published Vy speed (which can be adjusted for weight) is a benefit that the pilot may decide to take advantage of.
On the other hand, in a Transport Category Airplane a particular takeoff path (climb gradient) must be satisfied in accordance with [FAR Part 25.111](https://www.ecfr.gov/cgi-bin/retrieveECFR?gp=&SID=67f22790b882a3dc26f65b7053d7fc75&mc=true&n=pt14.1.25&r=PART&ty=HTML#se14.1.25_1115) criteria, which are fundamentally and functionally irrelevant to the establishment of a "Vy" speed (this does not mean a Vy speed for a light aircraft is less important, just less relevant considering the certification regulations).
The issue can be complex, but generally speaking Part 25 airplanes must (depending on the operational regulations involved, e.g., part 121, part 135 ops, etc.) takeoff and climb out using a profile (e.g. speeds, configuration, weight, thrust setting, procedures etc.) that allows for the avoidance of obstacles during the climb. see [AC 120-129 "Airport Obstacle Analysis"](http://www.faa.gov/documentLibrary/media/Advisory_Circular/AC120-91.pdf)
For example, during normal Part 121 operations, more often than not, the the thrust setting used for takeoff is less (sometimes far less) than 100%. The amount of thrust used is based on environmental/operational conditions (weight, runway, temp, obstacles, etc.) and computed so that the required climb gradient is achieved.
Performance engineers providing data to the carrier in textual form or programmed data (e.g. FMC) for each airport/runway reduce the very complex amalgamation of regulatory requirements, necessary climb performance, near/far obstacles in the area of consideration, etc. into thrust/airspeed/configuration settings for the crew.
An excellent discussion of this entire issue can be found in this [Aircraft Climb Performance](http://www.nbaa.org/ops/safety/climb-performance/20120510-one-engine-inoperative-climb-performance-planning.php) NBAA article. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Large commercial jets operate within a much wider range of weights than most GA aircraft do, and since Vy varies with weight, it wouldn't make sense to publish "a" single Vy speed for them. The crew can get a best rate or best angle of climb speed from the FMC (which "knows" the current weight of the aircraft, based on current fuel & an entered Zero Fuel Weight).
From an empty aircraft with minimum fuel to a loaded aircraft with max fuel, the weight probably won't quite double for most commercial jet aircraft, but the one might be 170% or more of the other. With that much range, any single Vy you publish would be way far off in a lot of cases. On a GA aircraft, without an FMC and operating in a much narrower weight range, publishing a single speed makes much more sense as the delta between published and actual becomes smaller and the consequence of being a couple knots off is probably slight. | Well they do of sorts. But your pilot friend is right, they are not tabulated for a transport category aircraft like is done for a Part 23 aircraft. Due to the large payloads, CG ranges and configurations, the best rate of climb speed must be computed for each situation. There is no one published Vy for a large transport category airplane.
Incidentally the best rate of climb varies for any aircraft you fly, it’s just that for smaller airplanes that range is quite small. As an example, in a Cessna 172 the best rate of climb Vy varies only a few knots between sea level and its service ceiling. Larger, more powerful GA aircraft will have tables published in the performance and limitations sections of their AFM listing this. Saying that any airplane has a single best rate of climb speed is a bit of a misnomer, similar to saying that an airplane has a ‘stall speed’, etc. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Large commercial jets operate within a much wider range of weights than most GA aircraft do, and since Vy varies with weight, it wouldn't make sense to publish "a" single Vy speed for them. The crew can get a best rate or best angle of climb speed from the FMC (which "knows" the current weight of the aircraft, based on current fuel & an entered Zero Fuel Weight).
From an empty aircraft with minimum fuel to a loaded aircraft with max fuel, the weight probably won't quite double for most commercial jet aircraft, but the one might be 170% or more of the other. With that much range, any single Vy you publish would be way far off in a lot of cases. On a GA aircraft, without an FMC and operating in a much narrower weight range, publishing a single speed makes much more sense as the delta between published and actual becomes smaller and the consequence of being a couple knots off is probably slight. | First things first. All the airplanes have a speed for best climb rate (Vy), and this includes transport category aircraft. But the speed Vy, does not matter to us because our climb performance calculations are a little bit more complex when compared to a small GA aircraft.
Think of this. For a general aviation pilot who flies a small aircraft, the main cost he/ she has to bear while flying the aircraft is what he/ she pays for the fuel. Other costs are miniscule when compared to that. So, the aim of a GA pilot will always be to fly while burning the least amount of fuel. Climbing and Vy gives exactly that as it allows for a much more fuel efficient flight, because the faster you reach the cruise altitude the faster you can reduce the power and lean the engine for the least amount of fuel burn. So, Vy matters in a smaller aircraft.
Now think of a transport category aircraft flown by an airline. Yes, the fuel is still a major cost, but an airline also have to pay for the lease or if they own the aircraft they need to cover the capital, they need to pay the pilots, cabin crew and ground engineers and they also need to put the aircraft away for much more longer, scheduled maintenance to keep it airworthy. All of these costs are what we call *time related costs.* The relationship between these time related costs and *fuel related costs* is known as the **Cost index (CI).**
>
> **CI = Time related costs / Fuel related costs**
>
>
>
[](https://i.stack.imgur.com/sirfS.png)
As pilots, we insert a CI into our flight management computer. A higher CI means, you will go faster burning more fuel but in the process, you will save time on the trip and save the airline time costs. On the other hand, flying at a lower cost index will burn less fuel and thus saving on fuel costs, but it increases flight time and the result is an increase in time related costs. Based on the CI and very importantly the weight of the aircraft, the computers will calculate an **ECON climb speed** called an **IAS(ECON)**. And this is the speed that we use to climb at.
If you want the airplane to climb at roughly the best rate of climb, you can set the cost index value to zero (0) in the flight management system. The computers will then calculate an **IAS(ECON)** to climb, based on the weight. This speed will be the Vy of the aircraft because at a zero cost index the whole aim of the aircraft will be to get to the cruising altitude faster and reduce the time spent in the fuel consuming climb segment so that more fuel is saved. The CI value will vary based on airlines. Some airlines have a very low CI while others have a higher CI. Most airlines prefer to keep it in an in between value, that is keeping a balance between fuel related and time related costs.
[](https://i.stack.imgur.com/fZmtV.png) |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Airplanes certificated under FAR Part 25 (Transport Category Airplanes) must meet far more complex and regulated takeoff performance criteria than can be reduced to a (light aircraft) Vy or Vx (Vyse or Vxse) speed.
If you're taking off in a Cessna 310 and interested in gaining altitude as quickly as possible (rate) then having a published Vy speed (which can be adjusted for weight) is a benefit that the pilot may decide to take advantage of.
On the other hand, in a Transport Category Airplane a particular takeoff path (climb gradient) must be satisfied in accordance with [FAR Part 25.111](https://www.ecfr.gov/cgi-bin/retrieveECFR?gp=&SID=67f22790b882a3dc26f65b7053d7fc75&mc=true&n=pt14.1.25&r=PART&ty=HTML#se14.1.25_1115) criteria, which are fundamentally and functionally irrelevant to the establishment of a "Vy" speed (this does not mean a Vy speed for a light aircraft is less important, just less relevant considering the certification regulations).
The issue can be complex, but generally speaking Part 25 airplanes must (depending on the operational regulations involved, e.g., part 121, part 135 ops, etc.) takeoff and climb out using a profile (e.g. speeds, configuration, weight, thrust setting, procedures etc.) that allows for the avoidance of obstacles during the climb. see [AC 120-129 "Airport Obstacle Analysis"](http://www.faa.gov/documentLibrary/media/Advisory_Circular/AC120-91.pdf)
For example, during normal Part 121 operations, more often than not, the the thrust setting used for takeoff is less (sometimes far less) than 100%. The amount of thrust used is based on environmental/operational conditions (weight, runway, temp, obstacles, etc.) and computed so that the required climb gradient is achieved.
Performance engineers providing data to the carrier in textual form or programmed data (e.g. FMC) for each airport/runway reduce the very complex amalgamation of regulatory requirements, necessary climb performance, near/far obstacles in the area of consideration, etc. into thrust/airspeed/configuration settings for the crew.
An excellent discussion of this entire issue can be found in this [Aircraft Climb Performance](http://www.nbaa.org/ops/safety/climb-performance/20120510-one-engine-inoperative-climb-performance-planning.php) NBAA article. | Actually modern jets in general do have massive excess thrust. One big reason is due to safety requirements to handle engine loss. Vy is a big issue while on a single engine or piston props. With two turbofans/turboprops running and at low altitudes, they "climb like a rocket" compared with single piston and even twin pistons with big engines.
Additional reasons for the substantial thrust to weight is necessary acceleration for short runway takeoffs and just as importantly to still have excess thrust to climb way up there where the air is thin and high subsonic cruise can be achieved. Up there the airframe and the engine are both more efficient, but due to lost thrust with altitude, you need big powerful engines.
Remember that for jets and high performance turboprops, 3000-4000fpm climbs are common. It just doesn't take long until the terrain is no longer and issue and its more important to get to the destination faster and also save fuel. Flying on Vy typically wastes fuel, because you are running the engine at max continuous power/thrust, while not getting neither the best forward nor the best vertical speeds.
Big jets prefer to climb at speeds above 250KIAS, so they hit the 250KIAS below 10000ft limit.
But strictly speaking, what would be used as Vy, to clear critical terrain right after takeoff, something in the V2+20 to V2+50 range would be used. V2 might actually produce a better angle of climb, but its very uncomfortable to fly that close in case an engine quits. Even then this is used for as short a period as possible. V2+30 requires the aircraft has flaps deployed and is flying at half the speed it would like to go. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Well they do of sorts. But your pilot friend is right, they are not tabulated for a transport category aircraft like is done for a Part 23 aircraft. Due to the large payloads, CG ranges and configurations, the best rate of climb speed must be computed for each situation. There is no one published Vy for a large transport category airplane.
Incidentally the best rate of climb varies for any aircraft you fly, it’s just that for smaller airplanes that range is quite small. As an example, in a Cessna 172 the best rate of climb Vy varies only a few knots between sea level and its service ceiling. Larger, more powerful GA aircraft will have tables published in the performance and limitations sections of their AFM listing this. Saying that any airplane has a single best rate of climb speed is a bit of a misnomer, similar to saying that an airplane has a ‘stall speed’, etc. | Actually modern jets in general do have massive excess thrust. One big reason is due to safety requirements to handle engine loss. Vy is a big issue while on a single engine or piston props. With two turbofans/turboprops running and at low altitudes, they "climb like a rocket" compared with single piston and even twin pistons with big engines.
Additional reasons for the substantial thrust to weight is necessary acceleration for short runway takeoffs and just as importantly to still have excess thrust to climb way up there where the air is thin and high subsonic cruise can be achieved. Up there the airframe and the engine are both more efficient, but due to lost thrust with altitude, you need big powerful engines.
Remember that for jets and high performance turboprops, 3000-4000fpm climbs are common. It just doesn't take long until the terrain is no longer and issue and its more important to get to the destination faster and also save fuel. Flying on Vy typically wastes fuel, because you are running the engine at max continuous power/thrust, while not getting neither the best forward nor the best vertical speeds.
Big jets prefer to climb at speeds above 250KIAS, so they hit the 250KIAS below 10000ft limit.
But strictly speaking, what would be used as Vy, to clear critical terrain right after takeoff, something in the V2+20 to V2+50 range would be used. V2 might actually produce a better angle of climb, but its very uncomfortable to fly that close in case an engine quits. Even then this is used for as short a period as possible. V2+30 requires the aircraft has flaps deployed and is flying at half the speed it would like to go. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | First things first. All the airplanes have a speed for best climb rate (Vy), and this includes transport category aircraft. But the speed Vy, does not matter to us because our climb performance calculations are a little bit more complex when compared to a small GA aircraft.
Think of this. For a general aviation pilot who flies a small aircraft, the main cost he/ she has to bear while flying the aircraft is what he/ she pays for the fuel. Other costs are miniscule when compared to that. So, the aim of a GA pilot will always be to fly while burning the least amount of fuel. Climbing and Vy gives exactly that as it allows for a much more fuel efficient flight, because the faster you reach the cruise altitude the faster you can reduce the power and lean the engine for the least amount of fuel burn. So, Vy matters in a smaller aircraft.
Now think of a transport category aircraft flown by an airline. Yes, the fuel is still a major cost, but an airline also have to pay for the lease or if they own the aircraft they need to cover the capital, they need to pay the pilots, cabin crew and ground engineers and they also need to put the aircraft away for much more longer, scheduled maintenance to keep it airworthy. All of these costs are what we call *time related costs.* The relationship between these time related costs and *fuel related costs* is known as the **Cost index (CI).**
>
> **CI = Time related costs / Fuel related costs**
>
>
>
[](https://i.stack.imgur.com/sirfS.png)
As pilots, we insert a CI into our flight management computer. A higher CI means, you will go faster burning more fuel but in the process, you will save time on the trip and save the airline time costs. On the other hand, flying at a lower cost index will burn less fuel and thus saving on fuel costs, but it increases flight time and the result is an increase in time related costs. Based on the CI and very importantly the weight of the aircraft, the computers will calculate an **ECON climb speed** called an **IAS(ECON)**. And this is the speed that we use to climb at.
If you want the airplane to climb at roughly the best rate of climb, you can set the cost index value to zero (0) in the flight management system. The computers will then calculate an **IAS(ECON)** to climb, based on the weight. This speed will be the Vy of the aircraft because at a zero cost index the whole aim of the aircraft will be to get to the cruising altitude faster and reduce the time spent in the fuel consuming climb segment so that more fuel is saved. The CI value will vary based on airlines. Some airlines have a very low CI while others have a higher CI. Most airlines prefer to keep it in an in between value, that is keeping a balance between fuel related and time related costs.
[](https://i.stack.imgur.com/fZmtV.png) | Actually modern jets in general do have massive excess thrust. One big reason is due to safety requirements to handle engine loss. Vy is a big issue while on a single engine or piston props. With two turbofans/turboprops running and at low altitudes, they "climb like a rocket" compared with single piston and even twin pistons with big engines.
Additional reasons for the substantial thrust to weight is necessary acceleration for short runway takeoffs and just as importantly to still have excess thrust to climb way up there where the air is thin and high subsonic cruise can be achieved. Up there the airframe and the engine are both more efficient, but due to lost thrust with altitude, you need big powerful engines.
Remember that for jets and high performance turboprops, 3000-4000fpm climbs are common. It just doesn't take long until the terrain is no longer and issue and its more important to get to the destination faster and also save fuel. Flying on Vy typically wastes fuel, because you are running the engine at max continuous power/thrust, while not getting neither the best forward nor the best vertical speeds.
Big jets prefer to climb at speeds above 250KIAS, so they hit the 250KIAS below 10000ft limit.
But strictly speaking, what would be used as Vy, to clear critical terrain right after takeoff, something in the V2+20 to V2+50 range would be used. V2 might actually produce a better angle of climb, but its very uncomfortable to fly that close in case an engine quits. Even then this is used for as short a period as possible. V2+30 requires the aircraft has flaps deployed and is flying at half the speed it would like to go. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Airplanes certificated under FAR Part 25 (Transport Category Airplanes) must meet far more complex and regulated takeoff performance criteria than can be reduced to a (light aircraft) Vy or Vx (Vyse or Vxse) speed.
If you're taking off in a Cessna 310 and interested in gaining altitude as quickly as possible (rate) then having a published Vy speed (which can be adjusted for weight) is a benefit that the pilot may decide to take advantage of.
On the other hand, in a Transport Category Airplane a particular takeoff path (climb gradient) must be satisfied in accordance with [FAR Part 25.111](https://www.ecfr.gov/cgi-bin/retrieveECFR?gp=&SID=67f22790b882a3dc26f65b7053d7fc75&mc=true&n=pt14.1.25&r=PART&ty=HTML#se14.1.25_1115) criteria, which are fundamentally and functionally irrelevant to the establishment of a "Vy" speed (this does not mean a Vy speed for a light aircraft is less important, just less relevant considering the certification regulations).
The issue can be complex, but generally speaking Part 25 airplanes must (depending on the operational regulations involved, e.g., part 121, part 135 ops, etc.) takeoff and climb out using a profile (e.g. speeds, configuration, weight, thrust setting, procedures etc.) that allows for the avoidance of obstacles during the climb. see [AC 120-129 "Airport Obstacle Analysis"](http://www.faa.gov/documentLibrary/media/Advisory_Circular/AC120-91.pdf)
For example, during normal Part 121 operations, more often than not, the the thrust setting used for takeoff is less (sometimes far less) than 100%. The amount of thrust used is based on environmental/operational conditions (weight, runway, temp, obstacles, etc.) and computed so that the required climb gradient is achieved.
Performance engineers providing data to the carrier in textual form or programmed data (e.g. FMC) for each airport/runway reduce the very complex amalgamation of regulatory requirements, necessary climb performance, near/far obstacles in the area of consideration, etc. into thrust/airspeed/configuration settings for the crew.
An excellent discussion of this entire issue can be found in this [Aircraft Climb Performance](http://www.nbaa.org/ops/safety/climb-performance/20120510-one-engine-inoperative-climb-performance-planning.php) NBAA article. | Well they do of sorts. But your pilot friend is right, they are not tabulated for a transport category aircraft like is done for a Part 23 aircraft. Due to the large payloads, CG ranges and configurations, the best rate of climb speed must be computed for each situation. There is no one published Vy for a large transport category airplane.
Incidentally the best rate of climb varies for any aircraft you fly, it’s just that for smaller airplanes that range is quite small. As an example, in a Cessna 172 the best rate of climb Vy varies only a few knots between sea level and its service ceiling. Larger, more powerful GA aircraft will have tables published in the performance and limitations sections of their AFM listing this. Saying that any airplane has a single best rate of climb speed is a bit of a misnomer, similar to saying that an airplane has a ‘stall speed’, etc. |
27,488 | I was talking with a pilot about an inability to maintain the targeted climb rate in a particular situation and asked him what the Vy was for the jet. He curtly replied "Vy is only for Part 23 aircraft." (FYI for those outside the US: Part 25 aircraft are commerical planes, while Part 23 are usually general aviation planes. You can find more details [here](https://www.faa.gov/aircraft/air_cert/airworthiness_certification/std_awcert/std_awcert_regs/regs/).)
Yet, I know for a fact that there is a maximum excess thrust speed, because at a certain speed drag is at a minimum. This should be close to Vy. I also know that rate of climb is frequently listed for these aircraft. However, the optimal speed for gaining altitude isn't usually listed for commercial aircraft like it is for GA aircraft. In fact, many of the v-speeds like Vmca and Vdec are harder to find for larger aircraft.
[](https://i.stack.imgur.com/DZDnj.jpg)
Why is this? I can think of several possibilities:
* Commercial aircraft speeds are defined by ATC and operating procedures, not by performance considerations
* Commercial aircraft have enough thrust that climb performance limits isn't an issue (which I doubt from my experience).
* Commercial aircraft use other parameters for similar purposes like rate of climb, v2, or long range cruise speed
* Jets don't list this speed but propeller planes do | 2016/05/11 | [
"https://aviation.stackexchange.com/questions/27488",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/14613/"
] | Airplanes certificated under FAR Part 25 (Transport Category Airplanes) must meet far more complex and regulated takeoff performance criteria than can be reduced to a (light aircraft) Vy or Vx (Vyse or Vxse) speed.
If you're taking off in a Cessna 310 and interested in gaining altitude as quickly as possible (rate) then having a published Vy speed (which can be adjusted for weight) is a benefit that the pilot may decide to take advantage of.
On the other hand, in a Transport Category Airplane a particular takeoff path (climb gradient) must be satisfied in accordance with [FAR Part 25.111](https://www.ecfr.gov/cgi-bin/retrieveECFR?gp=&SID=67f22790b882a3dc26f65b7053d7fc75&mc=true&n=pt14.1.25&r=PART&ty=HTML#se14.1.25_1115) criteria, which are fundamentally and functionally irrelevant to the establishment of a "Vy" speed (this does not mean a Vy speed for a light aircraft is less important, just less relevant considering the certification regulations).
The issue can be complex, but generally speaking Part 25 airplanes must (depending on the operational regulations involved, e.g., part 121, part 135 ops, etc.) takeoff and climb out using a profile (e.g. speeds, configuration, weight, thrust setting, procedures etc.) that allows for the avoidance of obstacles during the climb. see [AC 120-129 "Airport Obstacle Analysis"](http://www.faa.gov/documentLibrary/media/Advisory_Circular/AC120-91.pdf)
For example, during normal Part 121 operations, more often than not, the the thrust setting used for takeoff is less (sometimes far less) than 100%. The amount of thrust used is based on environmental/operational conditions (weight, runway, temp, obstacles, etc.) and computed so that the required climb gradient is achieved.
Performance engineers providing data to the carrier in textual form or programmed data (e.g. FMC) for each airport/runway reduce the very complex amalgamation of regulatory requirements, necessary climb performance, near/far obstacles in the area of consideration, etc. into thrust/airspeed/configuration settings for the crew.
An excellent discussion of this entire issue can be found in this [Aircraft Climb Performance](http://www.nbaa.org/ops/safety/climb-performance/20120510-one-engine-inoperative-climb-performance-planning.php) NBAA article. | First things first. All the airplanes have a speed for best climb rate (Vy), and this includes transport category aircraft. But the speed Vy, does not matter to us because our climb performance calculations are a little bit more complex when compared to a small GA aircraft.
Think of this. For a general aviation pilot who flies a small aircraft, the main cost he/ she has to bear while flying the aircraft is what he/ she pays for the fuel. Other costs are miniscule when compared to that. So, the aim of a GA pilot will always be to fly while burning the least amount of fuel. Climbing and Vy gives exactly that as it allows for a much more fuel efficient flight, because the faster you reach the cruise altitude the faster you can reduce the power and lean the engine for the least amount of fuel burn. So, Vy matters in a smaller aircraft.
Now think of a transport category aircraft flown by an airline. Yes, the fuel is still a major cost, but an airline also have to pay for the lease or if they own the aircraft they need to cover the capital, they need to pay the pilots, cabin crew and ground engineers and they also need to put the aircraft away for much more longer, scheduled maintenance to keep it airworthy. All of these costs are what we call *time related costs.* The relationship between these time related costs and *fuel related costs* is known as the **Cost index (CI).**
>
> **CI = Time related costs / Fuel related costs**
>
>
>
[](https://i.stack.imgur.com/sirfS.png)
As pilots, we insert a CI into our flight management computer. A higher CI means, you will go faster burning more fuel but in the process, you will save time on the trip and save the airline time costs. On the other hand, flying at a lower cost index will burn less fuel and thus saving on fuel costs, but it increases flight time and the result is an increase in time related costs. Based on the CI and very importantly the weight of the aircraft, the computers will calculate an **ECON climb speed** called an **IAS(ECON)**. And this is the speed that we use to climb at.
If you want the airplane to climb at roughly the best rate of climb, you can set the cost index value to zero (0) in the flight management system. The computers will then calculate an **IAS(ECON)** to climb, based on the weight. This speed will be the Vy of the aircraft because at a zero cost index the whole aim of the aircraft will be to get to the cruising altitude faster and reduce the time spent in the fuel consuming climb segment so that more fuel is saved. The CI value will vary based on airlines. Some airlines have a very low CI while others have a higher CI. Most airlines prefer to keep it in an in between value, that is keeping a balance between fuel related and time related costs.
[](https://i.stack.imgur.com/fZmtV.png) |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | Probably this is more a workaround that proper support for test module overriding, but it allows to override production modules with test one. The code snippets below shows simple case when you have just one component and one module, but this should work for any scenario. It requires a lot of boilerplate and code repetition so be aware of this. I'm sure there'll be a better way to achieve this in the future.
I've also created a [project with examples for Espresso and Robolectric](https://github.com/tomrozb/dagger-testing). This answer is based on code contained in the project.
The solution requires two things:
* provide additional setter for `@Component`
* test component must extend the production component
Assume we've simple `Application` like below:
```
public class App extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerApp_AppComponent.create();
}
public AppComponent component() {
return mAppComponent;
}
@Singleton
@Component(modules = StringHolderModule.class)
public interface AppComponent {
void inject(MainActivity activity);
}
@Module
public static class StringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder("Release string");
}
}
}
```
We've to add additional method to `App` class. This allows us to replace the production component.
```
/**
* Visible only for testing purposes.
*/
// @VisibleForTesting
public void setTestComponent(AppComponent appComponent) {
mAppComponent = appComponent;
}
```
As you can see the `StringHolder` object contains "Release string" value. This object is injected to the `MainActivity`.
```
public class MainActivity extends ActionBarActivity {
@Inject
StringHolder mStringHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((App) getApplication()).component().inject(this);
}
}
```
In our tests we want to provide `StringHolder` with "Test string". We've to set the test component in `App` class before the `MainActivity` is created - because `StringHolder` is injected in the `onCreate` callback.
In Dagger v2.0.0 components can extend other interfaces. We can leverage this to create our `TestAppComponent` which **extends** `AppComponent`.
```
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
```
Now we're able to define our test modules e.g. `TestStringHolderModule`. The last step is to set the test component using previously added setter method in `App` class. It's important to do this before the activity is created.
```
((App) application).setTestComponent(mTestAppComponent);
```
**Espresso**
For Espresso I've created custom `ActivityTestRule` which allows to swap the component before the activity is created. You can find code for `DaggerActivityTestRule` [here](https://github.com/tomrozb/dagger-testing/blob/master/app/src/androidTest/java/pl/dagger/testing/util/DaggerActivityTestRule.java).
Sample test with Espresso:
```
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
public static final String TEST_STRING = "Test string";
private TestAppComponent mTestAppComponent;
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new DaggerActivityTestRule<>(MainActivity.class, new OnBeforeActivityLaunchedListener<MainActivity>() {
@Override
public void beforeActivityLaunched(@NonNull Application application, @NonNull MainActivity activity) {
mTestAppComponent = DaggerMainActivityEspressoTest_TestAppComponent.create();
((App) application).setTestComponent(mTestAppComponent);
}
});
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
...
// when
onView(...)
// then
onView(...)
.check(...);
}
}
```
**Robolectric**
It's much easier with Robolectric thanks to the `RuntimeEnvironment.application`.
Sample test with Robolectric:
```
@RunWith(RobolectricGradleTestRunner.class)
@Config(emulateSdk = 21, reportSdk = 21, constants = BuildConfig.class)
public class MainActivityRobolectricTest {
public static final String TEST_STRING = "Test string";
@Before
public void setTestComponent() {
AppComponent appComponent = DaggerMainActivityRobolectricTest_TestAppComponent.create();
((App) RuntimeEnvironment.application).setTestComponent(appComponent);
}
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
// when
...
// then
assertThat(...)
}
}
``` | It seems I've found yet another way and it's working so far.
First, a component interface that is not a component itself:
**MyComponent.java**
```
interface MyComponent {
Foo provideFoo();
}
```
Then we have two different modules: actual one and testing one.
**MyModule.java**
```
@Module
class MyModule {
@Provides
public Foo getFoo() {
return new Foo();
}
}
```
**TestModule.java**
```
@Module
class TestModule {
private Foo foo;
public void setFoo(Foo foo) {
this.foo = foo;
}
@Provides
public Foo getFoo() {
return foo;
}
}
```
And we have two components to use these two modules:
**MyRealComponent.java**
```
@Component(modules=MyModule.class)
interface MyRealComponent extends MyComponent {
Foo provideFoo(); // without this dagger will not do its magic
}
```
**MyTestComponent.java**
```
@Component(modules=TestModule.class)
interface MyTestComponent extends MyComponent {
Foo provideFoo();
}
```
In application we do this:
```
MyComponent component = DaggerMyRealComponent.create();
<...>
Foo foo = component.getFoo();
```
While in test code we use:
```
TestModule testModule = new TestModule();
testModule.setFoo(someMockFoo);
MyComponent component = DaggerMyTestComponent.builder()
.testModule(testModule).build();
<...>
Foo foo = component.getFoo(); // will return someMockFoo
```
The problem is that we have to copy all methods of MyModule into TestModule, but it can be done by having MyModule inside TestModule and use MyModule's methods unless they are directly set from outside. Like this:
**TestModule.java**
```
@Module
class TestModule {
MyModule myModule = new MyModule();
private Foo foo = myModule.getFoo();
public void setFoo(Foo foo) {
this.foo = foo;
}
@Provides
public Foo getFoo() {
return foo;
}
}
``` |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | The workaround proposed by @tomrozb is very good and put me on the right track, but my problem with it was that it exposed a `setTestComponent()` method in the PRODUCTION `Application` class. I was able to get this working slightly differently, such that my production application doesn't have to know anything at all about my testing environment.
TL;DR - Extend your Application class with a test application that uses your test component and module. Then create a custom test runner that runs on the test application instead of your production application.
---
EDIT: This method only works for global dependencies (typically marked with `@Singleton`). If your app has components with different scope (e.g. per activity) then you'll either need to create subclasses for each scope, or use @tomrozb's original answer. Thanks to @tomrozb for pointing this out!
---
This example uses the [AndroidJUnitRunner](https://developer.android.com/intl/ko/reference/android/support/test/runner/AndroidJUnitRunner.html) test runner but this could probably be adapted to [Robolectric](http://robolectric.org/custom-test-runner/) and others.
First, my production application. It looks something like this:
```
public class MyApp extends Application {
protected MyComponent component;
public void setComponent() {
component = DaggerMyComponent.builder()
.myModule(new MyModule())
.build();
component.inject(this);
}
public MyComponent getComponent() {
return component;
}
@Override
public void onCreate() {
super.onCreate();
setComponent();
}
}
```
This way, my activities and other class that use `@Inject` simply have to call something like `getApp().getComponent().inject(this);` to inject themselves into the dependency graph.
For completeness, here is my component:
```
@Singleton
@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(MyApp app);
// other injects and getters
}
```
And my module:
```
@Module
public class MyModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// ... other providers
}
```
For the testing environment, extend your test component from your production component. This is the same as in @tomrozb's answer.
```
@Singleton
@Component(modules = {MyTestModule.class})
public interface MyTestComponent extends MyComponent {
// more component methods if necessary
}
```
And the test module can be whatever you want. Presumably you'll handle your mocking and stuff in here (I use Mockito).
```
@Module
public class MyTestModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// Make sure to implement all the same methods here that are in MyModule,
// even though it's not an override.
}
```
So now, the tricky part. Create a test application class that extends from your production application class, and override the `setComponent()` method to set the test component with the test module. Note that this can only work if `MyTestComponent` is a descendant of `MyComponent`.
```
public class MyTestApp extends MyApp {
// Make sure to call this method during setup of your tests!
@Override
public void setComponent() {
component = DaggerMyTestComponent.builder()
.myTestModule(new MyTestModule())
.build();
component.inject(this)
}
}
```
Make sure you call `setComponent()` on the app before you begin your tests to make sure the graph is set up correctly. Something like this:
```
@Before
public void setUp() {
MyTestApp app = (MyTestApp) getInstrumentation().getTargetContext().getApplicationContext();
app.setComponent()
((MyTestComponent) app.getComponent()).inject(this)
}
```
Finally, the last missing piece is to override your TestRunner with a custom test runner. In my project I was using the `AndroidJUnitRunner` but it looks like you can [do the same with Robolectric](http://robolectric.org/custom-test-runner/).
```
public class TestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(@NonNull ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, MyTestApp.class.getName(), context);
}
}
```
You'll also have to update your `testInstrumentationRunner` gradle, like so:
```
testInstrumentationRunner "com.mypackage.TestRunner"
```
And if you're using Android Studio, you'll also have to click Edit Configuration from the run menu and enter the name of your test runner under "Specific instrumentation runner".
And that's it! Hopefully this information helps somebody :) | Can you guys check out my solution, I have included subcomponent example: <https://github.com/nongdenchet/android-mvvm-with-tests>. Thank you @vaughandroid, I have borrowed your overriding methods. Here is the main point:
1. I create a class to create subcomponent. My custom application will also hold an instance of this class:
```
// The builder class
public class ComponentBuilder {
private AppComponent appComponent;
public ComponentBuilder(AppComponent appComponent) {
this.appComponent = appComponent;
}
public PlacesComponent placesComponent() {
return appComponent.plus(new PlacesModule());
}
public PurchaseComponent purchaseComponent() {
return appComponent.plus(new PurchaseModule());
}
}
// My custom application class
public class MyApplication extends Application {
protected AppComponent mAppComponent;
protected ComponentBuilder mComponentBuilder;
@Override
public void onCreate() {
super.onCreate();
// Create app component
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule())
.build();
// Create component builder
mComponentBuilder = new ComponentBuilder(mAppComponent);
}
public AppComponent component() {
return mAppComponent;
}
public ComponentBuilder builder() {
return mComponentBuilder;
}
}
// Sample using builder class:
public class PurchaseActivity extends BaseActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Setup dependency
((MyApplication) getApplication())
.builder()
.purchaseComponent()
.inject(this);
...
}
}
```
2. I have a custom TestApplication that extends the MyApplication class above. This class contains two methods to replace the root component and the builder:
```
public class TestApplication extends MyApplication {
public void setComponent(AppComponent appComponent) {
this.mAppComponent = appComponent;
}
public void setComponentBuilder(ComponentBuilder componentBuilder) {
this.mComponentBuilder = componentBuilder;
}
}
```
3. Finally I will try to mock or stub the dependency of module and builder to provide fake dependency to the activity:
```
@MediumTest
@RunWith(AndroidJUnit4.class)
public class PurchaseActivityTest {
@Rule
public ActivityTestRule<PurchaseActivity> activityTestRule =
new ActivityTestRule<>(PurchaseActivity.class, true, false);
@Before
public void setUp() throws Exception {
PurchaseModule stubModule = new PurchaseModule() {
@Provides
@ViewScope
public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) {
return new StubPurchaseViewModel();
}
};
// Setup test component
AppComponent component = ApplicationUtils.application().component();
ApplicationUtils.application().setComponentBuilder(new ComponentBuilder(component) {
@Override
public PurchaseComponent purchaseComponent() {
return component.plus(stubModule);
}
});
// Run the activity
activityTestRule.launchActivity(new Intent());
}
``` |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | The workaround proposed by @tomrozb is very good and put me on the right track, but my problem with it was that it exposed a `setTestComponent()` method in the PRODUCTION `Application` class. I was able to get this working slightly differently, such that my production application doesn't have to know anything at all about my testing environment.
TL;DR - Extend your Application class with a test application that uses your test component and module. Then create a custom test runner that runs on the test application instead of your production application.
---
EDIT: This method only works for global dependencies (typically marked with `@Singleton`). If your app has components with different scope (e.g. per activity) then you'll either need to create subclasses for each scope, or use @tomrozb's original answer. Thanks to @tomrozb for pointing this out!
---
This example uses the [AndroidJUnitRunner](https://developer.android.com/intl/ko/reference/android/support/test/runner/AndroidJUnitRunner.html) test runner but this could probably be adapted to [Robolectric](http://robolectric.org/custom-test-runner/) and others.
First, my production application. It looks something like this:
```
public class MyApp extends Application {
protected MyComponent component;
public void setComponent() {
component = DaggerMyComponent.builder()
.myModule(new MyModule())
.build();
component.inject(this);
}
public MyComponent getComponent() {
return component;
}
@Override
public void onCreate() {
super.onCreate();
setComponent();
}
}
```
This way, my activities and other class that use `@Inject` simply have to call something like `getApp().getComponent().inject(this);` to inject themselves into the dependency graph.
For completeness, here is my component:
```
@Singleton
@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(MyApp app);
// other injects and getters
}
```
And my module:
```
@Module
public class MyModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// ... other providers
}
```
For the testing environment, extend your test component from your production component. This is the same as in @tomrozb's answer.
```
@Singleton
@Component(modules = {MyTestModule.class})
public interface MyTestComponent extends MyComponent {
// more component methods if necessary
}
```
And the test module can be whatever you want. Presumably you'll handle your mocking and stuff in here (I use Mockito).
```
@Module
public class MyTestModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// Make sure to implement all the same methods here that are in MyModule,
// even though it's not an override.
}
```
So now, the tricky part. Create a test application class that extends from your production application class, and override the `setComponent()` method to set the test component with the test module. Note that this can only work if `MyTestComponent` is a descendant of `MyComponent`.
```
public class MyTestApp extends MyApp {
// Make sure to call this method during setup of your tests!
@Override
public void setComponent() {
component = DaggerMyTestComponent.builder()
.myTestModule(new MyTestModule())
.build();
component.inject(this)
}
}
```
Make sure you call `setComponent()` on the app before you begin your tests to make sure the graph is set up correctly. Something like this:
```
@Before
public void setUp() {
MyTestApp app = (MyTestApp) getInstrumentation().getTargetContext().getApplicationContext();
app.setComponent()
((MyTestComponent) app.getComponent()).inject(this)
}
```
Finally, the last missing piece is to override your TestRunner with a custom test runner. In my project I was using the `AndroidJUnitRunner` but it looks like you can [do the same with Robolectric](http://robolectric.org/custom-test-runner/).
```
public class TestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(@NonNull ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, MyTestApp.class.getName(), context);
}
}
```
You'll also have to update your `testInstrumentationRunner` gradle, like so:
```
testInstrumentationRunner "com.mypackage.TestRunner"
```
And if you're using Android Studio, you'll also have to click Edit Configuration from the run menu and enter the name of your test runner under "Specific instrumentation runner".
And that's it! Hopefully this information helps somebody :) | **THIS ANSWER IS OBSOLETE. READ BELOW IN EDIT.**
Disappointingly enough, you *cannot extend from a Module*, or you'll get the following compilation error:
```
Error:(24, 21) error: @Provides methods may not override another method.
Overrides: Provides
retrofit.Endpoint hu.mycompany.injection.modules.application.domain.networking.EndpointModule.myServerEndpoint()
```
Meaning you can't just extend a "mock module" and replace your original module. Nope, it's not that easy. And considering you design your components in such a way that it directly binds the Modules by class, you can't really just make a "TestComponent" either, because that'd mean you have to reinvent **everything** from scratch, and you'd have to make a component for every variation! Clearly that is not an option.
So on the smaller scale, what I ended up doing is making a "provider" that I give to the module, which determines whether I select the mock or the production type.
```
public interface EndpointProvider {
Endpoint serverEndpoint();
}
public class ProdEndpointProvider implements EndpointProvider {
@Override
public Endpoint serverEndpoint() {
return new ServerEndpoint();
}
}
public class TestEndpointProvider implements EndpointProvider {
@Override
public Endpoint serverEndpoint() {
return new TestServerEndpoint();
}
}
@Module
public class EndpointModule {
private Endpoint serverEndpoint;
private EndpointProvider endpointProvider;
public EndpointModule(EndpointProvider endpointProvider) {
this.endpointProvider = endpointProvider;
}
@Named("server")
@Provides
public Endpoint serverEndpoint() {
return endpointProvider.serverEndpoint();
}
}
```
EDIT: Apparently as the error message says, you CAN'T override another method using a `@Provides` annotated method, but that doesn't mean you can't override an `@Provides` annotated method :(
All that magic was for naught! You can just extend a Module without putting `@Provides` on the method and it works... Refer to @vaughandroid 's answer. |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | As @EpicPandaForce rightly says, you can't extend Modules. However, I came up with a sneaky workaround for this which I think avoids a lot of the boilerplate which the other examples suffer from.
The trick to 'extending' a Module is to create a partial mock, and mock out the provider methods which you want to override.
Using [Mockito](http://mockito.org/):
```
MyModule module = Mockito.spy(new MyModule());
Mockito.doReturn("mocked string").when(module).provideString();
MyComponent component = DaggerMyComponent.builder()
.myModule(module)
.build();
app.setComponent(component);
```
I created [this gist](https://gist.github.com/vaughandroid/2ac4aeb28d3e6b008fa4) here to show a full example.
**EDIT**
It turns out you can do this even without a partial mock, like so:
```
MyComponent component = DaggerMyComponent.builder()
.myModule(new MyModule() {
@Override public String provideString() {
return "mocked string";
}
})
.build();
app.setComponent(component);
``` | Can you guys check out my solution, I have included subcomponent example: <https://github.com/nongdenchet/android-mvvm-with-tests>. Thank you @vaughandroid, I have borrowed your overriding methods. Here is the main point:
1. I create a class to create subcomponent. My custom application will also hold an instance of this class:
```
// The builder class
public class ComponentBuilder {
private AppComponent appComponent;
public ComponentBuilder(AppComponent appComponent) {
this.appComponent = appComponent;
}
public PlacesComponent placesComponent() {
return appComponent.plus(new PlacesModule());
}
public PurchaseComponent purchaseComponent() {
return appComponent.plus(new PurchaseModule());
}
}
// My custom application class
public class MyApplication extends Application {
protected AppComponent mAppComponent;
protected ComponentBuilder mComponentBuilder;
@Override
public void onCreate() {
super.onCreate();
// Create app component
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule())
.build();
// Create component builder
mComponentBuilder = new ComponentBuilder(mAppComponent);
}
public AppComponent component() {
return mAppComponent;
}
public ComponentBuilder builder() {
return mComponentBuilder;
}
}
// Sample using builder class:
public class PurchaseActivity extends BaseActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Setup dependency
((MyApplication) getApplication())
.builder()
.purchaseComponent()
.inject(this);
...
}
}
```
2. I have a custom TestApplication that extends the MyApplication class above. This class contains two methods to replace the root component and the builder:
```
public class TestApplication extends MyApplication {
public void setComponent(AppComponent appComponent) {
this.mAppComponent = appComponent;
}
public void setComponentBuilder(ComponentBuilder componentBuilder) {
this.mComponentBuilder = componentBuilder;
}
}
```
3. Finally I will try to mock or stub the dependency of module and builder to provide fake dependency to the activity:
```
@MediumTest
@RunWith(AndroidJUnit4.class)
public class PurchaseActivityTest {
@Rule
public ActivityTestRule<PurchaseActivity> activityTestRule =
new ActivityTestRule<>(PurchaseActivity.class, true, false);
@Before
public void setUp() throws Exception {
PurchaseModule stubModule = new PurchaseModule() {
@Provides
@ViewScope
public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) {
return new StubPurchaseViewModel();
}
};
// Setup test component
AppComponent component = ApplicationUtils.application().component();
ApplicationUtils.application().setComponentBuilder(new ComponentBuilder(component) {
@Override
public PurchaseComponent purchaseComponent() {
return component.plus(stubModule);
}
});
// Run the activity
activityTestRule.launchActivity(new Intent());
}
``` |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | Probably this is more a workaround that proper support for test module overriding, but it allows to override production modules with test one. The code snippets below shows simple case when you have just one component and one module, but this should work for any scenario. It requires a lot of boilerplate and code repetition so be aware of this. I'm sure there'll be a better way to achieve this in the future.
I've also created a [project with examples for Espresso and Robolectric](https://github.com/tomrozb/dagger-testing). This answer is based on code contained in the project.
The solution requires two things:
* provide additional setter for `@Component`
* test component must extend the production component
Assume we've simple `Application` like below:
```
public class App extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerApp_AppComponent.create();
}
public AppComponent component() {
return mAppComponent;
}
@Singleton
@Component(modules = StringHolderModule.class)
public interface AppComponent {
void inject(MainActivity activity);
}
@Module
public static class StringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder("Release string");
}
}
}
```
We've to add additional method to `App` class. This allows us to replace the production component.
```
/**
* Visible only for testing purposes.
*/
// @VisibleForTesting
public void setTestComponent(AppComponent appComponent) {
mAppComponent = appComponent;
}
```
As you can see the `StringHolder` object contains "Release string" value. This object is injected to the `MainActivity`.
```
public class MainActivity extends ActionBarActivity {
@Inject
StringHolder mStringHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((App) getApplication()).component().inject(this);
}
}
```
In our tests we want to provide `StringHolder` with "Test string". We've to set the test component in `App` class before the `MainActivity` is created - because `StringHolder` is injected in the `onCreate` callback.
In Dagger v2.0.0 components can extend other interfaces. We can leverage this to create our `TestAppComponent` which **extends** `AppComponent`.
```
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
```
Now we're able to define our test modules e.g. `TestStringHolderModule`. The last step is to set the test component using previously added setter method in `App` class. It's important to do this before the activity is created.
```
((App) application).setTestComponent(mTestAppComponent);
```
**Espresso**
For Espresso I've created custom `ActivityTestRule` which allows to swap the component before the activity is created. You can find code for `DaggerActivityTestRule` [here](https://github.com/tomrozb/dagger-testing/blob/master/app/src/androidTest/java/pl/dagger/testing/util/DaggerActivityTestRule.java).
Sample test with Espresso:
```
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
public static final String TEST_STRING = "Test string";
private TestAppComponent mTestAppComponent;
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new DaggerActivityTestRule<>(MainActivity.class, new OnBeforeActivityLaunchedListener<MainActivity>() {
@Override
public void beforeActivityLaunched(@NonNull Application application, @NonNull MainActivity activity) {
mTestAppComponent = DaggerMainActivityEspressoTest_TestAppComponent.create();
((App) application).setTestComponent(mTestAppComponent);
}
});
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
...
// when
onView(...)
// then
onView(...)
.check(...);
}
}
```
**Robolectric**
It's much easier with Robolectric thanks to the `RuntimeEnvironment.application`.
Sample test with Robolectric:
```
@RunWith(RobolectricGradleTestRunner.class)
@Config(emulateSdk = 21, reportSdk = 21, constants = BuildConfig.class)
public class MainActivityRobolectricTest {
public static final String TEST_STRING = "Test string";
@Before
public void setTestComponent() {
AppComponent appComponent = DaggerMainActivityRobolectricTest_TestAppComponent.create();
((App) RuntimeEnvironment.application).setTestComponent(appComponent);
}
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
// when
...
// then
assertThat(...)
}
}
``` | With Dagger2, you can pass a specific module (the TestModule there) to a component using the generated builder api.
```
ApplicationComponent appComponent = Dagger_ApplicationComponent.builder()
.helloModule(new TestModule())
.build();
```
Please note that, Dagger\_ApplicationComponent is a generated class with the new @Component annotation. |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | As @EpicPandaForce rightly says, you can't extend Modules. However, I came up with a sneaky workaround for this which I think avoids a lot of the boilerplate which the other examples suffer from.
The trick to 'extending' a Module is to create a partial mock, and mock out the provider methods which you want to override.
Using [Mockito](http://mockito.org/):
```
MyModule module = Mockito.spy(new MyModule());
Mockito.doReturn("mocked string").when(module).provideString();
MyComponent component = DaggerMyComponent.builder()
.myModule(module)
.build();
app.setComponent(component);
```
I created [this gist](https://gist.github.com/vaughandroid/2ac4aeb28d3e6b008fa4) here to show a full example.
**EDIT**
It turns out you can do this even without a partial mock, like so:
```
MyComponent component = DaggerMyComponent.builder()
.myModule(new MyModule() {
@Override public String provideString() {
return "mocked string";
}
})
.build();
app.setComponent(component);
``` | It seems I've found yet another way and it's working so far.
First, a component interface that is not a component itself:
**MyComponent.java**
```
interface MyComponent {
Foo provideFoo();
}
```
Then we have two different modules: actual one and testing one.
**MyModule.java**
```
@Module
class MyModule {
@Provides
public Foo getFoo() {
return new Foo();
}
}
```
**TestModule.java**
```
@Module
class TestModule {
private Foo foo;
public void setFoo(Foo foo) {
this.foo = foo;
}
@Provides
public Foo getFoo() {
return foo;
}
}
```
And we have two components to use these two modules:
**MyRealComponent.java**
```
@Component(modules=MyModule.class)
interface MyRealComponent extends MyComponent {
Foo provideFoo(); // without this dagger will not do its magic
}
```
**MyTestComponent.java**
```
@Component(modules=TestModule.class)
interface MyTestComponent extends MyComponent {
Foo provideFoo();
}
```
In application we do this:
```
MyComponent component = DaggerMyRealComponent.create();
<...>
Foo foo = component.getFoo();
```
While in test code we use:
```
TestModule testModule = new TestModule();
testModule.setFoo(someMockFoo);
MyComponent component = DaggerMyTestComponent.builder()
.testModule(testModule).build();
<...>
Foo foo = component.getFoo(); // will return someMockFoo
```
The problem is that we have to copy all methods of MyModule into TestModule, but it can be done by having MyModule inside TestModule and use MyModule's methods unless they are directly set from outside. Like this:
**TestModule.java**
```
@Module
class TestModule {
MyModule myModule = new MyModule();
private Foo foo = myModule.getFoo();
public void setFoo(Foo foo) {
this.foo = foo;
}
@Provides
public Foo getFoo() {
return foo;
}
}
``` |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | Probably this is more a workaround that proper support for test module overriding, but it allows to override production modules with test one. The code snippets below shows simple case when you have just one component and one module, but this should work for any scenario. It requires a lot of boilerplate and code repetition so be aware of this. I'm sure there'll be a better way to achieve this in the future.
I've also created a [project with examples for Espresso and Robolectric](https://github.com/tomrozb/dagger-testing). This answer is based on code contained in the project.
The solution requires two things:
* provide additional setter for `@Component`
* test component must extend the production component
Assume we've simple `Application` like below:
```
public class App extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerApp_AppComponent.create();
}
public AppComponent component() {
return mAppComponent;
}
@Singleton
@Component(modules = StringHolderModule.class)
public interface AppComponent {
void inject(MainActivity activity);
}
@Module
public static class StringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder("Release string");
}
}
}
```
We've to add additional method to `App` class. This allows us to replace the production component.
```
/**
* Visible only for testing purposes.
*/
// @VisibleForTesting
public void setTestComponent(AppComponent appComponent) {
mAppComponent = appComponent;
}
```
As you can see the `StringHolder` object contains "Release string" value. This object is injected to the `MainActivity`.
```
public class MainActivity extends ActionBarActivity {
@Inject
StringHolder mStringHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((App) getApplication()).component().inject(this);
}
}
```
In our tests we want to provide `StringHolder` with "Test string". We've to set the test component in `App` class before the `MainActivity` is created - because `StringHolder` is injected in the `onCreate` callback.
In Dagger v2.0.0 components can extend other interfaces. We can leverage this to create our `TestAppComponent` which **extends** `AppComponent`.
```
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
```
Now we're able to define our test modules e.g. `TestStringHolderModule`. The last step is to set the test component using previously added setter method in `App` class. It's important to do this before the activity is created.
```
((App) application).setTestComponent(mTestAppComponent);
```
**Espresso**
For Espresso I've created custom `ActivityTestRule` which allows to swap the component before the activity is created. You can find code for `DaggerActivityTestRule` [here](https://github.com/tomrozb/dagger-testing/blob/master/app/src/androidTest/java/pl/dagger/testing/util/DaggerActivityTestRule.java).
Sample test with Espresso:
```
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
public static final String TEST_STRING = "Test string";
private TestAppComponent mTestAppComponent;
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new DaggerActivityTestRule<>(MainActivity.class, new OnBeforeActivityLaunchedListener<MainActivity>() {
@Override
public void beforeActivityLaunched(@NonNull Application application, @NonNull MainActivity activity) {
mTestAppComponent = DaggerMainActivityEspressoTest_TestAppComponent.create();
((App) application).setTestComponent(mTestAppComponent);
}
});
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
...
// when
onView(...)
// then
onView(...)
.check(...);
}
}
```
**Robolectric**
It's much easier with Robolectric thanks to the `RuntimeEnvironment.application`.
Sample test with Robolectric:
```
@RunWith(RobolectricGradleTestRunner.class)
@Config(emulateSdk = 21, reportSdk = 21, constants = BuildConfig.class)
public class MainActivityRobolectricTest {
public static final String TEST_STRING = "Test string";
@Before
public void setTestComponent() {
AppComponent appComponent = DaggerMainActivityRobolectricTest_TestAppComponent.create();
((App) RuntimeEnvironment.application).setTestComponent(appComponent);
}
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
// when
...
// then
assertThat(...)
}
}
``` | The workaround proposed by @tomrozb is very good and put me on the right track, but my problem with it was that it exposed a `setTestComponent()` method in the PRODUCTION `Application` class. I was able to get this working slightly differently, such that my production application doesn't have to know anything at all about my testing environment.
TL;DR - Extend your Application class with a test application that uses your test component and module. Then create a custom test runner that runs on the test application instead of your production application.
---
EDIT: This method only works for global dependencies (typically marked with `@Singleton`). If your app has components with different scope (e.g. per activity) then you'll either need to create subclasses for each scope, or use @tomrozb's original answer. Thanks to @tomrozb for pointing this out!
---
This example uses the [AndroidJUnitRunner](https://developer.android.com/intl/ko/reference/android/support/test/runner/AndroidJUnitRunner.html) test runner but this could probably be adapted to [Robolectric](http://robolectric.org/custom-test-runner/) and others.
First, my production application. It looks something like this:
```
public class MyApp extends Application {
protected MyComponent component;
public void setComponent() {
component = DaggerMyComponent.builder()
.myModule(new MyModule())
.build();
component.inject(this);
}
public MyComponent getComponent() {
return component;
}
@Override
public void onCreate() {
super.onCreate();
setComponent();
}
}
```
This way, my activities and other class that use `@Inject` simply have to call something like `getApp().getComponent().inject(this);` to inject themselves into the dependency graph.
For completeness, here is my component:
```
@Singleton
@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(MyApp app);
// other injects and getters
}
```
And my module:
```
@Module
public class MyModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// ... other providers
}
```
For the testing environment, extend your test component from your production component. This is the same as in @tomrozb's answer.
```
@Singleton
@Component(modules = {MyTestModule.class})
public interface MyTestComponent extends MyComponent {
// more component methods if necessary
}
```
And the test module can be whatever you want. Presumably you'll handle your mocking and stuff in here (I use Mockito).
```
@Module
public class MyTestModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// Make sure to implement all the same methods here that are in MyModule,
// even though it's not an override.
}
```
So now, the tricky part. Create a test application class that extends from your production application class, and override the `setComponent()` method to set the test component with the test module. Note that this can only work if `MyTestComponent` is a descendant of `MyComponent`.
```
public class MyTestApp extends MyApp {
// Make sure to call this method during setup of your tests!
@Override
public void setComponent() {
component = DaggerMyTestComponent.builder()
.myTestModule(new MyTestModule())
.build();
component.inject(this)
}
}
```
Make sure you call `setComponent()` on the app before you begin your tests to make sure the graph is set up correctly. Something like this:
```
@Before
public void setUp() {
MyTestApp app = (MyTestApp) getInstrumentation().getTargetContext().getApplicationContext();
app.setComponent()
((MyTestComponent) app.getComponent()).inject(this)
}
```
Finally, the last missing piece is to override your TestRunner with a custom test runner. In my project I was using the `AndroidJUnitRunner` but it looks like you can [do the same with Robolectric](http://robolectric.org/custom-test-runner/).
```
public class TestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(@NonNull ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, MyTestApp.class.getName(), context);
}
}
```
You'll also have to update your `testInstrumentationRunner` gradle, like so:
```
testInstrumentationRunner "com.mypackage.TestRunner"
```
And if you're using Android Studio, you'll also have to click Edit Configuration from the run menu and enter the name of your test runner under "Specific instrumentation runner".
And that's it! Hopefully this information helps somebody :) |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | Probably this is more a workaround that proper support for test module overriding, but it allows to override production modules with test one. The code snippets below shows simple case when you have just one component and one module, but this should work for any scenario. It requires a lot of boilerplate and code repetition so be aware of this. I'm sure there'll be a better way to achieve this in the future.
I've also created a [project with examples for Espresso and Robolectric](https://github.com/tomrozb/dagger-testing). This answer is based on code contained in the project.
The solution requires two things:
* provide additional setter for `@Component`
* test component must extend the production component
Assume we've simple `Application` like below:
```
public class App extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerApp_AppComponent.create();
}
public AppComponent component() {
return mAppComponent;
}
@Singleton
@Component(modules = StringHolderModule.class)
public interface AppComponent {
void inject(MainActivity activity);
}
@Module
public static class StringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder("Release string");
}
}
}
```
We've to add additional method to `App` class. This allows us to replace the production component.
```
/**
* Visible only for testing purposes.
*/
// @VisibleForTesting
public void setTestComponent(AppComponent appComponent) {
mAppComponent = appComponent;
}
```
As you can see the `StringHolder` object contains "Release string" value. This object is injected to the `MainActivity`.
```
public class MainActivity extends ActionBarActivity {
@Inject
StringHolder mStringHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((App) getApplication()).component().inject(this);
}
}
```
In our tests we want to provide `StringHolder` with "Test string". We've to set the test component in `App` class before the `MainActivity` is created - because `StringHolder` is injected in the `onCreate` callback.
In Dagger v2.0.0 components can extend other interfaces. We can leverage this to create our `TestAppComponent` which **extends** `AppComponent`.
```
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
```
Now we're able to define our test modules e.g. `TestStringHolderModule`. The last step is to set the test component using previously added setter method in `App` class. It's important to do this before the activity is created.
```
((App) application).setTestComponent(mTestAppComponent);
```
**Espresso**
For Espresso I've created custom `ActivityTestRule` which allows to swap the component before the activity is created. You can find code for `DaggerActivityTestRule` [here](https://github.com/tomrozb/dagger-testing/blob/master/app/src/androidTest/java/pl/dagger/testing/util/DaggerActivityTestRule.java).
Sample test with Espresso:
```
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
public static final String TEST_STRING = "Test string";
private TestAppComponent mTestAppComponent;
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new DaggerActivityTestRule<>(MainActivity.class, new OnBeforeActivityLaunchedListener<MainActivity>() {
@Override
public void beforeActivityLaunched(@NonNull Application application, @NonNull MainActivity activity) {
mTestAppComponent = DaggerMainActivityEspressoTest_TestAppComponent.create();
((App) application).setTestComponent(mTestAppComponent);
}
});
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
...
// when
onView(...)
// then
onView(...)
.check(...);
}
}
```
**Robolectric**
It's much easier with Robolectric thanks to the `RuntimeEnvironment.application`.
Sample test with Robolectric:
```
@RunWith(RobolectricGradleTestRunner.class)
@Config(emulateSdk = 21, reportSdk = 21, constants = BuildConfig.class)
public class MainActivityRobolectricTest {
public static final String TEST_STRING = "Test string";
@Before
public void setTestComponent() {
AppComponent appComponent = DaggerMainActivityRobolectricTest_TestAppComponent.create();
((App) RuntimeEnvironment.application).setTestComponent(appComponent);
}
@Component(modules = TestStringHolderModule.class)
interface TestAppComponent extends AppComponent {
}
@Module
static class TestStringHolderModule {
@Provides
StringHolder provideString() {
return new StringHolder(TEST_STRING);
}
}
@Test
public void checkSomething() {
// given
MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
// when
...
// then
assertThat(...)
}
}
``` | I have solution for **Roboletric 3.+**.
I have MainActivity which i want to test without injection on create:
```
public class MainActivity extends BaseActivity{
@Inject
public Configuration configuration;
@Inject
public AppStateService appStateService;
@Inject
public LoginService loginService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.processIntent(getIntent()); // this is point where pass info from test
super.onCreate(savedInstanceState)
...
}
...
}
```
Next my BaseActivty:
```
public class BaseActivity extends AppCompatActivity {
protected Logger mLog;
protected boolean isTestingSession = false; //info about test session
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (!isTestingSession) { // check if it is in test session, if not enable injectig
AndroidInjection.inject(this);
}
super.onCreate(savedInstanceState);
}
// method for receive intent from child and scaning if has item TESTING with true
protected void processIntent(Intent intent) {
if (intent != null && intent.getExtras() != null) {
isTestingSession = intent.getExtras().getBoolean("TESTING", false);
}
}
```
finally my testclass:
```
@Before
public void setUp() throws Exception {
...
// init mocks...
loginServiceMock = mock(LoginService.class);
locServiceMock = mock(LocationClientService.class);
fakeConfiguration = new ConfigurationUtils(new ConfigurationXmlParser());
fakeConfiguration.save(FAKE_XML_CONFIGURATION);
appStateService = new AppStateService(fakeConfiguration, locServiceMock, RuntimeEnvironment.application);
// prepare activity
Intent intent = new Intent(RuntimeEnvironment.application, MainActivity.class);
intent.putExtra("TESTING", true);
ActivityController<MainActivity> activityController = Robolectric.buildActivity(MainActivity.class, intent); // place to put bundle with extras
// get the activity instance
mainActivity = activityController.get();
// init fields which should be injected
mainActivity.appStateService = appStateService;
mainActivity.loginService = loginServiceMock;
mainActivity.configuration = fakeConfiguration;
// and whoala
// now setup your activity after mock injection
activityController.setup();
// get views etc..
actionButton = mainActivity.findViewById(R.id.mainButtonAction);
NavigationView navigationView = mainActivity.findViewById(R.id.nav_view);
....
}
``` |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | The workaround proposed by @tomrozb is very good and put me on the right track, but my problem with it was that it exposed a `setTestComponent()` method in the PRODUCTION `Application` class. I was able to get this working slightly differently, such that my production application doesn't have to know anything at all about my testing environment.
TL;DR - Extend your Application class with a test application that uses your test component and module. Then create a custom test runner that runs on the test application instead of your production application.
---
EDIT: This method only works for global dependencies (typically marked with `@Singleton`). If your app has components with different scope (e.g. per activity) then you'll either need to create subclasses for each scope, or use @tomrozb's original answer. Thanks to @tomrozb for pointing this out!
---
This example uses the [AndroidJUnitRunner](https://developer.android.com/intl/ko/reference/android/support/test/runner/AndroidJUnitRunner.html) test runner but this could probably be adapted to [Robolectric](http://robolectric.org/custom-test-runner/) and others.
First, my production application. It looks something like this:
```
public class MyApp extends Application {
protected MyComponent component;
public void setComponent() {
component = DaggerMyComponent.builder()
.myModule(new MyModule())
.build();
component.inject(this);
}
public MyComponent getComponent() {
return component;
}
@Override
public void onCreate() {
super.onCreate();
setComponent();
}
}
```
This way, my activities and other class that use `@Inject` simply have to call something like `getApp().getComponent().inject(this);` to inject themselves into the dependency graph.
For completeness, here is my component:
```
@Singleton
@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(MyApp app);
// other injects and getters
}
```
And my module:
```
@Module
public class MyModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// ... other providers
}
```
For the testing environment, extend your test component from your production component. This is the same as in @tomrozb's answer.
```
@Singleton
@Component(modules = {MyTestModule.class})
public interface MyTestComponent extends MyComponent {
// more component methods if necessary
}
```
And the test module can be whatever you want. Presumably you'll handle your mocking and stuff in here (I use Mockito).
```
@Module
public class MyTestModule {
// EDIT: This solution only works for global dependencies
@Provides @Singleton
public MyClass provideMyClass() { ... }
// Make sure to implement all the same methods here that are in MyModule,
// even though it's not an override.
}
```
So now, the tricky part. Create a test application class that extends from your production application class, and override the `setComponent()` method to set the test component with the test module. Note that this can only work if `MyTestComponent` is a descendant of `MyComponent`.
```
public class MyTestApp extends MyApp {
// Make sure to call this method during setup of your tests!
@Override
public void setComponent() {
component = DaggerMyTestComponent.builder()
.myTestModule(new MyTestModule())
.build();
component.inject(this)
}
}
```
Make sure you call `setComponent()` on the app before you begin your tests to make sure the graph is set up correctly. Something like this:
```
@Before
public void setUp() {
MyTestApp app = (MyTestApp) getInstrumentation().getTargetContext().getApplicationContext();
app.setComponent()
((MyTestComponent) app.getComponent()).inject(this)
}
```
Finally, the last missing piece is to override your TestRunner with a custom test runner. In my project I was using the `AndroidJUnitRunner` but it looks like you can [do the same with Robolectric](http://robolectric.org/custom-test-runner/).
```
public class TestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(@NonNull ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, MyTestApp.class.getName(), context);
}
}
```
You'll also have to update your `testInstrumentationRunner` gradle, like so:
```
testInstrumentationRunner "com.mypackage.TestRunner"
```
And if you're using Android Studio, you'll also have to click Edit Configuration from the run menu and enter the name of your test runner under "Specific instrumentation runner".
And that's it! Hopefully this information helps somebody :) | For me the following works best.
That's not a test-friendly solution but I use it a lot to mock some APIs while developing whenever backend is not ready yet but I need to implement UI in advance.
Dagger (2.29.1) won't allow to override providing methods in modules with:
```
Binding methods may not be overridden in modules
```
However with some extra boilerplate you could cheat it:
```kotlin
@Module
open class NetworkServicesModule {
/**
* Provide a mock instead
*/
protected open fun doProvideFlightService(context: Context, retrofit: Retrofit): FlightService {
return retrofit.create(FlightService::class.java)
}
@Provides
@Singleton
fun provideFlightService(context: Context, retrofit: Retrofit): FlightService {
return doProvideFlightService(context, retrofit)
}
}
@Module
class MockNetworkServiceModule() : NetworkServicesModule() {
/**
* Need this to be able to mock a service in a production app
*/
override fun doProvideFlightService(context: Context, retrofit: Retrofit): FlightService {
return MockFlightService(context, super.doProvideFlightService(context, retrofit))
}
```
Given you have a component defined like that:
```kotlin
@Component(
modules = [
NetworkServicesModule::class,
]
)
interface BaseComponent {
fun provideFlightService(): FlightService
@Component.Builder
interface Builder {
fun networkServicesModule(networkServicesModule: NetworkServicesModule): Builder
fun build(): BaseComponent
}
}
```
You could have some network module provider which you choose depending on your app variant/flavor or the way you like it better:
```kotlin
/**
* Provides mock networking services module
*/
interface NetworkServicesModuleProvider {
/**
* Provides networking service module
*/
fun get() : NetworkServicesModule = NetworkServiceModule()
}
/**
* Provides mock networking services module
*/
object MockNetworkServicesModuleProvider : NetworkServicesModuleProvider {
/**
* Provides networking service module
*/
override fun get() : NetworkServicesModule = MockNetworkServiceModule()
}
```
Then when it's time to build your component call:
```kotlin
val networkServicesProvider: NetworkServicesModuleProvider = ...
DaggerBaseComponent.builder()
.networkServicesModule(networkServicesProvider.get())
.build()
``` |
26,939,349 | I have to draw a cone with a given height and radius at a specific co-ordinate.
MATLAB has the function `cylinder(r)`, but it draws only a unit cylinder whereas I need it to be of a specific height.
None of the other links specify how to draw a cone of height 'h'. | 2014/11/14 | [
"https://Stackoverflow.com/questions/26939349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750013/"
] | As @EpicPandaForce rightly says, you can't extend Modules. However, I came up with a sneaky workaround for this which I think avoids a lot of the boilerplate which the other examples suffer from.
The trick to 'extending' a Module is to create a partial mock, and mock out the provider methods which you want to override.
Using [Mockito](http://mockito.org/):
```
MyModule module = Mockito.spy(new MyModule());
Mockito.doReturn("mocked string").when(module).provideString();
MyComponent component = DaggerMyComponent.builder()
.myModule(module)
.build();
app.setComponent(component);
```
I created [this gist](https://gist.github.com/vaughandroid/2ac4aeb28d3e6b008fa4) here to show a full example.
**EDIT**
It turns out you can do this even without a partial mock, like so:
```
MyComponent component = DaggerMyComponent.builder()
.myModule(new MyModule() {
@Override public String provideString() {
return "mocked string";
}
})
.build();
app.setComponent(component);
``` | For me the following works best.
That's not a test-friendly solution but I use it a lot to mock some APIs while developing whenever backend is not ready yet but I need to implement UI in advance.
Dagger (2.29.1) won't allow to override providing methods in modules with:
```
Binding methods may not be overridden in modules
```
However with some extra boilerplate you could cheat it:
```kotlin
@Module
open class NetworkServicesModule {
/**
* Provide a mock instead
*/
protected open fun doProvideFlightService(context: Context, retrofit: Retrofit): FlightService {
return retrofit.create(FlightService::class.java)
}
@Provides
@Singleton
fun provideFlightService(context: Context, retrofit: Retrofit): FlightService {
return doProvideFlightService(context, retrofit)
}
}
@Module
class MockNetworkServiceModule() : NetworkServicesModule() {
/**
* Need this to be able to mock a service in a production app
*/
override fun doProvideFlightService(context: Context, retrofit: Retrofit): FlightService {
return MockFlightService(context, super.doProvideFlightService(context, retrofit))
}
```
Given you have a component defined like that:
```kotlin
@Component(
modules = [
NetworkServicesModule::class,
]
)
interface BaseComponent {
fun provideFlightService(): FlightService
@Component.Builder
interface Builder {
fun networkServicesModule(networkServicesModule: NetworkServicesModule): Builder
fun build(): BaseComponent
}
}
```
You could have some network module provider which you choose depending on your app variant/flavor or the way you like it better:
```kotlin
/**
* Provides mock networking services module
*/
interface NetworkServicesModuleProvider {
/**
* Provides networking service module
*/
fun get() : NetworkServicesModule = NetworkServiceModule()
}
/**
* Provides mock networking services module
*/
object MockNetworkServicesModuleProvider : NetworkServicesModuleProvider {
/**
* Provides networking service module
*/
override fun get() : NetworkServicesModule = MockNetworkServiceModule()
}
```
Then when it's time to build your component call:
```kotlin
val networkServicesProvider: NetworkServicesModuleProvider = ...
DaggerBaseComponent.builder()
.networkServicesModule(networkServicesProvider.get())
.build()
``` |
235,838 | In about 50 minutes from now (it's 11:06 PM) my machine will slow down. It does this every night at the exact same time.
Is OSX indexing or what is going on and what can I do about it? | 2011/01/20 | [
"https://superuser.com/questions/235838",
"https://superuser.com",
"https://superuser.com/users/63997/"
] | Your processor has [HyperThreading](http://en.wikipedia.org/wiki/HyperThreading), giving it two *virtual/logical* cores per *physical* core. | Sounds like your processor is hyper threaded which means each core will have two threads, Windows will see these threads (logical cores) as additional cores. |
235,838 | In about 50 minutes from now (it's 11:06 PM) my machine will slow down. It does this every night at the exact same time.
Is OSX indexing or what is going on and what can I do about it? | 2011/01/20 | [
"https://superuser.com/questions/235838",
"https://superuser.com",
"https://superuser.com/users/63997/"
] | Your processor has [HyperThreading](http://en.wikipedia.org/wiki/HyperThreading), giving it two *virtual/logical* cores per *physical* core. | Looks like the applications are detecting what is called Hyperthreading. This feature effectively allows a single core to behave as two cores. See the wikipedia article if you want to know more. <http://en.wikipedia.org/wiki/Hyper-threading> |
235,838 | In about 50 minutes from now (it's 11:06 PM) my machine will slow down. It does this every night at the exact same time.
Is OSX indexing or what is going on and what can I do about it? | 2011/01/20 | [
"https://superuser.com/questions/235838",
"https://superuser.com",
"https://superuser.com/users/63997/"
] | Your processor has [HyperThreading](http://en.wikipedia.org/wiki/HyperThreading), giving it two *virtual/logical* cores per *physical* core. | This is most probably because the i7 870 has hyperthreading (~2 hardware threads by core), my Core i5 760 shows only 4.
[For each processor core that is physically present, the operating system addresses two virtual processors](http://en.wikipedia.org/wiki/Hyper-threading) |
235,838 | In about 50 minutes from now (it's 11:06 PM) my machine will slow down. It does this every night at the exact same time.
Is OSX indexing or what is going on and what can I do about it? | 2011/01/20 | [
"https://superuser.com/questions/235838",
"https://superuser.com",
"https://superuser.com/users/63997/"
] | Sounds like your processor is hyper threaded which means each core will have two threads, Windows will see these threads (logical cores) as additional cores. | Looks like the applications are detecting what is called Hyperthreading. This feature effectively allows a single core to behave as two cores. See the wikipedia article if you want to know more. <http://en.wikipedia.org/wiki/Hyper-threading> |
235,838 | In about 50 minutes from now (it's 11:06 PM) my machine will slow down. It does this every night at the exact same time.
Is OSX indexing or what is going on and what can I do about it? | 2011/01/20 | [
"https://superuser.com/questions/235838",
"https://superuser.com",
"https://superuser.com/users/63997/"
] | This is most probably because the i7 870 has hyperthreading (~2 hardware threads by core), my Core i5 760 shows only 4.
[For each processor core that is physically present, the operating system addresses two virtual processors](http://en.wikipedia.org/wiki/Hyper-threading) | Looks like the applications are detecting what is called Hyperthreading. This feature effectively allows a single core to behave as two cores. See the wikipedia article if you want to know more. <http://en.wikipedia.org/wiki/Hyper-threading> |
72,661,424 | example of a valley:
9,6,5,4,10,13,40,55,68
The list must be strictly decreasing until one point and then after the list must be strictly increasing. Then it is considered as a valley.
constraints:
Use two pointer approach
Guys, I have come up with this code:
---
```
def isValley(n,j,n1):
i = 0
res = False
while(i<j):
if (n[i]>n[i+1]) and (n[j]>n[j-1]):
n1.append(1)
else:
n1.append(0)
res = n1.count(n1[0]) == len(n1)
i+=1
j-=1
print(n1)
if res:
if(n1[0] == 1):
print("Valley")
else:
print("Not a valley")
else:
print("Not a valley")
n = list(map(int,input("Enter the numbers : ").split()))
n1 = []
j = len(n)-1
print(n)
isValley(n,j,n1)
```
my code is working only when the no of elements on the left side of the element is equal to
the number of elements on the right side of the element.
please correct this and come up with a code that even satisfies irrespective of the number
of elements left of the element and right of the element.
hint:
I think i have issue while making comparisions
(Use Two pointer Approach only)
Please help me out guys | 2022/06/17 | [
"https://Stackoverflow.com/questions/72661424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15927270/"
] | I think you can just iterate from left to right (and from right to left), while the elements are strictly decreasing (increasing). Then it's a valley if and only if the pointers end up at the same location
```
def isValley(array):
N = len(array)
front_i = 0
back_i = N-1
while front_i < N-1 and array[front_i] > array[front_i + 1]:
front_i += 1
while back_i > 0 and array[back_i] > array[back_i - 1]:
back_i -= 1
is_valley = (front_i == back_i)
return is_valley
print(isValley([9,6,5,4,10,13,40,55,68])) # prints True
``` | You can check that there is a strictly negative gradient followed by a strictly positive gradient. One way of doing this (using numpy) is:
```py
import numpy as np
def isValley(array):
d = np.diff(array)
return (
np.array_equal(
np.concatenate((np.argwhere(d < 0), np.argwhere(d > 0))).flatten(),
np.arange(len(array) - 1)
)
)
``` |
51,844,508 | I am trying to aggregate a `GroupedData` object into a `Row` with the best attributes (not `None` or highest `timestamp`) for a `Dataframe` like:
```
╔═══════╦═══════════╦════════╦════════╦════════╗
║ group ║ timestamp ║ value1 ║ value2 ║ value3 ║
╠═══════╬═══════════╬════════╬════════╬════════╣
║ a ║ 111 ║ None ║ None ║ None ║
║ a ║ 222 ║ a ║ None ║ None ║
║ a ║ 333 ║ b ║ 1 ║ 1.1 ║
║ a ║ 444 ║ None ║ None ║ 2.2 ║
║ b ║ 111 ║ c ║ None ║ 3.3 ║
╚═══════╩═══════════╩════════╩════════╩════════╝
```
I want to have a result `Dataframe` like:
```
╔═══════╦═══════════╦════════╦════════╦════════╗
║ group ║ timestamp ║ value1 ║ value2 ║ value3 ║
╠═══════╬═══════════╬════════╬════════╬════════╣
║ a ║ 444 ║ b ║ 1 ║ 2.2 ║
║ b ║ 111 ║ c ║ None ║ 3.3 ║
╚═══════╩═══════════╩════════╩════════╩════════╝
```
Ideally I want to create a different logic to aggregate every column. For example `min` for `timestamp` but `max` for `value3`.
Is this possible in `Dataframe`s?
Thanks, | 2018/08/14 | [
"https://Stackoverflow.com/questions/51844508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1517843/"
] | `SparkSQL` will actually do exactly what you want it to do and ignore null values when aggregating a column. As an example, let's consider the following dataframe:
```
df = sc.parallelize([("a", 1, None), ("b", None, 5), ("a", 2, None), ("b", 0, 7)]).toDF(["A", "B", "C"])
```
that looks like this:
```
+---+----+----+
| A| B| C|
+---+----+----+
| a| 1|null|
| b|null| 5|
| a| 2|null|
| b| 0| 7|
+---+----+----+
```
You can aggregate using different functions like this:
```
import pyspark.sql.functions as F
df.groupBy("A").agg(F.min(F.col("B")), F.max(F.col("C") ))
```
and get what you expect (ignored null values expect when this is the only value, and different aggregator functions):
```
+---+------+------+
| A|min(B)|max(C)|
+---+------+------+
| b| 0| 7|
| a| 1| null|
+---+------+------+
``` | You can do like below to achieve your result
```
# create data frame like below to match your grouped data frame
df = sqlContext.createDataFrame([('a', 111, None, None, None), ('a', 222, 'a', None, None), ('a', 333, 'b', 1, 1.1), ('a', 444, None, None, 2.2), ('b', 111, 'c', None, 3.3)], ('group', 'timestamp', 'value1', 'value2', 'value3'))
# import necessary functions
import pyspark.sql.functions as f
# apply group by and agg functions on the data frame
df1 = df.groupBy('group').agg(f.min('timestamp').alias('timestamp'), f.max('value1').alias('value1'), f.max('value2').alias('value2'), f.max('value3').alias('value3'))
# show the result data frame
df1.show()
# +-----+---------+------+------+------+
# |group|timestamp|value1|value2|value3|
# +-----+---------+------+------+------+
# | a| 111| b| 1| 2.2|
# | b| 111| c| null| 3.3|
# +-----+---------+------+------+------+
``` |
45,570,827 | I am trying to run a script using Java and ProcessBuilder. When I try to run, I receive the following message: error=2, No such file or directory.
I dont know what I am doing wrong but here is my code (ps: I tried to execute just the script without arguments and the error is the same:
```
String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
ProcessBuilder p = new ProcessBuilder(command);
try {
// create a process builder to send a command and a argument
Process p2 = p.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
log.info("Output of running " + command + " is: ");
System.out.println("Output of running " + command + " is: ");
while ((line = br.readLine()) != null) {
log.info(line);
}
}
``` | 2017/08/08 | [
"https://Stackoverflow.com/questions/45570827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7478594/"
] | Try replacing
```
String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
```
with
```
String[] command = {"/teste/teste_back/script.sh", argument1, argument};
```
Refer [ProcessBuilder](https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html) for more information.
>
> ProcessBuilder(String... command)
>
>
> Constructs a process builder with the specified operating system
> program and arguments.
>
>
> | Unless your script.sh has a comma in its name, that is the mistake:
```
String[] command = {"/teste/teste_back/script.sh" , argument1, argument};
``` |
45,570,827 | I am trying to run a script using Java and ProcessBuilder. When I try to run, I receive the following message: error=2, No such file or directory.
I dont know what I am doing wrong but here is my code (ps: I tried to execute just the script without arguments and the error is the same:
```
String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
ProcessBuilder p = new ProcessBuilder(command);
try {
// create a process builder to send a command and a argument
Process p2 = p.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
log.info("Output of running " + command + " is: ");
System.out.println("Output of running " + command + " is: ");
while ((line = br.readLine()) != null) {
log.info(line);
}
}
``` | 2017/08/08 | [
"https://Stackoverflow.com/questions/45570827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7478594/"
] | Try replacing
```
String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
```
with
```
String[] command = {"/teste/teste_back/script.sh", argument1, argument};
```
Refer [ProcessBuilder](https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html) for more information.
>
> ProcessBuilder(String... command)
>
>
> Constructs a process builder with the specified operating system
> program and arguments.
>
>
> | You can define a method with ProcessBuilder.
```
public static Map execCommand(String... str) {
Map<Integer, String> map = new HashMap<>();
ProcessBuilder pb = new ProcessBuilder(str);
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
if (process != null) {
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
}
String line;
StringBuilder stringBuilder = new StringBuilder();
try {
if (reader != null) {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (process != null) {
process.waitFor();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (process != null) {
map.put(0, String.valueOf(process.exitValue()));
}
try {
map.put(1, stringBuilder.toString());
} catch (StringIndexOutOfBoundsException e) {
if (stringBuilder.toString().length() == 0) {
return map;
}
}
return map;
}
```
You can call the function to execute shell command or script
```
String cmds = "ifconfig";
String[] callCmd = {"/bin/bash", "-c", cmds};
System.out.println("exit code:\n" + execCommand(callCmd).get(0).toString());
System.out.println();
System.out.println("command result:\n" + execCommand(callCmd).get(1).toString());
``` |
267 | I just had an [old question of mine](https://bioinformatics.stackexchange.com/q/3151/298) closed by a moderator with the following comment:
>
> I’m voting to close this question because it was asked a long time ago, and it is likely that an answer is no longer useful to the person who asked the question, or to the general bioinformatics community. Please feel free to edit the question and update it if you feel it's important to get an answer. – 7 hours ago
>
>
>
I then checked the mod's profile and saw that they've actually closed *a total of nine questions with the same comment*! I'm sure the mod means well, but this is a problem. First, a question's age is irrelevant, questions can be answered at any time and on SE sites we answer for the broader community not for the OP alone. So even if the OP has abandoned the question, that is no reason to assume that nobody else would benefit from an answer. So why would you want to forcibly bar a question from ever being answered?
Perhaps more importantly, there is no rule that says old questions should be closed, so I don't understand by what authority someone would presume to make this choice. Moderators have the ability to single-handedly close questions, but that should only be used for things that are blatantly off topic. Otherwise, it feels like the moderator is just imposing their own preferences and getting to choose what questions stay and what questions are closed. Again, I am sure the mod meant well, but this feels like crossing a very important line.
So, please reopen ***all*** of the questions you've closed just for being old. That is not how these sites work, you didn't come to meta to see if this is what the commnunity wants and, in my own opinion, closing such questions actively harms the site for no benefit whatsoever. The most important thing though is that closing such questions is imposing one person's choice on the rest of the community with no discussion or consultation. Please don't do this. | 2021/07/04 | [
"https://bioinformatics.meta.stackexchange.com/questions/267",
"https://bioinformatics.meta.stackexchange.com",
"https://bioinformatics.meta.stackexchange.com/users/298/"
] | I agree. We should not assume that all old and non-answered questions are not interesting or unnecessary.
However, I also do see that bioinformatics is a fast evolving discipline and some of the unanswered questions are very quickly outdated. I do think it would be handy to have "question is outdated" closing reason. In [this example](https://bioinformatics.stackexchange.com/questions/2923/how-to-submit-a-canu-job-on-lsf-high-performance-computing-cluster-farm), the OP must have talked about millions of Canu versions ago, it might be still a valid question, but I would not be surprised if Canu would have a completely different job distrbution mechanism. So, I would say in those cases, it would be handy to at least add a version of software people are asing about (but that would be probs the best specified very early on when talking about bugs).
Anyway, my whole point is - there is a fine line between old and outdated and we should try our best to never cross it. | Bioinformatics Stack Exchange has an existing canned site-specific close reason:
>
> Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers.
>
>
>
I used this as a base, and added additional clarification to make it more obvious that it's fine to reopen a question if it seems useful (*especially* if the question can be improved / updated).
<https://bioinformatics.stackexchange.com/help/reopen-questions>
These questions were not closed *just* because they were old; they were closed because they had no answers, and there had been no question activity for a long time. In most cases, there were additional close reasons; I just thought that the above was the most appropriate. If you notice that your question is not getting answered, try here for some inspiration:
<https://bioinformatics.stackexchange.com/help/no-one-answers>
StackExchange encourages users to keep questions and answers current, in particular by bumping old posts that have no accepted answers. This means that old questions, even if inactive, will still get exposure in the new queue from time to time. Where this exposure doesn't encourage activity, it's an indication to me that the question is not sufficiently relevant to this community. I'm not interested in reopening these unanswered questions (which, to clarify, haven't been touched in *years*) unless they are modified to update and/or improve the question (or voted on to reopen by multiple users).
My bigger concern is in *new* questions that are rapidly closed, especially when they are created by new users to the site (e.g. [here](https://bioinformatics.stackexchange.com/questions/16175/addpercellqc-doesnt-seem-to-calculate-pct-and-logcount-values). I don't like this practise; it leads to anxiety in new users - what's the point of posting if my question won't be good enough for the rapid closers?
Update: After discussion, I have decided to no longer use this canned close reason, as its interpretation is ambiguous. Where questions remain that I closed with this reason (i.e. have not been edited or had a few votes for reopening), I have altered my close reason to one of the non-site-specific reasons and added additional clarification. |
62,872,032 | Getting (java.net.MalformedURLException) unknown protocol: jrt error, with suggestion to rebuild the project, in Intellij.
Stack trace -
```
Error:Internal error: (java.net.MalformedURLException) unknown protocol: jrt
java.net.MalformedURLException: unknown protocol: jrt
at java.net.URL.<init>(URL.java:421)
at java.net.URL.<init>(URL.java:310)
at java.net.URL.<init>(URL.java:333)
at com.intellij.compiler.instrumentation.InstrumentationClassFinder.createJDKPlatformUrl(InstrumentationClassFinder.java:61)
at org.jetbrains.jps.incremental.instrumentation.ClassProcessingBuilder.createInstrumentationClassFinder(ClassProcessingBuilder.java:125)
at org.jetbrains.jps.incremental.instrumentation.ClassProcessingBuilder.build(ClassProcessingBuilder.java:93)
at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1246)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:923)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:995)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:886)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:719)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:371)
at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:308)
at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:138)
at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:235)
at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Please perform full project rebuild (Build | Rebuild Project)
```
Building full project via mvn is failing due to other artifact issue.
Specs -
```
java version "1.8.0_201"
IntelliJ IDEA 2017.3.7 (Ultimate Edition)
``` | 2020/07/13 | [
"https://Stackoverflow.com/questions/62872032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5488173/"
] | If I understood the question correctly. this might be what you are looking for
```js
var searchIDs = [
{ "id":"6001", "other" : "..." },
{ "id":"6002", "other" : "..."}
]
var list = [
{"id":"9666", "status":"active"},
{"id":"9667", "status":"none"},
{"id":"9999", "status":"none"},
{"id":"9668", "status":"none"},
{"id":"9669", "status":"active"},
{"id":"6001", "status":"none"},
{"id":"6002", "status":"none"},
{"id":"6003", "status":"none"},
{"id":"6004", "status":"none"},
{"id":"6005", "status":"active"},
{"id":"6006", "status":"none"},
{"id":"6007", "status":"none"},
{"id":"6008", "status":"none"},
{"id":"6009", "status":"none"}
]
// This line creates a new array with only the id's in it
const ids = searchIDs.map(line => line.id)
// We will map this array
// if the this line id appears in the ids list we can set the status to active. otherwise to none
var newList = list.map(line => {
// you could also use .includes
line.status = ids.indexOf(line.id) > -1 ? 'active' : 'none';
return line;
})
console.log(newList)
``` | I would suggest searching for the items in the first list (searchIDs) in an [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) call on the second list (list), we're essentially checking if each member of list is also a member of searchIDs.
This might not be super-efficient if searchIDs is very large, so one could create a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and check for membership using [Set.has](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has).
```js
var searchIDs = [{ "id":"6001", "other" : "..." },
{ "id":"6002", "other" : "..."}]
var list = [
{"id":"9666", "status":"active"},
{"id":"9667", "status":"none"},
{"id":"9999", "status":"none"},
{"id":"9668", "status":"none"},
{"id":"9669", "status":"active"},
{"id":"6001", "status":"none"},
{"id":"6002", "status":"none"},
{"id":"6003", "status":"none"},
{"id":"6004", "status":"none"},
{"id":"6005", "status":"active"},
{"id":"6006", "status":"none"},
{"id":"6007", "status":"none"},
{"id":"6008", "status":"none"},
{"id":"6009", "status":"none"}
]
list = list.map(r => {
return { id: r.id, status: searchIDs.find(s => s.id === r.id) ? "active": "none" };
})
console.log(list);
``` |
62,872,032 | Getting (java.net.MalformedURLException) unknown protocol: jrt error, with suggestion to rebuild the project, in Intellij.
Stack trace -
```
Error:Internal error: (java.net.MalformedURLException) unknown protocol: jrt
java.net.MalformedURLException: unknown protocol: jrt
at java.net.URL.<init>(URL.java:421)
at java.net.URL.<init>(URL.java:310)
at java.net.URL.<init>(URL.java:333)
at com.intellij.compiler.instrumentation.InstrumentationClassFinder.createJDKPlatformUrl(InstrumentationClassFinder.java:61)
at org.jetbrains.jps.incremental.instrumentation.ClassProcessingBuilder.createInstrumentationClassFinder(ClassProcessingBuilder.java:125)
at org.jetbrains.jps.incremental.instrumentation.ClassProcessingBuilder.build(ClassProcessingBuilder.java:93)
at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1246)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:923)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:995)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:886)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:719)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:371)
at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:308)
at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:138)
at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:235)
at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Please perform full project rebuild (Build | Rebuild Project)
```
Building full project via mvn is failing due to other artifact issue.
Specs -
```
java version "1.8.0_201"
IntelliJ IDEA 2017.3.7 (Ultimate Edition)
``` | 2020/07/13 | [
"https://Stackoverflow.com/questions/62872032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5488173/"
] | If I understood the question correctly. this might be what you are looking for
```js
var searchIDs = [
{ "id":"6001", "other" : "..." },
{ "id":"6002", "other" : "..."}
]
var list = [
{"id":"9666", "status":"active"},
{"id":"9667", "status":"none"},
{"id":"9999", "status":"none"},
{"id":"9668", "status":"none"},
{"id":"9669", "status":"active"},
{"id":"6001", "status":"none"},
{"id":"6002", "status":"none"},
{"id":"6003", "status":"none"},
{"id":"6004", "status":"none"},
{"id":"6005", "status":"active"},
{"id":"6006", "status":"none"},
{"id":"6007", "status":"none"},
{"id":"6008", "status":"none"},
{"id":"6009", "status":"none"}
]
// This line creates a new array with only the id's in it
const ids = searchIDs.map(line => line.id)
// We will map this array
// if the this line id appears in the ids list we can set the status to active. otherwise to none
var newList = list.map(line => {
// you could also use .includes
line.status = ids.indexOf(line.id) > -1 ? 'active' : 'none';
return line;
})
console.log(newList)
``` | This works.
```
var searchIDs = [
{ "id":"6001", "other" : "..." },
{ "id":"6002", "other" : "..."}
]
var list = [
{"id":"9666", "status":"active"},
{"id":"9667", "status":"none"},
{"id":"9999", "status":"none"},
{"id":"9668", "status":"none"},
{"id":"9669", "status":"active"},
{"id":"6001", "status":"none"},
{"id":"6002", "status":"none"},
{"id":"6003", "status":"none"},
{"id":"6004", "status":"none"},
{"id":"6005", "status":"active"},
{"id":"6006", "status":"none"},
{"id":"6007", "status":"none"},
{"id":"6008", "status":"none"},
{"id":"6009", "status":"none"}
]
let resArr = list.map(function(item){
let obj = item;
if(searchIDs.find(x => x.id == item.id)){
obj.status = "active";
}else{
obj.status = "none";
}
return obj;
});
console.log(resArr);
``` |
62,872,032 | Getting (java.net.MalformedURLException) unknown protocol: jrt error, with suggestion to rebuild the project, in Intellij.
Stack trace -
```
Error:Internal error: (java.net.MalformedURLException) unknown protocol: jrt
java.net.MalformedURLException: unknown protocol: jrt
at java.net.URL.<init>(URL.java:421)
at java.net.URL.<init>(URL.java:310)
at java.net.URL.<init>(URL.java:333)
at com.intellij.compiler.instrumentation.InstrumentationClassFinder.createJDKPlatformUrl(InstrumentationClassFinder.java:61)
at org.jetbrains.jps.incremental.instrumentation.ClassProcessingBuilder.createInstrumentationClassFinder(ClassProcessingBuilder.java:125)
at org.jetbrains.jps.incremental.instrumentation.ClassProcessingBuilder.build(ClassProcessingBuilder.java:93)
at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1246)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:923)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:995)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:886)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:719)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:371)
at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:308)
at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:138)
at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:235)
at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Please perform full project rebuild (Build | Rebuild Project)
```
Building full project via mvn is failing due to other artifact issue.
Specs -
```
java version "1.8.0_201"
IntelliJ IDEA 2017.3.7 (Ultimate Edition)
``` | 2020/07/13 | [
"https://Stackoverflow.com/questions/62872032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5488173/"
] | If I understood the question correctly. this might be what you are looking for
```js
var searchIDs = [
{ "id":"6001", "other" : "..." },
{ "id":"6002", "other" : "..."}
]
var list = [
{"id":"9666", "status":"active"},
{"id":"9667", "status":"none"},
{"id":"9999", "status":"none"},
{"id":"9668", "status":"none"},
{"id":"9669", "status":"active"},
{"id":"6001", "status":"none"},
{"id":"6002", "status":"none"},
{"id":"6003", "status":"none"},
{"id":"6004", "status":"none"},
{"id":"6005", "status":"active"},
{"id":"6006", "status":"none"},
{"id":"6007", "status":"none"},
{"id":"6008", "status":"none"},
{"id":"6009", "status":"none"}
]
// This line creates a new array with only the id's in it
const ids = searchIDs.map(line => line.id)
// We will map this array
// if the this line id appears in the ids list we can set the status to active. otherwise to none
var newList = list.map(line => {
// you could also use .includes
line.status = ids.indexOf(line.id) > -1 ? 'active' : 'none';
return line;
})
console.log(newList)
``` | Posting with a very basic approach as below, hope it helps you.
```
var searchIDs = [{ "id":"6001", "other" : "..." },
{ "id":"6002", "other" : "..."}]
var list = [
{"id":"9666", "status":"active"},
{"id":"9667", "status":"none"},
{"id":"9999", "status":"none"},
{"id":"9668", "status":"none"},
{"id":"9669", "status":"active"},
{"id":"6001", "status":"none"},
{"id":"6002", "status":"none"},
{"id":"6003", "status":"none"},
{"id":"6004", "status":"none"},
{"id":"6005", "status":"active"},
{"id":"6006", "status":"none"},
{"id":"6007", "status":"none"},
{"id":"6008", "status":"none"},
{"id":"6009", "status":"none"}
]
let newsearchIds = [];
for (var i = 0 ; i < searchIDs.length ; i ++) {
for(let key in searchIDs[i]){
newsearchIds.push(searchIDs[i][key]);
}
}
for (var i = 0 ; i < list.length ; i ++) {
for (var j = 0 ; j < newsearchIds.length ; j ++) {
if(list[i].id === newsearchIds[j]){
list[i].status= "active";
}
}
}
console.log(list);
``` |
63,516 | Not sure if this is right place for this question, but taking an example of the following trend, how can I determine that groups A and B are the areas where the result has been best?
[](https://i.stack.imgur.com/SyQMj.png)
I have already tried by doing an average and finding all those above the average. But finding out a group and driving a conclusion is tricky part. How can I do this? | 2019/11/21 | [
"https://datascience.stackexchange.com/questions/63516",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/78392/"
] | Let's start with the definitions:
$$ \text{RMSE} = \sqrt{\frac{1}{N} \sum\_{i = 1}^{N} (y\_i - \hat y\_i)^2}, $$
$$ \text{RMSLE} = \sqrt{\frac{1}{N} \sum\_{i = 1}^{N} (\log y\_i - \log \hat y\_i)^2}, $$
where $y\_i$ is the target value for example $i$ and $\hat y\_i$ is the model's prediction. Both metrics quantify the prediction error, so in general a high RMSE implies a high RMSLE as well.
RMSLE has the meaning of a relative error, while RMSE is an absolute error. Choosing one depends on the nature of your problem. Imagine that the target spans values from around 1 to around 100. Is predicting $\hat y = 1.01$ for true $y = 1$ as bad as $\hat y = 101$ for $y = 100$? Then RMSLE might be a good choice. With RMSE, on the other hand, predicting $\hat y = 2$ for $y = 1$ is as bad as $\hat y = 101$ for $y = 100$.
In general, you would often want to use the logarithm (or maybe the square root or some other power $0 < \alpha < 1$) for strictly positive targets that span a large range. | RMSE will have a drastic effect of outliers on its values. But in case of RMSLE we can reduce the effect of outliers by many magnitudes & their effect is much less.
RMSLE value will only consider the relative error between Predicted and the actual value neglecting the scale of data. But RMSE value will increase in magnitude if the scale of error increases. For e.g.
```
Actual value = 100
Predicted Value = 90
RMLSE: 0.1053
RMSE: 10
Actual value = 1000
Predicted Value = 900
RMSLE: 0.1053
RMSE : 100
```
Also in case of under-estimation results from RMSLE are affected greatly. So one can easily understand that it is better than RMSE in certain scenarios but RMSE works better for generalise cases. At last RMSLE is bit better than RMSE but based upon certain cases only. |
27,878 | I am rather new to Mac, but I am trying to get familiar with Terminal and I want to change its theme. I am a bit confused on how to go about installing Solarized themes I am seeing so much of around the net. I am able to get the theme installed for vim, but I want it for just my general terminal usage.
I see some suggesting to install SIMBL but then I read if you have Lion, SIMBL is not needed with the color support that it has.
And then I've seen a suggestion to just "double click" to install, I am not entirely sure what is meant to be double clicked, the `Solarized Dark ansi.terminal` file?
My concern is running something that I am not sure what it is going to do. So anyone who could shed some light on this process, that would be extremely helpful! | 2011/10/15 | [
"https://apple.stackexchange.com/questions/27878",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/12137/"
] | Just open up terminal, go to the preferences and select the theme (the .terminal file)
 | Double-Clicking a .terminal file will not "run" anything, it will just install the configuration in Terminal. At the end you will get to the same result by double-clicking and by importing the settings from Terminal directly. |
27,878 | I am rather new to Mac, but I am trying to get familiar with Terminal and I want to change its theme. I am a bit confused on how to go about installing Solarized themes I am seeing so much of around the net. I am able to get the theme installed for vim, but I want it for just my general terminal usage.
I see some suggesting to install SIMBL but then I read if you have Lion, SIMBL is not needed with the color support that it has.
And then I've seen a suggestion to just "double click" to install, I am not entirely sure what is meant to be double clicked, the `Solarized Dark ansi.terminal` file?
My concern is running something that I am not sure what it is going to do. So anyone who could shed some light on this process, that would be extremely helpful! | 2011/10/15 | [
"https://apple.stackexchange.com/questions/27878",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/12137/"
] | Just open up terminal, go to the preferences and select the theme (the .terminal file)
 | Using the 'save link as' option on the Github site for these themes didn't work, as noted in another answer. I dug in and noticed that the XML file formats were different when comparing the export of built-in themes and the ones I was trying to import.
When I did the **Download .zip** (the link is on the RHS of the main github window) and expanded the .zip file, it resulted in getting `Solarized Dark.terminal` and `Solarized Light.terminal` files which were import-able. |
388,189 | Ever heard of a proverb that reflects on "solving a problem creates a bigger one"? | 2017/05/07 | [
"https://english.stackexchange.com/questions/388189",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/100311/"
] | ***[out of the frying pan (and) into the fire](http://idioms.thefreedictionary.com/out+of+the+frying+pan+into+the+fire)*** suggests the idea that sometime trying to solve a problem may result in a bigger one:
>
> Fig. from a bad situation to a worse situation. (\*Typically: get ~; go ~; jump ~.)
>
>
> * When I tried to argue about my fine for a traffic violation, the judge charged me with contempt of court. I really went out of the frying pan into the fire. I got deeply in debt. Then I really got out of the frying pan into the fire when I lost my job.
>
>
>
(McGraw-Hill Dictionary of American Idioms and Phrasal Verbs) | [*The cure is worse than the disease* (Wikitionary):](https://en.wiktionary.org/wiki/the_cure_is_worse_than_the_disease)
>
> 2. (*figuratively*) The solution or proposed solution to a problem produces a worse net result than the problem does (or threatens a non-negligible risk of doing so), especially via unintended consequences.
>
>
>
Also *the remedy is worse than the disease* or *the ailment*. Examples from the media:
>
> The Cure for Fake News Is Worse than the Disease
>
> [(Politico, November 12, 2016.)](http://www.politico.com/magazine/story/2016/11/the-cure-for-fake-news-is-worse-than-the-disease-214477)
>
>
> Fake news is sickening, but don't make the cure worse than the disease
>
> [(The Sydney Morning Herald, December 16, 2016.)](http://www.smh.com.au/business/comment-and-analysis/fake-news-is-sickening-but-dont-make-the-cure-worse-than-the-disease-20161216-gtcuew.html)
>
>
>
Both articles acknowledge that fakes news is a problem, but go on to point out that suggested solutions, which would involve giving someone the power to decide what is fake news and what is real news, would be a bigger problem. |
479,438 | This is only a general question in order for me to get a better idea of my dual boot (windows 8 & Ubuntu) systems.
I noticed that every time I run Ubuntu (which is becoming more often) the battery power gets consumed really fast. I am not performing any special tasks at the moment, just getting to know the system, for example, sound settings, watching videos, surfing the net and so on. When I do the same thing in Windows 8 the battery lives a considerable amount of time longer.
Is this something to do with Ubuntu or is it because of the dual boot that I have going on? In other words, if I start running Ubuntu all by itself on my laptop, will it be more power consuming than Windows 8? | 2014/06/08 | [
"https://askubuntu.com/questions/479438",
"https://askubuntu.com",
"https://askubuntu.com/users/285421/"
] | Similar trouble can get solved by typing
```
$ tidy --help
The program 'tidy' is currently not installed. You can install it by typing:
sudo apt-get install tidy
```
... to get a hint on which packages might come into question. If there are several suggested ones, then look them up (google).
The " --help" makes MOST software respond with a first level of information. If that appears, then "tidy" would probably been in a place that the "caller software" did/does not know about, another possible cause for similar problems (hint; add to $PATH) | Run this in a terminal to install tidy:
```
sudo apt-get install tidy
```
then you are able to compile (`F8`) html files in Geany.
If you want to run them in the browser press `F5`. |
45,091,841 | I'm using expect to simulate sftp interactive prompt (`download_from_sftp.exp`):
```
#!/usr/bin/expect
set username [lindex $argv 0];
set server [lindex $argv 1]
set password [lindex $argv 2];
set source [lindex $argv 3];
set target [lindex $argv 4];
set timeout 2400;
spawn sftp "$username@$server"
expect "password:"
send "$password\n"
expect "sftp>"
send "get ${source} ${target}\n"
expect "sftp>"
send "bye\n"
interact
```
in which `$targe` is the output directory that contains space :(
How can I pass the argument so that it got treated as one argument? Currenly I'm using something like:
```
cmd="${git_directory}/sh/download_from_sftp.exp $sftp_username
$sftp_server $sftp_password ${src_xml} ${target_xml}"
$cmd # run
```
in which the last argument will be expanded. | 2017/07/13 | [
"https://Stackoverflow.com/questions/45091841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3935286/"
] | In the shell, you cannot "serialize" a command with arguments into a single string and get the command deserialized with some spaces as regular spaces and some as "special" spaces.
You need to use a shell array (bash, ksh, zsh all have arrays)
```
cmd=(
"$git_directory/sh/download_from_sftp.exp"
"$sftp_username"
"$sftp_server"
"$sftp_password"
"$src_xml"
"$target_xml"
)
"${cmd[@]}" # run
```
All those quotes are required.
This is the only way to reliably keep the arguments containing whitespace as single entities.
In expect, you'll have to probably quote the arguments (for sftp's sake)
```
send "get $source \"$target"\r"
```
Normally, you send with `\r` not `\n` -- `\r` is a carriage return, or "hitting enter" | You can enclose the arguement with quotes:
```
cmd="${git_directory}/sh/download_from_sftp.exp $sftp_username $sftp_server$sftp_password \"${src_xml}\" \"${target_xml}\""
$cmd # run
``` |
53,053,326 | I got an MVC 5 application that i'm porting to asp.net Core.
In the MVC application call to controller we're made using AngularJS $resource (sending JSON) and we we're POSTing data doing :
```
ressource.save({ entries: vm.entries, projectId: vm.project.id }).$promise...
```
that will send a JSON body like:
```
{
entries:
[
{
// lots of fields
}
],
projectId:12
}
```
the MVC controller looked like this :
```
[HttpPost]
public JsonResult Save(List<EntryViewModel> entries, int projectId) {
// code here
}
```
How can I replicate the same behaviour with .NET Core since we can't have multiple [FromBody] | 2018/10/29 | [
"https://Stackoverflow.com/questions/53053326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115322/"
] | As pointed out in the comment, one possible solution is to unify the properties you're posting onto a single model class.
Something like the following should do the trick:
```
public class SaveModel
{
public List<EntryViewModel> Entries{get;set;}
public int ProjectId {get;set;}
}
```
Don't forget to decorate the model with the `[FromBody]` attribute:
```
[HttpPost]
public JsonResult Save([FromBody]SaveViewModel model)
{
// code here
}
```
Hope this helps! | It's still rough but I made a Filter to mimic the feature.
```
public class OldMVCFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request.Method != "GET")
{
var body = context.HttpContext.Request.Body;
JToken token = null;
var param = context.ActionDescriptor.Parameters;
using (var reader = new StreamReader(body))
using (var jsonReader = new JsonTextReader(reader))
{
jsonReader.CloseInput = false;
token = JToken.Load(jsonReader);
}
if (token != null)
{
var serializer = new JsonSerializer();
serializer.DefaultValueHandling = DefaultValueHandling.Populate;
serializer.FloatFormatHandling = FloatFormatHandling.DefaultValue;
foreach (var item in param)
{
JToken model = token[item.Name];
if (model == null)
{
// try to cast the full body as the current object
model = token.Root;
}
if (model != null)
{
model = this.RemoveEmptyChildren(model, item.ParameterType);
var res = model.ToObject(item.ParameterType, serializer);
context.ActionArguments[item.Name] = res;
}
}
}
}
}
private JToken RemoveEmptyChildren(JToken token, Type type)
{
var HasBaseType = type.GenericTypeArguments.Count() > 0;
List<PropertyInfo> PIList = new List<PropertyInfo>();
if (HasBaseType)
{
PIList.AddRange(type.GenericTypeArguments.FirstOrDefault().GetProperties().ToList());
}
else
{
PIList.AddRange(type.GetTypeInfo().GetProperties().ToList());
}
if (token != null)
{
if (token.Type == JTokenType.Object)
{
JObject copy = new JObject();
foreach (JProperty jProp in token.Children<JProperty>())
{
var pi = PIList.FirstOrDefault(p => p.Name == jProp.Name);
if (pi != null) // If destination type dont have this property we ignore it
{
JToken child = jProp.Value;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, pi.PropertyType);
}
if (!IsEmpty(child))
{
if (child.Type == JTokenType.Object || child.Type == JTokenType.Array)
{
// nested value has been checked, we add the object
copy.Add(jProp.Name, child);
}
else
{
if (!pi.Name.ToLowerInvariant().Contains("string"))
{
// ignore empty value when type is not string
var Val = (string)child;
if (!string.IsNullOrWhiteSpace(Val))
{
// we add the property only if it contain meningfull data
copy.Add(jProp.Name, child);
}
}
}
}
}
}
return copy;
}
else if (token.Type == JTokenType.Array)
{
JArray copy = new JArray();
foreach (JToken item in token.Children())
{
JToken child = item;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, type);
}
if (!IsEmpty(child))
{
copy.Add(child);
}
}
return copy;
}
return token;
}
return null;
}
private bool IsEmpty(JToken token)
{
return (token.Type == JTokenType.Null || token.Type == JTokenType.Undefined);
}
}
``` |
53,053,326 | I got an MVC 5 application that i'm porting to asp.net Core.
In the MVC application call to controller we're made using AngularJS $resource (sending JSON) and we we're POSTing data doing :
```
ressource.save({ entries: vm.entries, projectId: vm.project.id }).$promise...
```
that will send a JSON body like:
```
{
entries:
[
{
// lots of fields
}
],
projectId:12
}
```
the MVC controller looked like this :
```
[HttpPost]
public JsonResult Save(List<EntryViewModel> entries, int projectId) {
// code here
}
```
How can I replicate the same behaviour with .NET Core since we can't have multiple [FromBody] | 2018/10/29 | [
"https://Stackoverflow.com/questions/53053326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115322/"
] | you cannot have multiple parameter with the FromBody attibute in an action method. If that is need, use a complex type such as a class with properties equivalent to the parameter or dynamic type like that
```
[HttpPost("save/{projectId}")]
public JsonResult Save(int projectId, [FromBody] dynamic entries) {
// code here
}
``` | It's still rough but I made a Filter to mimic the feature.
```
public class OldMVCFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request.Method != "GET")
{
var body = context.HttpContext.Request.Body;
JToken token = null;
var param = context.ActionDescriptor.Parameters;
using (var reader = new StreamReader(body))
using (var jsonReader = new JsonTextReader(reader))
{
jsonReader.CloseInput = false;
token = JToken.Load(jsonReader);
}
if (token != null)
{
var serializer = new JsonSerializer();
serializer.DefaultValueHandling = DefaultValueHandling.Populate;
serializer.FloatFormatHandling = FloatFormatHandling.DefaultValue;
foreach (var item in param)
{
JToken model = token[item.Name];
if (model == null)
{
// try to cast the full body as the current object
model = token.Root;
}
if (model != null)
{
model = this.RemoveEmptyChildren(model, item.ParameterType);
var res = model.ToObject(item.ParameterType, serializer);
context.ActionArguments[item.Name] = res;
}
}
}
}
}
private JToken RemoveEmptyChildren(JToken token, Type type)
{
var HasBaseType = type.GenericTypeArguments.Count() > 0;
List<PropertyInfo> PIList = new List<PropertyInfo>();
if (HasBaseType)
{
PIList.AddRange(type.GenericTypeArguments.FirstOrDefault().GetProperties().ToList());
}
else
{
PIList.AddRange(type.GetTypeInfo().GetProperties().ToList());
}
if (token != null)
{
if (token.Type == JTokenType.Object)
{
JObject copy = new JObject();
foreach (JProperty jProp in token.Children<JProperty>())
{
var pi = PIList.FirstOrDefault(p => p.Name == jProp.Name);
if (pi != null) // If destination type dont have this property we ignore it
{
JToken child = jProp.Value;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, pi.PropertyType);
}
if (!IsEmpty(child))
{
if (child.Type == JTokenType.Object || child.Type == JTokenType.Array)
{
// nested value has been checked, we add the object
copy.Add(jProp.Name, child);
}
else
{
if (!pi.Name.ToLowerInvariant().Contains("string"))
{
// ignore empty value when type is not string
var Val = (string)child;
if (!string.IsNullOrWhiteSpace(Val))
{
// we add the property only if it contain meningfull data
copy.Add(jProp.Name, child);
}
}
}
}
}
}
return copy;
}
else if (token.Type == JTokenType.Array)
{
JArray copy = new JArray();
foreach (JToken item in token.Children())
{
JToken child = item;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, type);
}
if (!IsEmpty(child))
{
copy.Add(child);
}
}
return copy;
}
return token;
}
return null;
}
private bool IsEmpty(JToken token)
{
return (token.Type == JTokenType.Null || token.Type == JTokenType.Undefined);
}
}
``` |
113,288 | I have a 32bit 10.04 server has 32gb ram
I am running opencart e-commerce sites (php)
Max How much ram can use by opencart? (32gb or 4gb?) | 2012/03/15 | [
"https://askubuntu.com/questions/113288",
"https://askubuntu.com",
"https://askubuntu.com/users/50776/"
] | If you use a [PAE-kernel](https://help.ubuntu.com/community/EnablingPAE) a 32 bit operating systems like yours, can use up to 64 Gb of memory (RAM). | Also, PHP has various tuning parameters, including `memory_limit`, which may be as high as 128MiB if you're running a recent version. Check your `php.ini` file for details. |
113,288 | I have a 32bit 10.04 server has 32gb ram
I am running opencart e-commerce sites (php)
Max How much ram can use by opencart? (32gb or 4gb?) | 2012/03/15 | [
"https://askubuntu.com/questions/113288",
"https://askubuntu.com",
"https://askubuntu.com/users/50776/"
] | If you have a PAE kernel installed, your 32 bit operating system should be able to address up to 64 GB of RAM.
As far as I know, each single process should be able to address not more than 4 GB RAM. Now since opencart is a PHP application and I assume that each visit of your website by another browser spwans a new PHP process, your system and therefore opencart should be able to use more than 4 GB of RAM. | Also, PHP has various tuning parameters, including `memory_limit`, which may be as high as 128MiB if you're running a recent version. Check your `php.ini` file for details. |
9,563,302 | I have service url : [please check it](http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson), It's return json string.
I don't know how to call this url by using `C#`
Then. By the link, you can see `"href"` in json data. It's have `.png` url. I would like to save that image to my local disk.
**Question**
1. How to get and read json data from this [service](http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson)
2. How to save image from url to local disk | 2012/03/05 | [
"https://Stackoverflow.com/questions/9563302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115817/"
] | I imagine you need the service request from the server and not from the client; if so a straightforward way would be
```
string json = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson");
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
if ((responseStream != null) && responseStream.CanRead)
{
using (var reader = new System.IO.StreamReader(responseStream))
{
json = reader.ReadToEnd();
}
}
}
finally
{
if (response != null)
{
response.Close();
}
}
```
The image can be obtained the same way.
For Json I recommend [JSON.NET](http://james.newtonking.com/pages/json-net.aspx). | 1. Add Json.NET package (see for reference [How to install JSON.NET using NuGet?](https://stackoverflow.com/questions/4444903/how-to-install-json-net-using-nuget))
2. Use the following code:
```
using Newtonsoft.Json;
......
string url = "...";
var webClient = new WebClient();
var s = webClient.DownloadString(url);
dynamic d = JsonConvert.DeserializeObject(s);
var href = ((string) d.href);
webClient.DownloadFile(href, @"d:\file.png");
```
Note that your png file does not exists :)
You may create your POCO class if you want. But if all you need is just download a file — that may not be needed. |
9,563,302 | I have service url : [please check it](http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson), It's return json string.
I don't know how to call this url by using `C#`
Then. By the link, you can see `"href"` in json data. It's have `.png` url. I would like to save that image to my local disk.
**Question**
1. How to get and read json data from this [service](http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson)
2. How to save image from url to local disk | 2012/03/05 | [
"https://Stackoverflow.com/questions/9563302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115817/"
] | Using Data Contracts and `DataContractJsonSerializer`:
References Required:
--------------------
```
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Net;
```
Data Contract
-------------
```
[DataContract]
internal class GISData
{
[DataMember]
public string href;
[DataMember]
public int width;
[DataMember]
public int height;
[DataMember]
public GISDataExtent extent;
[DataMember]
public string scale;
}
[DataContract]
internal class GISDataExtent
{
[DataMember]
public string xmin;
[DataMember]
public string ymin;
[DataMember]
public string xmax;
[DataMember]
public string ymax;
[DataMember]
public GISDataExtentSpatialReference spatialReference;
}
[DataContract]
internal class GISDataExtentSpatialReference
{
[DataMember]
public string wkid;
}
```
Putting it all together and downloading the file:
-------------------------------------------------
Pull the JSON String from your URL - Deserialize the object and download your image.
```
WebClient webClient;
webClient = new WebClient();
string json = webClient.DownloadString(@"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson");
MemoryStream stream = new MemoryStream((Encoding.UTF8.GetBytes(json)));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
stream.Position = 0;
GISData data = (GISData)ser.ReadObject(stream);
stream.Close();
webClient = new WebClient();
webClient.DownloadFile(data.href, "C:/" + data.href.Substring(data.href.LastIndexOf("/") + 1)); //Save only the filename and not the entire URL as a name.
``` | 1. Add Json.NET package (see for reference [How to install JSON.NET using NuGet?](https://stackoverflow.com/questions/4444903/how-to-install-json-net-using-nuget))
2. Use the following code:
```
using Newtonsoft.Json;
......
string url = "...";
var webClient = new WebClient();
var s = webClient.DownloadString(url);
dynamic d = JsonConvert.DeserializeObject(s);
var href = ((string) d.href);
webClient.DownloadFile(href, @"d:\file.png");
```
Note that your png file does not exists :)
You may create your POCO class if you want. But if all you need is just download a file — that may not be needed. |
58,247 | Say I have a disease that is autosomal recessive. If one was heterozygous for this trait, could the recessive gene still be expressed?
I know sickle cell anemia has a heterozygous advantage so it must be possible but what are the conditions for this to happen and also to what degree?
EDIT: This isn't asking how a gene is recessive or dominant in a molecular level. | 2017/04/10 | [
"https://biology.stackexchange.com/questions/58247",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/31455/"
] | **Short answer**
The concepts dominance, additivity, epistasis, recessivity and others are all specific to a given phenotype. Here you are getting confused because you are considering two different phenotypes at once.
**Slightly longer answer**
By definition, if an allele is recessive, then in the heterozygote state, the phenotype of interest is just like the homozygous dominant. An important point in the above sentence is "the phenotype of interest". A given locus may show a pattern of simple dominance-recessivity for a given phenotype but may show a completely different pattern for another phenotypic trait.
Let's consider your example of sickle cell anemia. For the phenotype which is the disease, sickle cell anemia has a simple dominance-recessivity relationship. However, for the phenotypic trait which is fitness (yes, in quantitative genetics, fitness is often modelled as a simple phenotypic trait), sickle-cell anemia shows (environment dependent) heterozygote advantage. Also, the fitnesses of the two homozygotes differ greatly.
Note that, in reality, very few loci show cases of perfect recessivity dominance.
**EDIT**
You are considering two (or even three) phenotypes.
*First Phenotype: Fitness*
Fitness shows overdominance (with highly unequal fitness for both homozygotes).
*Second phenotype: Disease*
Double mutant are sick, the others aren't. Perfect dominance-recessivity (although if I am not mistaken heterozygotes individuals have some restriction when it comes to scuba diving if I am not mistaken)
*Third phenotype: Shape of hemoglobin*
If the heterozygote hemoglobin is shaped just like the healthy homozygote, then there is dominance-recessivity. If the shape differs (which might be causing malaria resistance, I don't know), then there is some partial dominance going on. | There are a couple of distinctions to make here. You can have an allele which is 'Phenotypically Expressed', that is it's visible at the organism level by some feature. In that case, no, recessive alleles by definition do not express that particular phenotype.
Now at the molecular level things can be different. You have the same two alleles and both can produce equal mRNA and protein levels, but they differ by a nucleotide/codon, which gives rise to the distinct functions and thus produce distinct phenotypes.
At this molecular level, both alleles are expressed and are co-dominant for the phenotype of measuring mRNA variants by sequencing and at the same time, the organism presents only the dominant phenotype.
So it's important to consider in which context one is discussing 'expressed'. If a research paper is about genetic disease, you'll often hear discussion of the 'recessive allele' and still have measurements of it's expressed mRNA. Everyone just knows by convention that recessive in the context of a human genetics disease paper means the particular disease the paper is on or a phenotype that is being discussed. |
58,247 | Say I have a disease that is autosomal recessive. If one was heterozygous for this trait, could the recessive gene still be expressed?
I know sickle cell anemia has a heterozygous advantage so it must be possible but what are the conditions for this to happen and also to what degree?
EDIT: This isn't asking how a gene is recessive or dominant in a molecular level. | 2017/04/10 | [
"https://biology.stackexchange.com/questions/58247",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/31455/"
] | **Short answer**
The concepts dominance, additivity, epistasis, recessivity and others are all specific to a given phenotype. Here you are getting confused because you are considering two different phenotypes at once.
**Slightly longer answer**
By definition, if an allele is recessive, then in the heterozygote state, the phenotype of interest is just like the homozygous dominant. An important point in the above sentence is "the phenotype of interest". A given locus may show a pattern of simple dominance-recessivity for a given phenotype but may show a completely different pattern for another phenotypic trait.
Let's consider your example of sickle cell anemia. For the phenotype which is the disease, sickle cell anemia has a simple dominance-recessivity relationship. However, for the phenotypic trait which is fitness (yes, in quantitative genetics, fitness is often modelled as a simple phenotypic trait), sickle-cell anemia shows (environment dependent) heterozygote advantage. Also, the fitnesses of the two homozygotes differ greatly.
Note that, in reality, very few loci show cases of perfect recessivity dominance.
**EDIT**
You are considering two (or even three) phenotypes.
*First Phenotype: Fitness*
Fitness shows overdominance (with highly unequal fitness for both homozygotes).
*Second phenotype: Disease*
Double mutant are sick, the others aren't. Perfect dominance-recessivity (although if I am not mistaken heterozygotes individuals have some restriction when it comes to scuba diving if I am not mistaken)
*Third phenotype: Shape of hemoglobin*
If the heterozygote hemoglobin is shaped just like the healthy homozygote, then there is dominance-recessivity. If the shape differs (which might be causing malaria resistance, I don't know), then there is some partial dominance going on. | Others have already explained. I add some clarifications. You said that you know the molecular mechanism of dominance; revisiting them will answer your queries.
Gene expression means the formation of the gene product in whatever form it is active – protein or RNA. If an allele is recessive it can:
* Not form the product
* Form a non-functional product
* Form a hypo-active product
* Form less amount of product
In all but the first case the gene is expressed although it may not give rise to the product of your interest.
Phenotypes of homozygotes and heterozygotes can differ in these different cases but in a strictly Mendelian case, the expression (or non-expression) of the recessive allele has no effect on the phenotype if the dominant allele is present.
Now, one can also dig deep on what phenotype is. Phenotype is an observable manifestation of a trait but with latest technology we can observe even the DNA sequence. In my opinion (in a contemporary perspective), an allele is strictly dominant if a recessive allele present along with it does not perturb the regulatory/metabolic/signalling network at all. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.