qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | ( value == 0.00 )
Never gets true.
Or, it takes so many runs of the function that the it runs into, well, stack overflow :P
You should take another look at how you made your function. Right now it is not even useful, it can only ever return 0. | You could check `if (value * 0.98 == value)` instead of `if (value == 0)`. This condition will be met exactly when `value` becomes so small (subnormal) that it has too few bits of precision for multiplication by `0.98` to yield a different result. |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | You should *always* use 'approximate' comparisons in floating point calculations. E.g., `if (abs(value) < EPS)` instead of `if ( value == 0.00 )`. `EPS` here is a small constant (depends on your requirements and datatype).
I suspect this is what's actually happening. You get to the smallest possible positive value in your datatype, like `1 * 2^(-10000)` (10000 comes from the top of my head) and now `value * 0.98 = value`. E.g., it has to be rounded either to `0` or to `total` and `0.98*total` is obviously closer to `total`.
But that's only speculations, though. With floating point computations, you can never be sure :) | Wow, thanks for the quick answer everyone!
Apparently that little floating point detail was skipped in my class...
So since everyone is pretty much saying the same thing (don't compare floating points with equality since they're never really exact), does the same hold true if I used ints or doubles?
Originally I had the test as if ( value <= 0.0 ), but that gave me the same thing.
Just ran it with the test as <= 0.005 and that seemed to be just fine!
Thanks all!
mIL3S
www.milkdrinkingcow.com |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | Due to floating point calculations never being exact in floating point math you never get to value == 0.00. You might want to try something like value < 0.0000001 or something like that and tweak it where it works. | ( value == 0.00 )
Never gets true.
Or, it takes so many runs of the function that the it runs into, well, stack overflow :P
You should take another look at how you made your function. Right now it is not even useful, it can only ever return 0. |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | You should *always* use 'approximate' comparisons in floating point calculations. E.g., `if (abs(value) < EPS)` instead of `if ( value == 0.00 )`. `EPS` here is a small constant (depends on your requirements and datatype).
I suspect this is what's actually happening. You get to the smallest possible positive value in your datatype, like `1 * 2^(-10000)` (10000 comes from the top of my head) and now `value * 0.98 = value`. E.g., it has to be rounded either to `0` or to `total` and `0.98*total` is obviously closer to `total`.
But that's only speculations, though. With floating point computations, you can never be sure :) | don't compare float values with constants, always check if they fall under a lower-bound.
change your value == 0.00 to value <= 0.0001 for example |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | ( value == 0.00 )
Never gets true.
Or, it takes so many runs of the function that the it runs into, well, stack overflow :P
You should take another look at how you made your function. Right now it is not even useful, it can only ever return 0. | don't compare float values with constants, always check if they fall under a lower-bound.
change your value == 0.00 to value <= 0.0001 for example |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | ( value == 0.00 )
Never gets true.
Or, it takes so many runs of the function that the it runs into, well, stack overflow :P
You should take another look at how you made your function. Right now it is not even useful, it can only ever return 0. | Wow, thanks for the quick answer everyone!
Apparently that little floating point detail was skipped in my class...
So since everyone is pretty much saying the same thing (don't compare floating points with equality since they're never really exact), does the same hold true if I used ints or doubles?
Originally I had the test as if ( value <= 0.0 ), but that gave me the same thing.
Just ran it with the test as <= 0.005 and that seemed to be just fine!
Thanks all!
mIL3S
www.milkdrinkingcow.com |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | You should *always* use 'approximate' comparisons in floating point calculations. E.g., `if (abs(value) < EPS)` instead of `if ( value == 0.00 )`. `EPS` here is a small constant (depends on your requirements and datatype).
I suspect this is what's actually happening. You get to the smallest possible positive value in your datatype, like `1 * 2^(-10000)` (10000 comes from the top of my head) and now `value * 0.98 = value`. E.g., it has to be rounded either to `0` or to `total` and `0.98*total` is obviously closer to `total`.
But that's only speculations, though. With floating point computations, you can never be sure :) | Do not directly compare floating point numbers; your "value" will probably never really be 0.0 (zero).
do something like :
```
float smallNumber = 0.00001;
if ( value < smallNumber )
{
...
}
``` |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | Do not directly compare floating point numbers; your "value" will probably never really be 0.0 (zero).
do something like :
```
float smallNumber = 0.00001;
if ( value < smallNumber )
{
...
}
``` | don't compare float values with constants, always check if they fall under a lower-bound.
change your value == 0.00 to value <= 0.0001 for example |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | You could check `if (value * 0.98 == value)` instead of `if (value == 0)`. This condition will be met exactly when `value` becomes so small (subnormal) that it has too few bits of precision for multiplication by `0.98` to yield a different result. | Wow, thanks for the quick answer everyone!
Apparently that little floating point detail was skipped in my class...
So since everyone is pretty much saying the same thing (don't compare floating points with equality since they're never really exact), does the same hold true if I used ints or doubles?
Originally I had the test as if ( value <= 0.0 ), but that gave me the same thing.
Just ran it with the test as <= 0.005 and that seemed to be just fine!
Thanks all!
mIL3S
www.milkdrinkingcow.com |
4,628,946 | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks | 2011/01/07 | [
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] | Do not directly compare floating point numbers; your "value" will probably never really be 0.0 (zero).
do something like :
```
float smallNumber = 0.00001;
if ( value < smallNumber )
{
...
}
``` | Wow, thanks for the quick answer everyone!
Apparently that little floating point detail was skipped in my class...
So since everyone is pretty much saying the same thing (don't compare floating points with equality since they're never really exact), does the same hold true if I used ints or doubles?
Originally I had the test as if ( value <= 0.0 ), but that gave me the same thing.
Just ran it with the test as <= 0.005 and that seemed to be just fine!
Thanks all!
mIL3S
www.milkdrinkingcow.com |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | Using this config maintains my session id on node 0.6.17, express 3.0.0rc4. Initially I had the following in the virtualhost, but even after changing to match your config, it still works.
```
ServerName api
ServerAlias api.internal.local
```
I get a Set-cookie connect.sid which is maintained. | This happened to us to i don't think the reverse cookies stuff did anything to help our situation out.
I tried:
app.use("trust proxy");
to no avail.
however using
```
app.use("trust proxy");
app.set("trust proxy", 1);
```
Works.
Hope this helps anyone having proxy cookie issues. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | I experienced this exact issue and tried everything else mentioned here without success. The final piece of the puzzle was adding the following to Apache's SSL Virtual Host config:
`RequestHeader set X-Forwarded-Proto "https"`
This particular gem I discovered in one of the last comments at <https://github.com/expressjs/session/issues/251>
So overall the things I implemented to fix it were as follows:
1. Changes to Apache Config:
`RequestHeader set X-Forwarded-Proto "https"
ProxyPassReverseCookiePath / /`
2. Changes to Node App.
`app.enable('trust proxy');` | It should be trivial to look at the session cookie being forwarded and see why your browser doesn't re-send it when proxied -- the domain or path are likely wrong.
Re: your later comments -- Maybe you really did set "ProxyPassReverseCookieDomain / /" instead of using domains as the argument?
ProxyPreserveHost would probably also indirectly work for you, but fixing up the cookie is better. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | I experienced this exact issue and tried everything else mentioned here without success. The final piece of the puzzle was adding the following to Apache's SSL Virtual Host config:
`RequestHeader set X-Forwarded-Proto "https"`
This particular gem I discovered in one of the last comments at <https://github.com/expressjs/session/issues/251>
So overall the things I implemented to fix it were as follows:
1. Changes to Apache Config:
`RequestHeader set X-Forwarded-Proto "https"
ProxyPassReverseCookiePath / /`
2. Changes to Node App.
`app.enable('trust proxy');` | Using this config maintains my session id on node 0.6.17, express 3.0.0rc4. Initially I had the following in the virtualhost, but even after changing to match your config, it still works.
```
ServerName api
ServerAlias api.internal.local
```
I get a Set-cookie connect.sid which is maintained. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | Judging by [Apache ProxyPass and Sessions](https://stackoverflow.com/questions/8676890/apache-proxypass-and-sessions) This apache config Maybe ...
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPassReverseCookiePath / /
</VirtualHost>
``` | It should be trivial to look at the session cookie being forwarded and see why your browser doesn't re-send it when proxied -- the domain or path are likely wrong.
Re: your later comments -- Maybe you really did set "ProxyPassReverseCookieDomain / /" instead of using domains as the argument?
ProxyPreserveHost would probably also indirectly work for you, but fixing up the cookie is better. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | Judging by [Apache ProxyPass and Sessions](https://stackoverflow.com/questions/8676890/apache-proxypass-and-sessions) This apache config Maybe ...
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPassReverseCookiePath / /
</VirtualHost>
``` | Add the following to server.js
```
app.enable('trust proxy');
```
Quote from ExpressJS API Docs: <http://expressjs.com/api.html#app-settings> ...
>
> trust proxy - Enables reverse proxy support, disabled by default
>
>
> |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | Judging by [Apache ProxyPass and Sessions](https://stackoverflow.com/questions/8676890/apache-proxypass-and-sessions) This apache config Maybe ...
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPassReverseCookiePath / /
</VirtualHost>
``` | Using this config maintains my session id on node 0.6.17, express 3.0.0rc4. Initially I had the following in the virtualhost, but even after changing to match your config, it still works.
```
ServerName api
ServerAlias api.internal.local
```
I get a Set-cookie connect.sid which is maintained. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | I experienced this exact issue and tried everything else mentioned here without success. The final piece of the puzzle was adding the following to Apache's SSL Virtual Host config:
`RequestHeader set X-Forwarded-Proto "https"`
This particular gem I discovered in one of the last comments at <https://github.com/expressjs/session/issues/251>
So overall the things I implemented to fix it were as follows:
1. Changes to Apache Config:
`RequestHeader set X-Forwarded-Proto "https"
ProxyPassReverseCookiePath / /`
2. Changes to Node App.
`app.enable('trust proxy');` | This happened to us to i don't think the reverse cookies stuff did anything to help our situation out.
I tried:
app.use("trust proxy");
to no avail.
however using
```
app.use("trust proxy");
app.set("trust proxy", 1);
```
Works.
Hope this helps anyone having proxy cookie issues. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | It should be trivial to look at the session cookie being forwarded and see why your browser doesn't re-send it when proxied -- the domain or path are likely wrong.
Re: your later comments -- Maybe you really did set "ProxyPassReverseCookieDomain / /" instead of using domains as the argument?
ProxyPreserveHost would probably also indirectly work for you, but fixing up the cookie is better. | This happened to us to i don't think the reverse cookies stuff did anything to help our situation out.
I tried:
app.use("trust proxy");
to no avail.
however using
```
app.use("trust proxy");
app.set("trust proxy", 1);
```
Works.
Hope this helps anyone having proxy cookie issues. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | Judging by [Apache ProxyPass and Sessions](https://stackoverflow.com/questions/8676890/apache-proxypass-and-sessions) This apache config Maybe ...
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPassReverseCookiePath / /
</VirtualHost>
``` | This happened to us to i don't think the reverse cookies stuff did anything to help our situation out.
I tried:
app.use("trust proxy");
to no avail.
however using
```
app.use("trust proxy");
app.set("trust proxy", 1);
```
Works.
Hope this helps anyone having proxy cookie issues. |
12,295,963 | I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express! | 2012/09/06 | [
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] | Add the following to server.js
```
app.enable('trust proxy');
```
Quote from ExpressJS API Docs: <http://expressjs.com/api.html#app-settings> ...
>
> trust proxy - Enables reverse proxy support, disabled by default
>
>
> | Using this config maintains my session id on node 0.6.17, express 3.0.0rc4. Initially I had the following in the virtualhost, but even after changing to match your config, it still works.
```
ServerName api
ServerAlias api.internal.local
```
I get a Set-cookie connect.sid which is maintained. |
8,054,360 | I have written my own `PopupPanel` in GWT. I want to show the popup relative to an other widget. My implementation of the class looks like the following:
```java
public class Popover extends PopupPanel implements PositionCallback {
private static final Binder binder = GWT.create(Binder.class);
private UIObject relative;
interface Binder extends UiBinder<Widget, Popover> {
}
public Popover() {
setWidget(binder.createAndBindUi(this));
setStylePrimaryName("popover");
}
public void show(UIObject relative) {
this.relative = relative;
setPopupPositionAndShow(this);
}
public void setPosition(int offsetWidth, int offsetHeight) {
if (relative != null) {
int left = relative.getAbsoluteLeft();
int top = relative.getAbsoluteTop();
int width = relative.getOffsetWidth();
int height = relative.getOffsetHeight();
int topCenter = top + height / 2 - offsetHeight / 2;
if (offsetWidth < left) {
setPopupPosition(left - offsetWidth, topCenter);
} else {
setPopupPosition(left + width, topCenter);
}
}
}
}
```
The problem is that `offsetWidth` and `offsetHeight` is always `10`?
My `Popover.ui.xml` looks like the following:
```xml
<g:FlowPanel stylePrimaryName="popover">
<g:FlowPanel stylePrimaryName="arrow" />
<g:FlowPanel stylePrimaryName="inner">
<g:Label stylePrimaryName="title" text="New Label" />
<g:FlowPanel stylePrimaryName="content">
<g:Label text="Hallo" />
</g:FlowPanel>
</g:FlowPanel>
</g:FlowPanel>
``` | 2011/11/08 | [
"https://Stackoverflow.com/questions/8054360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | To solve this issue, I followed the steps used by `PopupPanel`'s `setPopupPositionAndShow()`, but I made the positioning step a deferred command. My code didn't extend `PopupPanel`, hence the `popupPanel` variable:
```java
popupPanel.setVisible(false);
popupPanel.show();
// Pausing until the event loop is clear appears to give the browser
// sufficient time to apply CSS styling. We use the popup's offset
// width and height to calculate the display position, but those
// dimensions are not accurate until styling has been applied.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
yourMethodToSetPositionGoesHere(popupPanel);
popupPanel.setVisible(true);
}
});
``` | `getOffsetWidth()` and `getOffsetHeight()` only work if the DOM is fully constructed and the container for which you want to get the value is visible and attached.
Why don't you use the `showRelativeTo()` function of the `PopupPanel`?
```java
popup.showRelativeTo(SomeWidget);
``` |
70,110,718 | I'm trying to create a ENV VAR called SETTINGS in a Python image with Dockerfile. This env var must be dynamic, because I need to change the conf profile betweet production and preproduction.
I've created an script (entrypoint.sh) with two commands, the first one create the SETTINGS VAR and the second one is a python command.
The problem is that the python line works properly but the SETTINGS var doesn't.
Script
```
#!/bin/bash
profile=$profile
export SETTINGS=/acalls-service/${profile}.cfg
python -m "_acalls_clasiffier"
exec
```
Dockerfile
```
ENTRYPOINT ["/bin/bash", "-c", ". entrypoint.sh"]
```
I've tried with ["./entrypoint.sh] also but I doesn't work. | 2021/11/25 | [
"https://Stackoverflow.com/questions/70110718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10744148/"
] | This would be a pretty typical use of an entrypoint wrapper script. Remember that a container only runs a single process. If your Dockerfile specifies an `ENTRYPOINT`, that's the process, and the `CMD` is passed as additional arguments to it. That lets you set up a script that does some first-time setup and then replaces itself with the real command:
```sh
#!/bin/sh
# Set the environment variable
export SETTINGS=/acalls-service/${profile}.cfg
# Run the CMD
exec "$@"
```
In your Dockerfile you'd specify this script as the `ENTRYPOINT` and then the actual command as `CMD`.
```sh
ENTRYPOINT ["./entrypoint.sh"] # must be JSON-array syntax
CMD ["python", "-m", "_acalls_clasiffier"] # shell syntax allowed here too
```
Since you can easily provide a replacement `CMD`, you can check that this is working
```sh
docker run --rm myimage \
sh -c 'echo $SETTINGS' # <-- run in the container, single-quoted so the
# host shell doesn't expand it
```
If you get a debugging shell in the container with `docker exec`, it won't see the variable set because it doesn't run through the entrypoint sequence. That's not usually a practical problem. You can always `docker run` a new container with an interactive shell instead of the Python script. | There is a difference in passing a `dynamic` environment var on `docker build` or pass the variable on runtime.
Env vars on runtime
===================
If you want to pass it on runtime, it doesn't need to be in your Dockerfile, just pass it when running your container:
```
docker run my-image -e MY_ENV=foo
```
Env vars on build
=================
During build you have to:
* define your env var in your Dockerfile
* pass the env var into the build process
Example Dockerfile:
```
ARG MY_BUILD_ARG=myDefaultArgument
FROM node:16.9.0
ARG MY_BUILD_ARG
ENV MY_PUBLIC_ENV=${MY_BUILD_ARG}
RUN echo ${MY_PUBLIC_ENV} // => myRandomEnvVar
```
And then pass it when you build as:
```
docker build --build-arg MY_BUILD_ARG=myRandomEnvVar
``` |
60,408,730 | I am using spring boot starter 2.2.0.RELEASE for my application. I have one kafka consumer. Now I want to inject my spring entities into my kafka consumer (kafka consumer is not managed by spring container).
I tried ApplicationContextAware but it didn't helped me. I am getting applicationContext as null in my kafka consumer and hence I am not able to get bean from spring container. First time applicationContext is getting set properly but when context loads second time it set to null.
Below are the details of my application in short
```
@SpringBootApplication
@ComponentScan({"com.xyz.config_assign.service"})
public class ConfigAssignServer {
private static Logger log = LoggerFactory.getLogger(ConfigAssignServer.class);
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigAssignServer.class, args);
log.info("Started ConfigAssign Server!!! AppName= {} ", applicationContext.getApplicationName());
QkafkaClient.loadConfiguration();
}
}
```
All my application classes are present in com.xyz.config\_assign.service so no issue of bean scanning problem. It worked well before I add Kafka consumer
My ApplicationContextProvider which is using famous ApplicationContextAware
```
@Component
public class ApplicationContextProvider implements ApplicationContextAware{
public static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextProvider.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
```
And now my kafkaconsumer
```
public class ConfigAssignmentAssetTagChangeKafkaTopicProcessor implements BatchTopicProcessor<String, String> {
private Logger log = LoggerFactory.getLogger(ConfigAssignmentAssetTagChangeKafkaTopicProcessor.class);
private AssignConfigServiceImpl assignConfigServiceImpl;
public ConfigAssignmentAssetTagChangeKafkaTopicProcessor(){
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
assignConfigServiceImpl = applicationContext.getBean(AssignConfigServiceImpl.class);
}
@Override
public void handleError(ConsumerRecords<String, String> arg0, Exception arg1) {
// TODO Auto-generated method stub
}
@Override
public void process(ConsumerRecords<String, String> records, long arg1) {}
}
```
And the service I want to inject into kafka consumer is
```
@Service
public class AssignConfigServiceImpl implements AssignConfigService {
private Logger log = LoggerFactory.getLogger(AssignConfigServiceImpl.class);
@Autowired
private ConfigProfileDBService dbService;
public boolean assignConfigToAgents(List<UUID> agentList, long customerId) {
List<AgentConfigurationProfile> configProfiles =
dbService.getConfigurationProfilesForCustomer(customerId);
boolean isAssignSuccessful = assignConfigToAgents(agentList, customerId, configProfiles);
log.info("Config Assignment status ={}", isAssignSuccessful);
return isAssignSuccessful;
}
```
The other service I used is
```
@Service
public class ConfigProfileDBService implements DBService {
private static Logger log = LoggerFactory.getLogger(ConfigProfileDBService.class);
@Autowired
private JdbcTemplate jdbcTemplate;
public List<AgentConfigurationProfile> getConfigurationProfilesForCustomer(Long customerId) {
List<AgentConfigurationProfile> agentConfigList;
}
```
}
Can someone please let me know what went wrong, I tried multiple online solution but didn't worked for me. Thanks in advance.
Note : I haven't initialized any class using new operator. | 2020/02/26 | [
"https://Stackoverflow.com/questions/60408730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8086483/"
] | Based on clarifications in question and comments, and assuming its impossible to move KafkaConsumer to be spring managed (which is I believe the best solution):
`@Autowired` won't work in KafkaConsumer, so no need to put that annotation.
I assume that you're getting null for Application context in this line:
```
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
```
This means that `ApplicationContextProvider#setApplicationContext` has not been called by the time you create Kafka Consumer. Spring in addition to injection also manages lifecyle of the managed objects. Since you're not in spring, you're "on-your-own" and you have to make sure that Application Context gets created first and only after that create other objects (like Kafka Consumer for example).
When application context starts it adds beans one by one at some point, among other beans it also gets to the `ApplicationContextProvider` and calls its setter. | My main problem was my spring context was being loaded twice. As I printed every class's class loader I found that my Application was running twice. (i.e. when I debug in intellij after pressing F9 I was again landing up on same line i.e.
```
ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigAssignServer.class, args);
```
My problem was in pom.xml. I removed below dependency from my pom and it worked.
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
```
Please check for your dependencies. Hope it will help someone. Enjoy coding :) |
20,131,144 | I'm running the following query using NHibernate:
```
var query = session.QueryOver<TaskMeeting>()
.JoinQueryOver(x => x.Task)
.Where(x => x.CloseOn == null)
.List();
```
Which then generates the following SQL:
```
SELECT
this_.Id as Id89_1_,
this_.TaskMeetingTypeID as TaskMeet2_89_1_,
this_.DateTime as DateTime89_1_,
this_.Description as Descript4_89_1_,
this_.TaskID as TaskID89_1_,
ltaskalias1_.Id as Id87_0_,
ltaskalias1_.Title as Title87_0_,
ltaskalias1_.Description as Descript7_87_0_,
ltaskalias1_.CreatedOn as CreatedOn87_0_,
ltaskalias1_.LastUpdated as LastUpda9_87_0_,
ltaskalias1_.ClosedOn as ClosedOn87_0_,
FROM
dbo.[TaskMeeting] this_
inner join
dbo.[Task] ltaskalias1_
on this_.TaskID=ltaskalias1_.Id
WHERE
ltaskalias1_.ClosedOn is null
```
Is pulling joined table information normal behavior? I would think it should only be selecting data pertaining to the root entity unless I specify a `.Fetch` clause or manually select the data.
I'm using `Fluent NHibernate` for the class mappings, but they are basic mappings for something like this, no eager loading specified - just simple `Map` and `References` where appropriate.
I've tried removing the where clause thinking perhaps that was the cause. The additional `SELECT`s continue to persist unless I remove the join itself. | 2013/11/21 | [
"https://Stackoverflow.com/questions/20131144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467172/"
] | The way you queried your data, you get back a generic IList<> containing TaskMeeting entities. So it's normal for NHibernate to query all columns of your TaskMeeting table to put that data into your TaskMeeting entity properties. But i guess that is known already.
But because you want to restrict the data through another table you have to make a join to it. And that's the expensive part for the database server. Querying those few additional columns is peanuts compared to it and NHibernate might as well use the data to fill the Task references in your TaskMeeting entities.
At least that's how i understand it. | The quick answer is you told it to. You called JoinQueryOver which is going to create a join query on the task.
An easier way to get only what you want is to create a linq query and project only the fields you want into am anonymous type. That will generate a query with only the columns declared in the anonymous type.
var meetings =
from m in session.Query ()
where m.Task.ClosedOn <> null
select new { somefield = m.Task.Name, ...}; |
14,150,565 | The following code is to add the font tag to every character, but it don't work
```
Function AddFontTag (counter)
Do While Len (counter) < 7
newStr = newStr & "<font>" & Left (counter, i) & "</font>"
i = i + 1
Loop
AddFontTag = newStr
End Function
```
Because i'm not skilled in classic asp, such as variable scope, syntax. Does anyone know what's the problems of the above code?
thanks | 2013/01/04 | [
"https://Stackoverflow.com/questions/14150565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925552/"
] | Your `do..while` loop is an infinite loop - assuming `counter` is a string variable, its length never changes so if `Len(counter)` is less than `7` upon entering the function, it'll always stay less than `7` so your function never exits.
Your `newStr` variable is undefined - this works in VBScript but it's really bad practice and it's a source of countless errors. Is it a global variable or is it supposed to be a local? (It looks like a local.) | I'm not sure of how your 7 character limit applies, but for a general approach the following will do what you need for any length string:
```vb
function AddFontTag(byval str)
AddFontTag = Empty
do while len(str) <> 0
' get next character
dim c: c = left(str, 1)
' reduce original string
str = right(str, len(str) - 1)
' build up output string
AddFontTag = AddFontTag & "<font>" & c & "</font>"
loop
end function
```
The example
```
dim test: test = AddFontTag("a test")
Response.Write test
```
will give you
>
> <font>a</font><font> </font><font>t</font><font>e</font><font>s</font><font>t</font>
>
>
>
If you only want to apply this to strings of length less than 7 you can add
```
if len(str) > 6 then
exit function
end if
```
before the while loop or
```
str = left(str, 6)
```
if you just want to apply it to the first 6 characters of any length string |
14,150,565 | The following code is to add the font tag to every character, but it don't work
```
Function AddFontTag (counter)
Do While Len (counter) < 7
newStr = newStr & "<font>" & Left (counter, i) & "</font>"
i = i + 1
Loop
AddFontTag = newStr
End Function
```
Because i'm not skilled in classic asp, such as variable scope, syntax. Does anyone know what's the problems of the above code?
thanks | 2013/01/04 | [
"https://Stackoverflow.com/questions/14150565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925552/"
] | Your `do..while` loop is an infinite loop - assuming `counter` is a string variable, its length never changes so if `Len(counter)` is less than `7` upon entering the function, it'll always stay less than `7` so your function never exits.
Your `newStr` variable is undefined - this works in VBScript but it's really bad practice and it's a source of countless errors. Is it a global variable or is it supposed to be a local? (It looks like a local.) | your codes is looping without a condition to EXIT the looping.
try this... hope it helps.
```
Function AddFontTag (counter)
dim i,newStr,max
max=7
Do While Len (counter) < max
newStr = newStr & "<font>" & Left (counter, i) & "-" & "</font>"
i = i + 1
if i = max-1 then exit Do
Loop
AddFontTag = newStr
End Function
'to check the results
response.write AddFontTag ("params")
```
you will get
`<font>-</font><font>p-</font><font>pa-</font><font>par-</font><font>para-</font><font>param-</font>` |
14,150,565 | The following code is to add the font tag to every character, but it don't work
```
Function AddFontTag (counter)
Do While Len (counter) < 7
newStr = newStr & "<font>" & Left (counter, i) & "</font>"
i = i + 1
Loop
AddFontTag = newStr
End Function
```
Because i'm not skilled in classic asp, such as variable scope, syntax. Does anyone know what's the problems of the above code?
thanks | 2013/01/04 | [
"https://Stackoverflow.com/questions/14150565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925552/"
] | I'm not sure of how your 7 character limit applies, but for a general approach the following will do what you need for any length string:
```vb
function AddFontTag(byval str)
AddFontTag = Empty
do while len(str) <> 0
' get next character
dim c: c = left(str, 1)
' reduce original string
str = right(str, len(str) - 1)
' build up output string
AddFontTag = AddFontTag & "<font>" & c & "</font>"
loop
end function
```
The example
```
dim test: test = AddFontTag("a test")
Response.Write test
```
will give you
>
> <font>a</font><font> </font><font>t</font><font>e</font><font>s</font><font>t</font>
>
>
>
If you only want to apply this to strings of length less than 7 you can add
```
if len(str) > 6 then
exit function
end if
```
before the while loop or
```
str = left(str, 6)
```
if you just want to apply it to the first 6 characters of any length string | your codes is looping without a condition to EXIT the looping.
try this... hope it helps.
```
Function AddFontTag (counter)
dim i,newStr,max
max=7
Do While Len (counter) < max
newStr = newStr & "<font>" & Left (counter, i) & "-" & "</font>"
i = i + 1
if i = max-1 then exit Do
Loop
AddFontTag = newStr
End Function
'to check the results
response.write AddFontTag ("params")
```
you will get
`<font>-</font><font>p-</font><font>pa-</font><font>par-</font><font>para-</font><font>param-</font>` |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | Hint: Mulitply by
$$
\frac{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}
$$ | You can write $\sqrt[3]{1+x}=1+\frac{1}{3}x+O(x^2)$ for $x$ near zero.
So $$\sqrt[3]{n^2+3}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+3/n^2} = n^{2/3}+\frac{1}{3}\frac{3}{n^{4/3}} + O(1/n^{10/3})$$
Similarly, $$\sqrt[3]{n^2+5}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+5/n^2} = n^{2/3}+\frac{1}{3}\frac{5}{n^{4/3}} + O(1/n^{10/3})$$
So $$\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}=\frac{2}{3}n^{-4/3}+O(n^{-10/3})$$
---
Alternatively, you can use the mean value theorem. Let $f(x)=\sqrt[3]{x}$. Then for any $n$ there is a $c\_n\in [n^2+3,n^2+5]$ such that:
$$f(n^2+5)-f(n^2+3)=((n^2+5)-(n^2+3))f'(c\_n)=2f'(c\_n)$$
Now, show that $0< f'(c\_n)\leq f'(n^2+2)$ and $f'(n^2+2)\to 0.$ |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | Hint: Mulitply by
$$
\frac{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}
$$ | One developes an intuition that as $n^2$ becomes large the $+5$ and $-3$ become negligible and the whole thing becomes but how to prove it...
Well we can is eliminate the difference of square roots by multiplying by the compliment so we can probably do the same for cube roots.
I.e. $(\sqrt[3]a - \sqrt[3]b)(\sqrt[3]a^2 + \sqrt[3]a\sqrt[3]b+\sqrt[3]b^2) = a - b$.
So $\lim (\sqrt[3]{n^2 + 5} - \sqrt[3]{n^2 + 3})=$
$\lim (\sqrt[3]{n^2 + 5} - \sqrt[3]{n^2 + 3})\frac {\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}{\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}=$
$\lim \frac{(n^2 + 5)-(n^2 +3)}{\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}=$
$\lim \frac{2}{\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}=0$ |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | Hint: Mulitply by
$$
\frac{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}
$$ | $\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}
$
Since
$a^3-b^3
=(a-b)(a^2+ab+b^2)
$,
$a-b
=\dfrac{a^3-b^3}{a^2+ab+b^2}
$.
Therefore
$a^{1/3}-b^{1/3}
=\dfrac{a-b}{a^{2/3}+a^{1/3}b^{1/3}+b^{2/3}}
$.
Since,
for $x > 0$,
$1 < (1+x)^{1/3}
< 1+x/3
$
(cube both sides),
we have,
if $u > 0$,
$n^{2/3}
< (n^2+u)^{1/3}
= n^{2/3}(1+u/n^2)^{1/3}
< n^{2/3}(1+u/(3n^2))
= n^{2/3}+u/(3n^{4/3}))
$.
Therefore,
if $a = n^2+u$
and $b = n^2+v$,
$\begin{array}\\
3n^{4/3}
&< a^{2/3}+a^{1/3}b^{1/3}+b^{2/3}\\
&< (n^{2/3}+u/(3n^{4/3})))^2+(n^{2/3}+u/(3n^{4/3})))(n^{2/3}+v/(3n^{4/3})))+(n^{2/3}+v/(3n^{4/3})))^2\\
&= n^{4/3}( (1+u/(3n^2))^2+(1+u/(3n^2))(1+v/(3n^2))+(1+v/(3n^2))^2)\\
&= n^{4/3}(3+(2u+u+v+2v)/(3n^2)+(u^2+uv+v^2)/(3n^2)^2\\
&= 3n^{4/3}(1+(u+v)/(3n^2)+(u^2+uv+v^2)/(3n^4))\\
\end{array}
$
Therefore
$$a^{1/3}-b^{1/3}
=\dfrac{a-b}{a^{2/3}+a^{1/3}b^{1/3}+b^{2/3}}
< \dfrac{u-v}{3n^{4/3}}
$$
and
$$a^{1/3}-b^{1/3}
> \dfrac{u-v}{3n^{4/3}(1+(u+v)/(3n^2)+(u^2+uv+v^2)/(3n^4))}.
$$
Immediately we have that
$\lim\_{n \to \infty} a^{1/3}-b^{1/3}
=0
$.
More precisely,
we also have
$$\dfrac{u-v}{3}
> n^{4/3}(a^{1/3}-b^{1/3})
>\dfrac{u-v}{3}\dfrac1{1+(u+v)/(3n^2)+(u^2+uv+v^2)/(3n^4)}
$$
so that
$$\lim\_{n \to \infty} n^{4/3}(a^{1/3}-b^{1/3})
=(u-v)/3
=2/3
$$
since
$u=5, v=3$.
Note:
We can get explicit bounds
by using
$\dfrac1{1+x}
\gt 1-x
$
for $0 < x < 1$
and choosing
$n$ large enough
compared with
$u$ and $v$. |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | Hint: Mulitply by
$$
\frac{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}
$$ | If you have the Mean Value Theorem available, and if you know that the derivative of $f(x)=x^{1/3}$ is $f'(x)={1\over3}x^{-2/3}$, then note that
$$\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}=2{f(n^2+5)-f(n^2+3)\over(n^2+5)-(n^2+3)}=2f'(c\_n)={2\over3c\_n^{2/3}}$$
for some $c\_n\in(n^2+3,n^5+5)$. Clearly $c\_n\to\infty$ as $n\to\infty$, so we get
$$\lim\_{n\to\infty}(\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3})=\lim\_{n\to\infty}{2\over3c\_n^{2/3}}=0$$ |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | You can write $\sqrt[3]{1+x}=1+\frac{1}{3}x+O(x^2)$ for $x$ near zero.
So $$\sqrt[3]{n^2+3}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+3/n^2} = n^{2/3}+\frac{1}{3}\frac{3}{n^{4/3}} + O(1/n^{10/3})$$
Similarly, $$\sqrt[3]{n^2+5}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+5/n^2} = n^{2/3}+\frac{1}{3}\frac{5}{n^{4/3}} + O(1/n^{10/3})$$
So $$\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}=\frac{2}{3}n^{-4/3}+O(n^{-10/3})$$
---
Alternatively, you can use the mean value theorem. Let $f(x)=\sqrt[3]{x}$. Then for any $n$ there is a $c\_n\in [n^2+3,n^2+5]$ such that:
$$f(n^2+5)-f(n^2+3)=((n^2+5)-(n^2+3))f'(c\_n)=2f'(c\_n)$$
Now, show that $0< f'(c\_n)\leq f'(n^2+2)$ and $f'(n^2+2)\to 0.$ | One developes an intuition that as $n^2$ becomes large the $+5$ and $-3$ become negligible and the whole thing becomes but how to prove it...
Well we can is eliminate the difference of square roots by multiplying by the compliment so we can probably do the same for cube roots.
I.e. $(\sqrt[3]a - \sqrt[3]b)(\sqrt[3]a^2 + \sqrt[3]a\sqrt[3]b+\sqrt[3]b^2) = a - b$.
So $\lim (\sqrt[3]{n^2 + 5} - \sqrt[3]{n^2 + 3})=$
$\lim (\sqrt[3]{n^2 + 5} - \sqrt[3]{n^2 + 3})\frac {\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}{\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}=$
$\lim \frac{(n^2 + 5)-(n^2 +3)}{\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}=$
$\lim \frac{2}{\sqrt[3]{n^2 + 5}^2 + \sqrt[3]{n^2 + 5}\sqrt[3]{n^2 + 3}+\sqrt[3]{n^2 + 3}^2}=0$ |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | You can write $\sqrt[3]{1+x}=1+\frac{1}{3}x+O(x^2)$ for $x$ near zero.
So $$\sqrt[3]{n^2+3}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+3/n^2} = n^{2/3}+\frac{1}{3}\frac{3}{n^{4/3}} + O(1/n^{10/3})$$
Similarly, $$\sqrt[3]{n^2+5}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+5/n^2} = n^{2/3}+\frac{1}{3}\frac{5}{n^{4/3}} + O(1/n^{10/3})$$
So $$\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}=\frac{2}{3}n^{-4/3}+O(n^{-10/3})$$
---
Alternatively, you can use the mean value theorem. Let $f(x)=\sqrt[3]{x}$. Then for any $n$ there is a $c\_n\in [n^2+3,n^2+5]$ such that:
$$f(n^2+5)-f(n^2+3)=((n^2+5)-(n^2+3))f'(c\_n)=2f'(c\_n)$$
Now, show that $0< f'(c\_n)\leq f'(n^2+2)$ and $f'(n^2+2)\to 0.$ | $\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}
$
Since
$a^3-b^3
=(a-b)(a^2+ab+b^2)
$,
$a-b
=\dfrac{a^3-b^3}{a^2+ab+b^2}
$.
Therefore
$a^{1/3}-b^{1/3}
=\dfrac{a-b}{a^{2/3}+a^{1/3}b^{1/3}+b^{2/3}}
$.
Since,
for $x > 0$,
$1 < (1+x)^{1/3}
< 1+x/3
$
(cube both sides),
we have,
if $u > 0$,
$n^{2/3}
< (n^2+u)^{1/3}
= n^{2/3}(1+u/n^2)^{1/3}
< n^{2/3}(1+u/(3n^2))
= n^{2/3}+u/(3n^{4/3}))
$.
Therefore,
if $a = n^2+u$
and $b = n^2+v$,
$\begin{array}\\
3n^{4/3}
&< a^{2/3}+a^{1/3}b^{1/3}+b^{2/3}\\
&< (n^{2/3}+u/(3n^{4/3})))^2+(n^{2/3}+u/(3n^{4/3})))(n^{2/3}+v/(3n^{4/3})))+(n^{2/3}+v/(3n^{4/3})))^2\\
&= n^{4/3}( (1+u/(3n^2))^2+(1+u/(3n^2))(1+v/(3n^2))+(1+v/(3n^2))^2)\\
&= n^{4/3}(3+(2u+u+v+2v)/(3n^2)+(u^2+uv+v^2)/(3n^2)^2\\
&= 3n^{4/3}(1+(u+v)/(3n^2)+(u^2+uv+v^2)/(3n^4))\\
\end{array}
$
Therefore
$$a^{1/3}-b^{1/3}
=\dfrac{a-b}{a^{2/3}+a^{1/3}b^{1/3}+b^{2/3}}
< \dfrac{u-v}{3n^{4/3}}
$$
and
$$a^{1/3}-b^{1/3}
> \dfrac{u-v}{3n^{4/3}(1+(u+v)/(3n^2)+(u^2+uv+v^2)/(3n^4))}.
$$
Immediately we have that
$\lim\_{n \to \infty} a^{1/3}-b^{1/3}
=0
$.
More precisely,
we also have
$$\dfrac{u-v}{3}
> n^{4/3}(a^{1/3}-b^{1/3})
>\dfrac{u-v}{3}\dfrac1{1+(u+v)/(3n^2)+(u^2+uv+v^2)/(3n^4)}
$$
so that
$$\lim\_{n \to \infty} n^{4/3}(a^{1/3}-b^{1/3})
=(u-v)/3
=2/3
$$
since
$u=5, v=3$.
Note:
We can get explicit bounds
by using
$\dfrac1{1+x}
\gt 1-x
$
for $0 < x < 1$
and choosing
$n$ large enough
compared with
$u$ and $v$. |
2,137,187 | I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit? | 2017/02/09 | [
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] | You can write $\sqrt[3]{1+x}=1+\frac{1}{3}x+O(x^2)$ for $x$ near zero.
So $$\sqrt[3]{n^2+3}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+3/n^2} = n^{2/3}+\frac{1}{3}\frac{3}{n^{4/3}} + O(1/n^{10/3})$$
Similarly, $$\sqrt[3]{n^2+5}=\sqrt[3]{n^2}\cdot \sqrt[3]{1+5/n^2} = n^{2/3}+\frac{1}{3}\frac{5}{n^{4/3}} + O(1/n^{10/3})$$
So $$\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}=\frac{2}{3}n^{-4/3}+O(n^{-10/3})$$
---
Alternatively, you can use the mean value theorem. Let $f(x)=\sqrt[3]{x}$. Then for any $n$ there is a $c\_n\in [n^2+3,n^2+5]$ such that:
$$f(n^2+5)-f(n^2+3)=((n^2+5)-(n^2+3))f'(c\_n)=2f'(c\_n)$$
Now, show that $0< f'(c\_n)\leq f'(n^2+2)$ and $f'(n^2+2)\to 0.$ | If you have the Mean Value Theorem available, and if you know that the derivative of $f(x)=x^{1/3}$ is $f'(x)={1\over3}x^{-2/3}$, then note that
$$\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}=2{f(n^2+5)-f(n^2+3)\over(n^2+5)-(n^2+3)}=2f'(c\_n)={2\over3c\_n^{2/3}}$$
for some $c\_n\in(n^2+3,n^5+5)$. Clearly $c\_n\to\infty$ as $n\to\infty$, so we get
$$\lim\_{n\to\infty}(\sqrt[3]{n^2+5}-\sqrt[3]{n^2+3})=\lim\_{n\to\infty}{2\over3c\_n^{2/3}}=0$$ |
32,500 | Could you please explain why the syntax in the following stanza is wrong?
>
> Surrounded
>
> by that sturdy assertiveness
>
> that walled England the din
>
> of traffic in my mind quietens,
>
>
> | 2011/07/02 | [
"https://english.stackexchange.com/questions/32500",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/10536/"
] | There is nothing I can see wrong in the syntax of that stanza. In fact, unlike much poetry, there is no serious lexical ambiguity; and with a single comma it would render just fine as a prose sentence:
>
> Surrounded by that sturdy assertiveness that walled England, the din of traffic in my mind quietens.
>
>
>
Take "that sturdy assertiveness that walled England" to mean "the trait that formed a wall around England, which I will call 'sturdy assertiveness'" ... and thus shielded [as I am from such assertiveness], the noise of traffic in my mind becomes still. | There are two slightly different answers to your question. As a matter of formal grammar it is missing a comma.
```
Surrounded
by that sturdy assertiveness
that walled England **[COMMA]** the din
of traffic in my mind quietens,
```
However, there is something else worth pointing out. One of the things that sets poetry apart from prose is that it uses the form of words to convey meaning besides the strict semantics. This is true of prose to some extent, but it is a more important part of poetry. In simply poetry for example, rhyming schemes give a cadence to the meaning that enhances the reading pleasure.
In the example you gave the structure is rather awkward. The third line contains an obvious semantic break that isn't reflected well in the structure. I'd suggest this would be better:
```
Surrounded
by that sturdy assertiveness
that walled England,
the din of traffic in my mind quietens,
```
You might even break the fourth line into two, as a kind of ragged cadence seems to be the author's intent.
I'd also say it is an interesting sentence. I think it is unusual the way there is a huge pile of words before you hit the verb. As you are reading all the qualifiers you are thinking, and thinking "what is the point of this sentence." I suppose it builds a sense of anticipation.
Can the OP share the source? |
33,061,827 | This question has been asked before: [Start the thumbnails from the left of the slideshow instead of the middle](https://stackoverflow.com/q/30867297/4220943), but there's no answer yet.
I'm trying to get the thumbnail bar at the bottom to align the thumbnails to the left when fotorama is loaded. By default, it's centered. | 2015/10/11 | [
"https://Stackoverflow.com/questions/33061827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220943/"
] | As I answered it here, [Start the thumbnails from the left of the slideshow instead of the middle](https://stackoverflow.com/questions/30867297/start-the-thumbnails-from-the-left-of-the-sldieshow-instead-of-middle-of-the-sli/33062159#33062159), It is simple. The fotorama plugin uses css3 transform property to align thumbnails under the main image. just calculate the parent width and children container width using jQuery and if the parent is wider than children container, make a transform across X axis to shift all thumbnails to the left.
**EDIT:**
I made an edit that when you click on on arrows or thumbnails, it also does the alignment fix!
```
$(document).ready(function() {
var pw = $('.fotorama__nav--thumbs').innerWidth();
var cw = $('.fotorama__nav__shaft').innerWidth();
var offset = pw -cw;
var negOffset = (-1 * offset) / 2;
var totalOffset = negOffset + 'px';
if (pw > cw) {
$('.fotorama__nav__shaft').css('transform', 'translate3d(' + totalOffset + ', 0, 0)');
}
$('.fotorama__nav__frame--thumb, .fotorama__arr, .fotorama__stage__frame, .fotorama__img, .fotorama__stage__shaft').click(function() {
if (pw > cw) {
$('.fotorama__nav__shaft').css('transform', 'translate3d(' + totalOffset + ', 0, 0)');
}
});
});
``` | Just add to CSS that code:
```
.fotorama__nav {
text-align: left or right !important;
}
``` |
33,061,827 | This question has been asked before: [Start the thumbnails from the left of the slideshow instead of the middle](https://stackoverflow.com/q/30867297/4220943), but there's no answer yet.
I'm trying to get the thumbnail bar at the bottom to align the thumbnails to the left when fotorama is loaded. By default, it's centered. | 2015/10/11 | [
"https://Stackoverflow.com/questions/33061827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220943/"
] | I've just set
```
.fotorama__nav__shaft {
display: block;
}
``` | Just add to CSS that code:
```
.fotorama__nav {
text-align: left or right !important;
}
``` |
47,171 | I'm running an alter table, alter column on a table with nearly 30 million rows and SQL Azure fails after approximately 18 minutes saying that `The session has been terminated because of excessive transaction log space usage. Try modifying fewer rows in a single transaction.`
I'm guessing that it's not possible to break this down into modifying fewer rows at a time, so I'm wondering what my options are for making this change to the database. SQL Azure will not let me change the size of the transaction log (limited to 1gb).
I'm guessing that my best bet is going to be creating a new table with the new layout, migrating the data across into that one, deleting the original table and then renaming the new table to match the name of the old table. If that's the case, how is it best to structure those commands?
Scheduled downtime for our system is not an issue currently so this operation can take as long as it needs to. | 2013/07/28 | [
"https://dba.stackexchange.com/questions/47171",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/574/"
] | You will want to load your data into a new table, doing this in small batches, then drop the existing table. I put together a quick example using the Sales.Customer table in AdventureWorks, something similar should work for you also.
First, create your new table, complete with the new datatype you want to use:
```
CREATE TABLE [Sales].[Currency_New](
[CurrencyCode] [nchar](4) NOT NULL,
[Name] [varchar](128) NOT NULL,
[ModifiedDate] [datetime] NOT NULL,
CONSTRAINT [PK_Currency_New_CurrencyCode] PRIMARY KEY CLUSTERED
(
[CurrencyCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
```
Then, insert your records and define your batch. I am using 10 here, but you will likely want to use something larger, say 10,000 rows at a time. For 30MM rows I'd even suggest you go to 100k row batch size at a time, that's the limit I typically used with larger tables:
```
DECLARE @RowsInserted INT, @InsertVolume INT
SET @RowsInserted = 1
SET @InsertVolume = 10 --Set to # of rows
WHILE @RowsInserted > 0
BEGIN
INSERT INTO [Sales].[Currency_New] ([CurrencyCode]
,[Name]
,[ModifiedDate])
SELECT TOP (@InsertVolume)
SC.[CurrencyCode]
,SC.[Name]
,SC.[ModifiedDate]
FROM [Sales].[Currency] AS SC
LEFT JOIN [Sales].[Currency_New] AS SCN
ON SC.[CurrencyCode] = SCN.[CurrencyCode]
WHERE SCN.[CurrencyCode] IS NULL
SET @RowsInserted = @@ROWCOUNT
END
```
I usually do a sanity check and verify the rowcounts are the same before cleaning up:
```
SELECT COUNT(*) FROM [Sales].[Currency]
SELECT COUNT(*) FROM [Sales].[Currency_New]
```
Once you are confident you have migrated your data, you can drop the original table:
```
DROP TABLE [Sales].[Currency]
```
Last step, rename the new table, so that users don't have to change any code:
```
EXEC sp_rename '[Sales].[Currency_New]', '[Sales].[Currency]';
GO
```
I don't know how long this will take. I'd suggest you try doing this when you have a clear maintenance window and users aren't connected.
HTH | I'm on a phone right now but I just answered a very similar question on StackOverflow a few days ago. The column names are probably not applicable to you, but here's what I gave.
```
SELECT
[ID],
[Title],
[Abstract],
[Value],
[UserID],
[GroupID],
[Date],
[Views],
[Hates],
[Likes],
[Source]
INTO dbo.[News-News_Newest]
FROM [dbo].[News-News];
DROP TABLE [dbo].[News-News_Newest];
GO
EXEC sp_rename '[News-News_Newest]' , '[News-News]';
GO
ALTER TABLE [News-News]
ADD CONSTRAINT PK_News_ID PRIMARY KEY CLUSTERED (ID ASC);
```
The same caveat applies to you as we'll. script out your foreign key relationships too and then rebuild the. After the load with check check |
914,814 | ```
class Object
attr_reader :foo
def initialize
@foo = 'bar'
end
end
Object.new.foo # => 'bar'
''.foo # => nil
//.foo # => nil
[].foo # => nil
```
I want them all to return `'bar'`
Am aware that you can do this already:
```
class Object
def foo
'bar'
end
end
```
But I specifically want to initialize a state variable. Also note that this doesn't work.
```
class String
alias_method :old_init, :initialize
def initialize(*args)
super
old_init(*args)
end
end
class Object
attr_reader :foo
def initialize
@foo = 'bar'
super
end
end
''.foo # => nil
```
Nor does this:
```
class String
attr_reader :foo
def initialize
@foo = 'bar'
end
end
''.instance_variables # => []
```
I'm beginning to think that this isn't actually possible. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113019/"
] | If the thing you're trying to return (here, `'bar'`) requires much more setup cost than a small String, you could use the memoized version of [HermanD's answer](https://stackoverflow.com/questions/914814/in-ruby-how-can-i-initialize-instance-variables-in-new-objects-of-core-classes-c/914838#914838):
```
class Object
def foo
@foo ||= begin
'bar' # something far more complicated than just "'bar'"
end
end
end
```
You could even use the memoization for cheap stuff like Strings if you *really* need the instance variable to be set (for some reason that I can't quite think of at them moment):
```
class Object
def foo
@foo ||= 'bar'
end
end
``` | It's not an instance variable, but will meet the requirements of your example
```
class Object
def foo
'bar'
end
end
``` |
914,814 | ```
class Object
attr_reader :foo
def initialize
@foo = 'bar'
end
end
Object.new.foo # => 'bar'
''.foo # => nil
//.foo # => nil
[].foo # => nil
```
I want them all to return `'bar'`
Am aware that you can do this already:
```
class Object
def foo
'bar'
end
end
```
But I specifically want to initialize a state variable. Also note that this doesn't work.
```
class String
alias_method :old_init, :initialize
def initialize(*args)
super
old_init(*args)
end
end
class Object
attr_reader :foo
def initialize
@foo = 'bar'
super
end
end
''.foo # => nil
```
Nor does this:
```
class String
attr_reader :foo
def initialize
@foo = 'bar'
end
end
''.instance_variables # => []
```
I'm beginning to think that this isn't actually possible. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113019/"
] | This **is** possible.
```
class Object
class << self
Kernel.send :define_method, :foo do #Object.send to be more restrictive
@foo = 'bar'
end
end
end
```
.
```
irb(main):023:0> class Object
irb(main):024:1> class << self
irb(main):025:2> Kernel.send :define_method, :foo do
irb(main):026:3* @foo = 'bar'
irb(main):027:3> end
irb(main):028:2> end
irb(main):029:1> end
=> #<Proc:0x00007f5ac89db168@(irb):25>
irb(main):030:0> x = Object.new
=> #<Object:0x7f5ac89d6348>
irb(main):031:0> x.foo
=> "bar"
irb(main):032:0> [].foo
=> "bar"
irb(main):033:0> //.foo
=> "bar"
```
It's important to understand eigenclasses. Every class is implemented mysteriously by the Ruby interpreter as a hidden class type:
```
irb(main):001:0> class Object
irb(main):002:1> def eigenclass
irb(main):003:2> class << self; self; end
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> x = Object.new
=> #<Object:0x7fb6f285cd10>
irb(main):007:0> x.eigenclass
=> #<Class:#<Object:0x7fb6f285cd10>>
irb(main):008:0> Object.eigenclass
=> #<Class:Object>
irb(main):009:0> Object.class
=> Class
```
So, in your example, when you're trying to call foo on your objects, it's operating on the class `#<Object:0x7fb6f285cd10>`. However, what you want it to operate on is the secret class `#<Class:#<Object:0x7fb6f285cd10>>`
I hope this helps! | It's not an instance variable, but will meet the requirements of your example
```
class Object
def foo
'bar'
end
end
``` |
914,814 | ```
class Object
attr_reader :foo
def initialize
@foo = 'bar'
end
end
Object.new.foo # => 'bar'
''.foo # => nil
//.foo # => nil
[].foo # => nil
```
I want them all to return `'bar'`
Am aware that you can do this already:
```
class Object
def foo
'bar'
end
end
```
But I specifically want to initialize a state variable. Also note that this doesn't work.
```
class String
alias_method :old_init, :initialize
def initialize(*args)
super
old_init(*args)
end
end
class Object
attr_reader :foo
def initialize
@foo = 'bar'
super
end
end
''.foo # => nil
```
Nor does this:
```
class String
attr_reader :foo
def initialize
@foo = 'bar'
end
end
''.instance_variables # => []
```
I'm beginning to think that this isn't actually possible. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113019/"
] | This **is** possible.
```
class Object
class << self
Kernel.send :define_method, :foo do #Object.send to be more restrictive
@foo = 'bar'
end
end
end
```
.
```
irb(main):023:0> class Object
irb(main):024:1> class << self
irb(main):025:2> Kernel.send :define_method, :foo do
irb(main):026:3* @foo = 'bar'
irb(main):027:3> end
irb(main):028:2> end
irb(main):029:1> end
=> #<Proc:0x00007f5ac89db168@(irb):25>
irb(main):030:0> x = Object.new
=> #<Object:0x7f5ac89d6348>
irb(main):031:0> x.foo
=> "bar"
irb(main):032:0> [].foo
=> "bar"
irb(main):033:0> //.foo
=> "bar"
```
It's important to understand eigenclasses. Every class is implemented mysteriously by the Ruby interpreter as a hidden class type:
```
irb(main):001:0> class Object
irb(main):002:1> def eigenclass
irb(main):003:2> class << self; self; end
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> x = Object.new
=> #<Object:0x7fb6f285cd10>
irb(main):007:0> x.eigenclass
=> #<Class:#<Object:0x7fb6f285cd10>>
irb(main):008:0> Object.eigenclass
=> #<Class:Object>
irb(main):009:0> Object.class
=> Class
```
So, in your example, when you're trying to call foo on your objects, it's operating on the class `#<Object:0x7fb6f285cd10>`. However, what you want it to operate on is the secret class `#<Class:#<Object:0x7fb6f285cd10>>`
I hope this helps! | If the thing you're trying to return (here, `'bar'`) requires much more setup cost than a small String, you could use the memoized version of [HermanD's answer](https://stackoverflow.com/questions/914814/in-ruby-how-can-i-initialize-instance-variables-in-new-objects-of-core-classes-c/914838#914838):
```
class Object
def foo
@foo ||= begin
'bar' # something far more complicated than just "'bar'"
end
end
end
```
You could even use the memoization for cheap stuff like Strings if you *really* need the instance variable to be set (for some reason that I can't quite think of at them moment):
```
class Object
def foo
@foo ||= 'bar'
end
end
``` |
91,576 | Are the Jazz Masses, like the ones Mary Lou Williams and Joe Masters composed still licit forms of the Mass or have they been officially suppressed at some point in the last 50-60 years? | 2022/06/14 | [
"https://christianity.stackexchange.com/questions/91576",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/4/"
] | The 1967 instruction *[Musicam Sacram](https://www.vatican.va/archive/hist_councils/ii_vatican_council/documents/vat-ii_instr_19670305_musicam-sacram_en.html)* stated
>
> In permitting and using musical instruments, the culture and traditions of individual peoples must be taken into account. However, those instruments which are, by common opinion and use, suitable for secular music only, are to be altogether prohibited from every liturgical celebration and from popular devotions.
>
>
>
Note that this was written 8 years before *Mary Lou's Mass*, and the same year as Masters' *The Jazz Mass*.
In the 2003 *[Chirograph for the Centenary of the Motu Proprio "Tra le Sollecitudini" On Sacred Music](https://www.vatican.va/content/john-paul-ii/en/letters/2003/documents/hf_jp-ii_let_20031203_musica-sacra.html)* St John Paul II wrote:
>
> With regard to compositions of liturgical music, I make my own the "general rule" that St Pius X formulated in these words: "The more closely a composition for church approaches in its movement, inspiration and savour the Gregorian melodic form, the more sacred and liturgical it becomes; and the more out of harmony it is with that supreme model, the less worthy it is of the temple"
>
>
>
And so in 1903 the rules for church music had been thoroughly formulated by St Pius X in *[Tra Le Sollecitudini](https://adoremus.org/1903/11/tra-le-sollecitudini/)*
Therefore, it seems any "jazz mass" could only take place either outside of a Catholic Mass, or in a Catholic Mass only illicitly. | They are certainly not suppressed, if not less popular than at one point in time. Various churches in the US have weekly Jazz Masses, and multiple dioceses sponsor annual ones (while others have commissioned them for special occasions). There's one coming up next month in Detroit.
This, of course, says nothing on the topic of whether they are licit canonically, but I should doubt that stalwart conservatives like Archbishop Salvatore Cordileone would knowingly celebrate illicit Masses in their cathedral every year. One Jazz Mass you mentioned, from Mary Lou Williams, premiered at St Patrick's Cathedral, if I'm not mistaken.
Certain Vatican music docs from the 1960s (often interpreted as banning certain, usually African-American music forms) are hardly applied even in Rome today, so I suspect they represent a particular historical perspective that has since been superseded by other pronouncements and norms. |
51,153,183 | I am trying to cherry-pick a commit from one branch to another. Consider the below scenario.
Branch A -> commit1 -> commit message "12345 Hello World"
I want to add a new message at the beginning of the commit message while doing cherry-pick. So after cherry-pick it should look like,
Branch B -> commit2 -> commit message "98765 ........"
Here 98765 is the extra message I want to add. From Git documentation I found a command "git cherry-pick --edit" but I didn't find any example to understand its proper use. | 2018/07/03 | [
"https://Stackoverflow.com/questions/51153183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6096034/"
] | There isn't much to explain about `git cherry-pick --edit`. If you cherry pick with the `--edit` option, Git will bring up the commit message editor window before making the commit. There, you may customize the commit message however you want.
As to the logistics of *why* this is possible, when you cherry pick a commit you actually are making a *new* commit. So there is nothing extra to prevent you from using any commit message you want. | From comments, what you want is for the edit to occur automatically, rather than for git to present you with the commit message in an editor window.
To do this, write a script that edits the message in the required way. Your script will receive a filename as its first command-line argument, and it must update that file in place. For example you could use a perl script similar to:
```
open my $fh, '+<', $ARGV[0] or die;
local $/ = undef;
my $a = <$fh>;
seek $fh,0,0;
print $fh "new content $a";
close $fh;
```
Then you would specify this script as the editor to be used by your `cherry-pick` cmmand
```
git -c core.editor="perl /path/to/your/script.pl" cherry-pick --edit <commit>
``` |
51,153,183 | I am trying to cherry-pick a commit from one branch to another. Consider the below scenario.
Branch A -> commit1 -> commit message "12345 Hello World"
I want to add a new message at the beginning of the commit message while doing cherry-pick. So after cherry-pick it should look like,
Branch B -> commit2 -> commit message "98765 ........"
Here 98765 is the extra message I want to add. From Git documentation I found a command "git cherry-pick --edit" but I didn't find any example to understand its proper use. | 2018/07/03 | [
"https://Stackoverflow.com/questions/51153183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6096034/"
] | There isn't much to explain about `git cherry-pick --edit`. If you cherry pick with the `--edit` option, Git will bring up the commit message editor window before making the commit. There, you may customize the commit message however you want.
As to the logistics of *why* this is possible, when you cherry pick a commit you actually are making a *new* commit. So there is nothing extra to prevent you from using any commit message you want. | Thank you everyone for your quick response. I found the below way which helps my case. It will be done in two steps.
1. Cherry-pick without committing to the target using -n.
```
git cherry-pick -n <hash>
```
2. Then perform commit action.
```
git commit -m <message>
``` |
53,855,437 | I'm a beginner and I'm working on a little exercice right now where I need to implement a function that will vote for a specific picture every time we click on the "Vote" button.
[](https://i.stack.imgur.com/CgrDy.png)
Here is what it looks like, for example if I click on the first button, I need to increment the number of vote for this picture.
Here is what i did :
```
<div id="display" class="container">
<table class="w3-table-all" id="tableDisplay">
<tr>
<th>Cat</th>
<th>Vote</th>
</tr>
</table>
<div v-for="display in gridData">
<table class="w3-striped w3-table-all table table-bordered" id="tableDisplay">
<tr class="w3-hover-light-grey">
<th>
<img :src="display.url" height="200px" width="300px"/>
</th>
<th>
<button class="w3-button w3-green w3-hover-light-green"v-on:click="test(display.counter,display.id)" v-bind:id="display.id">Vote !</button>
</th>
</tr>
</table>
</div>
</div>
```
And the vueJs part :
```
new Vue({
el :'#display',
data: {
gridData :[
{
"url": "http://24.media.tumblr.com/tumblr_m82woaL5AD1rro1o5o1_1280.jpg",
"id": "MTgwODA3MA",
"counter" : 0
},
{
"url": "http://24.media.tumblr.com/tumblr_m29a9d62C81r2rj8po1_500.jpg",
"id": "tt",
"counter" : 0
}
],
},
methods:{
test: function(count,id){
count ++;
alert(count);
}
},
})
```
And the problem is that it doesn't update the change, in the "counter" section it still at 0.
Thank you for any help. | 2018/12/19 | [
"https://Stackoverflow.com/questions/53855437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9736244/"
] | Easiest way is to pipe `node`'s stdout to `python`'s stdin and keep reading `stdin` in Python until it is over. What is not good is that you most probably want to have some console output from Node application, and you definately dont want it to be passed to Python.
Second, recommended approach is to use `tcp/ip` channel. In this case you also benefit from being able to move Python app to another machine/container. Listening tcp/ip input in Python is very simple, I usually use following approach:
```
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import LineReceiver
class DataProcessor(LineReceiver):
def lineReceived(self, line):
print('Line received: {}'.format(line))
Factory factory = Factory()
factory.protocol = DataProcessor
reactor.listenTCP(8080, factory)
``` | All you need is to make an ajax request to your pythoncode. You can do this with jquery <http://api.jquery.com/jQuery.ajax/>, or use just javascript
```
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
``` |
17,374,871 | My project has a bare repo setup on the server. I'm currently on branch `0.9/develop`. I merged `0.9/develop` with a branch that another developer was working on. It turns out that it would be **way** more work to fix his code than to obliterate his changes entirely. Unfortunately, I already ran a `git push origin 0.9/develop` after having committed the merge AND I pulled those changes to my development AND staging servers (yes, I'm stupid).
I've been going through a bunch of somewhat similar questions on SO, but none of them quite seem to cover my exact case. This one was particularly useful: [How to revert Git repository to a previous commit?](https://stackoverflow.com/questions/4114095/git-revert-to-previous-commit-how)
Using info from that question, I was able to successfully obliterate the last commit off of the project. Specifically, I did a `git reset --hard f6c84a0`, which successfully reset my local repository to the commit right before I merged the other developer's n00bery into my poetry.
Okay, great. Now I just need to get the bare repo fixed up. So I tried `git push --force origin 0.9/develop`. Unfortunately I lost the specific message that the server sent back, but it was something along the lines of "success", and it showed that the remote repo had been updated to commit f6c84a0.
When I tried to ssh into the server and then go to my staging environment and run a `git pull`, the response was:
```
From /home/ben/web/example
+ 77d54e4...f6c84a0 0.9/develop -> origin/0.9/develop (forced update)
Already up-to-date.
```
However, when I ran a `git log` from the staging server, all of the commits from the merge are still on the `0.9/develop` branch. I tried a couple of things, like `git pull --force`, but I couldn't get the bad commits to go away.
Okay, fine. There's more than one way to skin a cat. I wiped the staging server clean and did a fresh `git clone --recursive --no-hardlinks example.git stage.example.com` and ran the necessary setup script that does a few little server maintenance things.
Now I can't get back to my `0.9/develop branch`. In the past, I have simply run `git checkout 0.9/develop`, but if I try that now, I get this:
```
Branch 0.9/develop set up to track remote branch 0.9/develop from origin.
Switched to a new branch '0.9/develop'
```
Wait...what? `0.9/develop` is not a new branch. Working with info from this question: [How to clone all remote branches in Git?](https://stackoverflow.com/questions/67699/how-do-i-clone-all-remote-branches-with-git) I did a `git branch -a` and got the following:
```
* 0.9/develop
master
remotes/origin/0.8/develop
remotes/origin/0.8/master
remotes/origin/0.9/develop
remotes/origin/HEAD -> origin/master
remotes/origin/category-address
remotes/origin/jaminimaj
remotes/origin/master
remotes/origin/permissions
remotes/origin/ticket-duration
remotes/origin/timzone-support
```
I then tried `git checkout origin/0.9/develop`, but I got the following message:
```
Note: checking out 'origin/0.9/develop'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at f6c84a0... bugfix: revert email helper
```
Well, the good news is the staging server now has the proper code base, but I'm in a detached HEAD state. I realize that I'm probably missing something very minor here, but it certainly is messing with my Friday evening. How can I get my staging server HEAD pointing back to the HEAD of `0.9/develop`? Also, I want to do the same thing on my development environment, but I'd rather do it in the proper `git` fashion than erasing the whole server and starting over again. Can I do that, or will I just have to brute-force it by rebuilding the server from the repo? Thanks for the help everybody! | 2013/06/28 | [
"https://Stackoverflow.com/questions/17374871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023812/"
] | The message
```
Branch 0.9/develop set up to track remote branch 0.9/develop from origin.
Switched to a new branch '0.9/develop'
```
means the following:
* git created a new branch pointer named 0.9/develop that points to the current head of origin/0.9/develop
* This branch pointer has auto-generated configuration settings to track the remote branch so that git pull and git push work as expected.
So it does what it's supposed to do. It's just a bit counter-intuitive, basically to work with a branch you need a local branch in the repository you cloned. This is merged with the remote branch whenever you run `git pull`.
By the way, git pull in the tracking branch is equivalent to
```
git fetch
git merge remotes/origin/0.9/develop
``` | Possibly your root problem is [answered here](https://stackoverflow.com/questions/4084868/how-do-i-recover-resynchronise-after-someone-pushes-a-rebase-or-a-reset-to-a-pub)
After manipulation like yours client must reset back a few commits and pull again, as their repo is ahead the forced push.
If you happen to be on detached hear, don't worry just `checkout` a *local* branch. It happens easily if you use checkout on a direct hash, a tag or a remote branch, or just got in the middle of some operation. It just means you're on no branch currently.
You got it by
```
git checkout origin/0.9/develop
```
It's unclear whether you lost your local branches or not. use `git branch` to see whether you have `0.9/develop` or not, and if so, checkout that. If not, start `git gui` and use create branch menu to create it from the tracking branch. |
17,374,871 | My project has a bare repo setup on the server. I'm currently on branch `0.9/develop`. I merged `0.9/develop` with a branch that another developer was working on. It turns out that it would be **way** more work to fix his code than to obliterate his changes entirely. Unfortunately, I already ran a `git push origin 0.9/develop` after having committed the merge AND I pulled those changes to my development AND staging servers (yes, I'm stupid).
I've been going through a bunch of somewhat similar questions on SO, but none of them quite seem to cover my exact case. This one was particularly useful: [How to revert Git repository to a previous commit?](https://stackoverflow.com/questions/4114095/git-revert-to-previous-commit-how)
Using info from that question, I was able to successfully obliterate the last commit off of the project. Specifically, I did a `git reset --hard f6c84a0`, which successfully reset my local repository to the commit right before I merged the other developer's n00bery into my poetry.
Okay, great. Now I just need to get the bare repo fixed up. So I tried `git push --force origin 0.9/develop`. Unfortunately I lost the specific message that the server sent back, but it was something along the lines of "success", and it showed that the remote repo had been updated to commit f6c84a0.
When I tried to ssh into the server and then go to my staging environment and run a `git pull`, the response was:
```
From /home/ben/web/example
+ 77d54e4...f6c84a0 0.9/develop -> origin/0.9/develop (forced update)
Already up-to-date.
```
However, when I ran a `git log` from the staging server, all of the commits from the merge are still on the `0.9/develop` branch. I tried a couple of things, like `git pull --force`, but I couldn't get the bad commits to go away.
Okay, fine. There's more than one way to skin a cat. I wiped the staging server clean and did a fresh `git clone --recursive --no-hardlinks example.git stage.example.com` and ran the necessary setup script that does a few little server maintenance things.
Now I can't get back to my `0.9/develop branch`. In the past, I have simply run `git checkout 0.9/develop`, but if I try that now, I get this:
```
Branch 0.9/develop set up to track remote branch 0.9/develop from origin.
Switched to a new branch '0.9/develop'
```
Wait...what? `0.9/develop` is not a new branch. Working with info from this question: [How to clone all remote branches in Git?](https://stackoverflow.com/questions/67699/how-do-i-clone-all-remote-branches-with-git) I did a `git branch -a` and got the following:
```
* 0.9/develop
master
remotes/origin/0.8/develop
remotes/origin/0.8/master
remotes/origin/0.9/develop
remotes/origin/HEAD -> origin/master
remotes/origin/category-address
remotes/origin/jaminimaj
remotes/origin/master
remotes/origin/permissions
remotes/origin/ticket-duration
remotes/origin/timzone-support
```
I then tried `git checkout origin/0.9/develop`, but I got the following message:
```
Note: checking out 'origin/0.9/develop'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at f6c84a0... bugfix: revert email helper
```
Well, the good news is the staging server now has the proper code base, but I'm in a detached HEAD state. I realize that I'm probably missing something very minor here, but it certainly is messing with my Friday evening. How can I get my staging server HEAD pointing back to the HEAD of `0.9/develop`? Also, I want to do the same thing on my development environment, but I'd rather do it in the proper `git` fashion than erasing the whole server and starting over again. Can I do that, or will I just have to brute-force it by rebuilding the server from the repo? Thanks for the help everybody! | 2013/06/28 | [
"https://Stackoverflow.com/questions/17374871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023812/"
] | The message
```
Branch 0.9/develop set up to track remote branch 0.9/develop from origin.
Switched to a new branch '0.9/develop'
```
means the following:
* git created a new branch pointer named 0.9/develop that points to the current head of origin/0.9/develop
* This branch pointer has auto-generated configuration settings to track the remote branch so that git pull and git push work as expected.
So it does what it's supposed to do. It's just a bit counter-intuitive, basically to work with a branch you need a local branch in the repository you cloned. This is merged with the remote branch whenever you run `git pull`.
By the way, git pull in the tracking branch is equivalent to
```
git fetch
git merge remotes/origin/0.9/develop
``` | It sounds like you need to check out the branch in the bare repo and use `git reset` to reset it back to where you want it. Alternatively, you can `git reset` the local branch in your local repo and `git push -f` it. In the staging repo, you have to do a `git reset` just like you do in your normal working repo. |
23,318,767 | I have this little class:
```
var SwitchHider;
SwitchHider = {
inputSelector: 'body.socials input',
_showOrHideClosestSwitch: function(element) {
var socialUrl, swich_wrapper;
socialUrl = $(element).val();
swich_wrapper = $(element).closest('.white-box').find('.switch');
if (socialUrl.length > 0) {
return swich_wrapper.show();
} else {
return swich_wrapper.hide();
}
},
_bindCallbacks: function() {
$(document).on('ready', function() {
return $(self.inputSelector).each(function(index, element) {
return self._showOrHideClosestSwitch(element);
});
});
return $(document).on('change keyup input', self.inputSelector, function() {
return self._showOrHideClosestSwitch(this);
});
},
initialize: function() {
var self;
self = this;
this._bindCallbacks();
}
};
window.SwitchHider = SwitchHider;
$(function() {
SwitchHider.initialize();
});
```
(it's compiled from this CoffeeScript file, hope it makes sense):
```
SwitchHider =
inputSelector: 'body.socials input'
_showOrHideClosestSwitch: (element) ->
socialUrl = $(element).val()
swich_wrapper = $(element).closest('.white-box').find('.switch')
if socialUrl.length > 0
swich_wrapper.show()
else
swich_wrapper.hide()
_bindCallbacks: ->
$(document).on 'ready', ->
$(self.inputSelector).each (index, element) ->
self._showOrHideClosestSwitch(element)
$(document).on 'change keyup input', self.inputSelector, ->
self._showOrHideClosestSwitch(@)
initialize: ->
self = this
@_bindCallbacks()
return
# Send to global namespace
window.SwitchHider = SwitchHider
# DOM Ready
$ ->
SwitchHider.initialize()
return
```
And when event is triggered - it gives this error:
```
TypeError: self._showOrHideClosestSwitch is not a function
```
Does anyone see why? It's my first attempt to write classes like that, don't fully understand what I'm doing. | 2014/04/27 | [
"https://Stackoverflow.com/questions/23318767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988673/"
] | The two commands have absolutely nothing in common, so no, you cannot use parentheses like that.
You must execute all the commands within a single CMD /C. You can concatenate commands on one line using `&`. I've defined a simple XCOPY "macro" to save a bit of typing.
```
set XCOPY=xcopy /e /c /h /i /v /r /y /q"
forfiles /m "%worldprefix%*" /c "cmd /c echo Copying World: @path&%XCOPY% @file %snapshotdir%\@file\%itdate%-%hour%-%time:~3,2%-%time:~6,2%&%XCOPY% @file %backdir%\%itdate%D\worlds\@file"
```
If you escape the quotes, then you can use line continuation to split the logical line accross multiple lines. But then you must also escape the `&`.
```
set XCOPY=xcopy /e /c /h /i /v /r /y /q"
forfiles /m "%worldprefix%*" /c ^"cmd /c ^
echo Copying World: @path ^&^
%XCOPY% @file %snapshotdir%\@file\%itdate%-%hour%-%time:~3,2%-%time:~6,2% ^&^
%XCOPY% @file %backdir%\%itdate%D\worlds\@file^"
```
Or you could put the `&` in the front of the line so that you don't need to escape it. The line continuation also escapes the first character of the next line:
```
set XCOPY=xcopy /e /c /h /i /v /r /y /q"
forfiles /m "%worldprefix%*" /c ^"cmd /c ^
echo Copying World: @path^
&%XCOPY% @file %snapshotdir%\@file\%itdate%-%hour%-%time:~3,2%-%time:~6,2%^
&%XCOPY% @file %backdir%\%itdate%D\worlds\@file^"
``` | I realize this is an old post, but another way of doing it is to call a batch file and pass it the parameters that it needs. And I do not believe that there is any limitations in what can be in that batch file. For example:
forfiles /M "\*.img" /C "cmd /c ProcessFile.bat @file @fdate @ftime" |
40,765,504 | I upload image files with codeigniter to my website using:
```
$uploaded = $this->upload->data();
```
and getting the filename in this way:
```
$uploaded['file_name'];
```
I want to change this filename adding "\_thumb" before extension and after the name. Like 'sda8sda8fa8f9.jpg' to 'sda8sda8fa8f9\_thumb.jpg'. Since I need to keep hashed name, what is the simpliest way to do this? | 2016/11/23 | [
"https://Stackoverflow.com/questions/40765504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5830157/"
] | When configuring [CI's file uploader](https://www.codeigniter.com/user_guide/libraries/file_uploading.html), you can pass a `file_name` option to the class. That will change the name of the uploaded file. Here's the description from the docs:
>
> If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. If no extension is provided in the original file\_name will be used.
>
>
>
And an example:
```php
$this->load->library('upload', ['file_name' => 'new-file-name.ext']);
$this->upload->do_upload('file_field_name');
```
So, you want to **modify** the uploaded file's name. The uploaded filename can be accessed from PHP's `$_FILES` array. First, we figure out the new name, then we hit CI's upload library. Assuming that the fieldname is `fieldname`:
```php
// Modify the filename, adding that "_thumb" thing
// I assumed the extension is always ".jpg" for the sake of simplicity,
// but if that's not the case, you can use "pathinfo()" to get info on
// the filename in order to modify it.
$new_filename = str_replace('.jpg', '_thumb.jpg', $_FILES['fieldname']['name']);
// Configure CI's upload library with the filename and hit it
$this->upload->initialize([
'file_name' => $new_filename
// Other config options...
]);
$this->upload->do_upload('fieldname');
```
Please note that the original filename (that from the `$_FILES['fieldname']['name']`) comes from the user's browser. It's the actual filename on user's device. As you decided to depend on it in your code, **always treat it as tainted.** | Simply add the calculated hash value to file name with thumb
```
$hash_variable = //Your calculated value
$thumb = '_thumb'
$config['file_name'] = $hash_variable.$thumb.".pdf|jpg|png etc";
$this->load->library('upload',$config);
``` |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't have much experience with dating. But I want to leave this here.
>
> *When I meet someone to date, how can I communicate clearly that I am only interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc?*
>
>
>
I think the problem here is the words **date** and **relationship**. It's sort of like [my answer to this question](https://interpersonal.stackexchange.com/a/4299/1599), only reversed: **You shouldn't mention those words!**
You are clearly looking for **friends**, not people you can have a short-term dating relationship with. It's okay to look for new friends, to do fun stuff with. But you don't take friends on dates, and you don't have 'relationships' with them (I prefer to call that particular form of a relation 'friendship', just to keep the two separated).
>
> *Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.*
>
>
>
If you mention this on a first date, of course, people might say that they are fine with it. They are on a first date with you, they don't know you. But the fact that they are on a **date** with you, means to me that they are at least interested in trying to see if a **serious relationship** can grow out of it. She might not have been looking for anything serious **right at that moment**. But the fact that she's dating, means that she is looking for something that can grow into something serious.
At least, I've never dated a guy for any other reason. If I don't want a serious relationship or a something casual that can grow into a serious one, I'm not going on a date with you. Then, we're just doing stuff together, without calling it a date.
I don't know how you are meeting these people, but I get the impression that they are firm believers that they are 'on a date' with you. If you get them via dating-apps or websites, I think it might be wise to quit doing so. People are there to find somebody to 'date'. Even though they might not be there to start a serious relationship right away, I think most people on these platforms are hoping for something that can develop into one given the time to grow.
If these are persons that you have a mutual friend with, that mutual friend might have acted like a middle-man. Make sure your friends know that you are willing to be introduced to new people, but that you are only looking for **friends** that share your interests, **not a girlfriend**.
I would believe that in this case, the magic words are **friend** and **shared interests**. And that you should avoid the words **date** and **relationship**. | >
> My latest three dating experiences have ended with the other person
> upset about the relationship not becoming more serious, even though
> I made it clear that I would **never** get serious with the person.
>
>
>
Are you sure you can always control your feelings? No matter how clearly or well you communicate
>
> that I am only interested in a casual/short-term dating relationship,
> such as dating for a few months by doing fun activities, going to
> parties, attending concerts, etc?
>
>
>
you can't prevent the woman you are dating from falling in love with you or developing deeper feelings for you. *You* may even develop feelings. What if the roles were reversed? What if someone you were dating short-term dumps you after they get tired of you and it's you this time wanting more?
Short-term dating specific sites? Sure. No guarantees.
You may need to consider having a friend with whom you mutually agree to also have sex. Again, no guarantees.
Or you could combine having friends for doing the fun stuff with plus hooking up with women for just sex (from specific sites if there are sites for that).
In the end, sure, you can be upfront all you like,
>
> Hey before we start [hanging out/dating/call it whatever], I just
> wanted to let you know that I'm not interested in a serious
> relationship and I won't be for a while. I'm being upfront with you to
> avoid misunderstandings in the future. I'm only interested in....
>
>
>
No guarantees. This is human nature you are talking about. Just, date responsibly. |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't have much experience with dating. But I want to leave this here.
>
> *When I meet someone to date, how can I communicate clearly that I am only interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc?*
>
>
>
I think the problem here is the words **date** and **relationship**. It's sort of like [my answer to this question](https://interpersonal.stackexchange.com/a/4299/1599), only reversed: **You shouldn't mention those words!**
You are clearly looking for **friends**, not people you can have a short-term dating relationship with. It's okay to look for new friends, to do fun stuff with. But you don't take friends on dates, and you don't have 'relationships' with them (I prefer to call that particular form of a relation 'friendship', just to keep the two separated).
>
> *Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.*
>
>
>
If you mention this on a first date, of course, people might say that they are fine with it. They are on a first date with you, they don't know you. But the fact that they are on a **date** with you, means to me that they are at least interested in trying to see if a **serious relationship** can grow out of it. She might not have been looking for anything serious **right at that moment**. But the fact that she's dating, means that she is looking for something that can grow into something serious.
At least, I've never dated a guy for any other reason. If I don't want a serious relationship or a something casual that can grow into a serious one, I'm not going on a date with you. Then, we're just doing stuff together, without calling it a date.
I don't know how you are meeting these people, but I get the impression that they are firm believers that they are 'on a date' with you. If you get them via dating-apps or websites, I think it might be wise to quit doing so. People are there to find somebody to 'date'. Even though they might not be there to start a serious relationship right away, I think most people on these platforms are hoping for something that can develop into one given the time to grow.
If these are persons that you have a mutual friend with, that mutual friend might have acted like a middle-man. Make sure your friends know that you are willing to be introduced to new people, but that you are only looking for **friends** that share your interests, **not a girlfriend**.
I would believe that in this case, the magic words are **friend** and **shared interests**. And that you should avoid the words **date** and **relationship**. | First, the assumptions.
* When you say "short term dating relationship" I'm assuming you mean acting as BF and GF, including physical intimacy.
* You are not currently in this situation, you are looking toward the next one
It is not unseemly for her to want to renegotiate the terms as her feelings evolve over time. You are free to do the same. "You cannot look twice at the same river; for fresh waters are ever flowing in." Your job now is to work with her in the negotiation, while being respectful of her feelings.
That is to say, getting mad and saying "We had a deal" isn't the right approach [1]. Be aware that proximity, shared experiences, and physical intimacy often do spark those deeper feelings. It's by far the more common pattern than what you proposed to her. Do not be surprised. I mean heck, many people either consciously or not, date like this as ... well ... "tryouts" for long-term mate compatibility.
**So ... what should you do?**
First, introspect a little. How *do* you feel about your reluctance to have longer relationships, fall in love, and so on? Do you feel like you have some healing to do? If not, not, but do ask the question.
Second, your approach seems ... like kind of a hard sell. It would not be hard to hear it as "I want to have fun with you and then discard you". Another poster suggested that you desexualize it and just *make friends* with women. Do a lot of group activities. I really do think you'll have trouble finding women who want the deal you're proposing. I could be wrong.
[1] Unless you are both huge Star Wars geeks. If I told a girl "We had a deal" and she snapped back "I am altering the deal. Pray I do not alter it any further" she would **own** my heart for all time. ;D |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | Short term dating relationships are just that *short term.* Meaning that regardless of how you try to frame it, you can only push them so long before people want or expect more.
I applaud your being honest about your intentions, telling people upfront what you're looking for is a good first step, but then you have to be willing to follow through and keep the relationship short.
There's no black and white rule for how long you'll be able to ride one of these situations out before feelings develop, so if it seems like people are getting more attached than you're comfortable with after a few months, you may want to keep things more in the few weeks range.
As an aside I would advise you to get over your fear of being cheated on. It's better to have loved and lost n' all. [Also while dating like this can be fun for a while, it very often gets harder as you get older.](https://youtu.be/ruR4uI8Ift8) | First, the assumptions.
* When you say "short term dating relationship" I'm assuming you mean acting as BF and GF, including physical intimacy.
* You are not currently in this situation, you are looking toward the next one
It is not unseemly for her to want to renegotiate the terms as her feelings evolve over time. You are free to do the same. "You cannot look twice at the same river; for fresh waters are ever flowing in." Your job now is to work with her in the negotiation, while being respectful of her feelings.
That is to say, getting mad and saying "We had a deal" isn't the right approach [1]. Be aware that proximity, shared experiences, and physical intimacy often do spark those deeper feelings. It's by far the more common pattern than what you proposed to her. Do not be surprised. I mean heck, many people either consciously or not, date like this as ... well ... "tryouts" for long-term mate compatibility.
**So ... what should you do?**
First, introspect a little. How *do* you feel about your reluctance to have longer relationships, fall in love, and so on? Do you feel like you have some healing to do? If not, not, but do ask the question.
Second, your approach seems ... like kind of a hard sell. It would not be hard to hear it as "I want to have fun with you and then discard you". Another poster suggested that you desexualize it and just *make friends* with women. Do a lot of group activities. I really do think you'll have trouble finding women who want the deal you're proposing. I could be wrong.
[1] Unless you are both huge Star Wars geeks. If I told a girl "We had a deal" and she snapped back "I am altering the deal. Pray I do not alter it any further" she would **own** my heart for all time. ;D |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't have much experience with dating. But I want to leave this here.
>
> *When I meet someone to date, how can I communicate clearly that I am only interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc?*
>
>
>
I think the problem here is the words **date** and **relationship**. It's sort of like [my answer to this question](https://interpersonal.stackexchange.com/a/4299/1599), only reversed: **You shouldn't mention those words!**
You are clearly looking for **friends**, not people you can have a short-term dating relationship with. It's okay to look for new friends, to do fun stuff with. But you don't take friends on dates, and you don't have 'relationships' with them (I prefer to call that particular form of a relation 'friendship', just to keep the two separated).
>
> *Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.*
>
>
>
If you mention this on a first date, of course, people might say that they are fine with it. They are on a first date with you, they don't know you. But the fact that they are on a **date** with you, means to me that they are at least interested in trying to see if a **serious relationship** can grow out of it. She might not have been looking for anything serious **right at that moment**. But the fact that she's dating, means that she is looking for something that can grow into something serious.
At least, I've never dated a guy for any other reason. If I don't want a serious relationship or a something casual that can grow into a serious one, I'm not going on a date with you. Then, we're just doing stuff together, without calling it a date.
I don't know how you are meeting these people, but I get the impression that they are firm believers that they are 'on a date' with you. If you get them via dating-apps or websites, I think it might be wise to quit doing so. People are there to find somebody to 'date'. Even though they might not be there to start a serious relationship right away, I think most people on these platforms are hoping for something that can develop into one given the time to grow.
If these are persons that you have a mutual friend with, that mutual friend might have acted like a middle-man. Make sure your friends know that you are willing to be introduced to new people, but that you are only looking for **friends** that share your interests, **not a girlfriend**.
I would believe that in this case, the magic words are **friend** and **shared interests**. And that you should avoid the words **date** and **relationship**. | Short term dating relationships are just that *short term.* Meaning that regardless of how you try to frame it, you can only push them so long before people want or expect more.
I applaud your being honest about your intentions, telling people upfront what you're looking for is a good first step, but then you have to be willing to follow through and keep the relationship short.
There's no black and white rule for how long you'll be able to ride one of these situations out before feelings develop, so if it seems like people are getting more attached than you're comfortable with after a few months, you may want to keep things more in the few weeks range.
As an aside I would advise you to get over your fear of being cheated on. It's better to have loved and lost n' all. [Also while dating like this can be fun for a while, it very often gets harder as you get older.](https://youtu.be/ruR4uI8Ift8) |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't see *sex* mentioned anywhere, or in reply to Catija's comments. It matters.
If you want to make it crystal clear that you're not interested in any long-term relationships, then put a time limit on it. Honest. Otherwise there's a good chance that the person you're "having fun with" might think they can change your mind. Let them know they can't. So, to pick up where you left off:
>
> You: I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together. [If you also want sex, add that between "hanging out" and "having fun", i.e., "just hanging out, having sex, and having fun together."]
>
> Her: Great, I'm not looking for anything serious either.
>
> You: Really? Great! Because I'm in it for no more than three months at the most, then I'm gone to greener pastures, I promise you. But in the meantime, if you want to have fun [(and sex)], and don't mind that I'm dating others at the same time, I'd love to take you out.
>
>
>
If she goes out with you and complains when you tell her it's over in three months or less, she has absolutely no right to complain.
It's honest, straightforward, and real. Don't be surprised if you don't get many takers, though. But that's good. You don't want to disappoint anyone. | First, the assumptions.
* When you say "short term dating relationship" I'm assuming you mean acting as BF and GF, including physical intimacy.
* You are not currently in this situation, you are looking toward the next one
It is not unseemly for her to want to renegotiate the terms as her feelings evolve over time. You are free to do the same. "You cannot look twice at the same river; for fresh waters are ever flowing in." Your job now is to work with her in the negotiation, while being respectful of her feelings.
That is to say, getting mad and saying "We had a deal" isn't the right approach [1]. Be aware that proximity, shared experiences, and physical intimacy often do spark those deeper feelings. It's by far the more common pattern than what you proposed to her. Do not be surprised. I mean heck, many people either consciously or not, date like this as ... well ... "tryouts" for long-term mate compatibility.
**So ... what should you do?**
First, introspect a little. How *do* you feel about your reluctance to have longer relationships, fall in love, and so on? Do you feel like you have some healing to do? If not, not, but do ask the question.
Second, your approach seems ... like kind of a hard sell. It would not be hard to hear it as "I want to have fun with you and then discard you". Another poster suggested that you desexualize it and just *make friends* with women. Do a lot of group activities. I really do think you'll have trouble finding women who want the deal you're proposing. I could be wrong.
[1] Unless you are both huge Star Wars geeks. If I told a girl "We had a deal" and she snapped back "I am altering the deal. Pray I do not alter it any further" she would **own** my heart for all time. ;D |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't see *sex* mentioned anywhere, or in reply to Catija's comments. It matters.
If you want to make it crystal clear that you're not interested in any long-term relationships, then put a time limit on it. Honest. Otherwise there's a good chance that the person you're "having fun with" might think they can change your mind. Let them know they can't. So, to pick up where you left off:
>
> You: I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together. [If you also want sex, add that between "hanging out" and "having fun", i.e., "just hanging out, having sex, and having fun together."]
>
> Her: Great, I'm not looking for anything serious either.
>
> You: Really? Great! Because I'm in it for no more than three months at the most, then I'm gone to greener pastures, I promise you. But in the meantime, if you want to have fun [(and sex)], and don't mind that I'm dating others at the same time, I'd love to take you out.
>
>
>
If she goes out with you and complains when you tell her it's over in three months or less, she has absolutely no right to complain.
It's honest, straightforward, and real. Don't be surprised if you don't get many takers, though. But that's good. You don't want to disappoint anyone. | >
> My latest three dating experiences have ended with the other person
> upset about the relationship not becoming more serious, even though
> I made it clear that I would **never** get serious with the person.
>
>
>
Are you sure you can always control your feelings? No matter how clearly or well you communicate
>
> that I am only interested in a casual/short-term dating relationship,
> such as dating for a few months by doing fun activities, going to
> parties, attending concerts, etc?
>
>
>
you can't prevent the woman you are dating from falling in love with you or developing deeper feelings for you. *You* may even develop feelings. What if the roles were reversed? What if someone you were dating short-term dumps you after they get tired of you and it's you this time wanting more?
Short-term dating specific sites? Sure. No guarantees.
You may need to consider having a friend with whom you mutually agree to also have sex. Again, no guarantees.
Or you could combine having friends for doing the fun stuff with plus hooking up with women for just sex (from specific sites if there are sites for that).
In the end, sure, you can be upfront all you like,
>
> Hey before we start [hanging out/dating/call it whatever], I just
> wanted to let you know that I'm not interested in a serious
> relationship and I won't be for a while. I'm being upfront with you to
> avoid misunderstandings in the future. I'm only interested in....
>
>
>
No guarantees. This is human nature you are talking about. Just, date responsibly. |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't see *sex* mentioned anywhere, or in reply to Catija's comments. It matters.
If you want to make it crystal clear that you're not interested in any long-term relationships, then put a time limit on it. Honest. Otherwise there's a good chance that the person you're "having fun with" might think they can change your mind. Let them know they can't. So, to pick up where you left off:
>
> You: I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together. [If you also want sex, add that between "hanging out" and "having fun", i.e., "just hanging out, having sex, and having fun together."]
>
> Her: Great, I'm not looking for anything serious either.
>
> You: Really? Great! Because I'm in it for no more than three months at the most, then I'm gone to greener pastures, I promise you. But in the meantime, if you want to have fun [(and sex)], and don't mind that I'm dating others at the same time, I'd love to take you out.
>
>
>
If she goes out with you and complains when you tell her it's over in three months or less, she has absolutely no right to complain.
It's honest, straightforward, and real. Don't be surprised if you don't get many takers, though. But that's good. You don't want to disappoint anyone. | First of all, kudos to you for being so honest. And I think the other answers are great advice.
However, I think the following points are yet missing. You ask:
>
> When I meet someone to date, how can I communicate clearly [...]
>
>
>
The key point here is that this communication should not be a one-time thing you tell potential candidates only on your first date. There is no magic sentence that wards off emotions by your acquaintances for weeks, months or years. Especially if you send mixed signals:
>
> "Relationship", "dating", etc.
>
>
>
The power of words should not be overestimated. Telling someone that you only want to 'have fun', while being there for them in difficult times, having sex together, sleeping in the same bed [I just assume you do this], being monogamous, among other things, sends signals that are very different from whatever you say. From my experience, people automatically expect romantic relationships to become more serious over time. This is not something you can change. [This article](http://www.dailymail.co.uk/health/article-2031498/Sex-Why-makes-women-fall-love--just-makes-men-want-MORE.html) even claims women automatically fall in love from sex alone.
>
> From this I realized I didn't enjoy serious relationships, so I've avoided them.
>
>
>
[Avoidance behaviour](https://www.iirp.edu/what-we-do/what-is-restorative-practices/defining-restorative/17-compass-of-shame) is rarely effective. This way, you are dealing with emotions, but not solving the problem. You're a firefighter spraying yourself (in order to cool yourself) instead of extinguishing the fire. You are now approaching 30. Around this age, two problems emerge for what I assume to be your current lifestyle:
1. Your friends develop serious relationships and/or mature.
2. Women expect 'more' from men of your age.
Problem 1:
Depending on your social circle, this might come sooner, later or might have already happened: Couples move in together, marry, have kids. Singles stay at home, use dating apps, focus on their career or simply go to bed early because they have to work the next day. Point being: Your friends won't do as much *cool* stuff as they used to. And they will prioritize their partners. It will be hard for you to have as much fun with your friends as you used to. Their serious partners offer a lot of possibilities to simply 'have a good time'. You deny yourself these possibilities.
Problem 2:
As you have mentioned yourself, the women you are attracted to generally want a more serious relationship. See problem 1.
**Solutions**
The solution you want: Keep sex and friendship separated, even if it means putting in more effort to continually find short-term sex partners and not being able to kiss your (female) friends at a concert.
The solution I consider more healthy: Seek psychotherapy. You already know what shapes your current relationship wishes: Your past relationships. That knowledge is a great starting point. However, you should ask yourself whether **your** future should be shaped by two people you don't even like anymore. A lot of people live great, satisfying relationships, free of cheating. It is possible for you, too. Also, you don't wake up with 35 and then you're magically able to open up to others emotionally and ready to sustain a serious relationship. You will have to face these problems sometime anyway. |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | Short term dating relationships are just that *short term.* Meaning that regardless of how you try to frame it, you can only push them so long before people want or expect more.
I applaud your being honest about your intentions, telling people upfront what you're looking for is a good first step, but then you have to be willing to follow through and keep the relationship short.
There's no black and white rule for how long you'll be able to ride one of these situations out before feelings develop, so if it seems like people are getting more attached than you're comfortable with after a few months, you may want to keep things more in the few weeks range.
As an aside I would advise you to get over your fear of being cheated on. It's better to have loved and lost n' all. [Also while dating like this can be fun for a while, it very often gets harder as you get older.](https://youtu.be/ruR4uI8Ift8) | >
> My latest three dating experiences have ended with the other person
> upset about the relationship not becoming more serious, even though
> I made it clear that I would **never** get serious with the person.
>
>
>
Are you sure you can always control your feelings? No matter how clearly or well you communicate
>
> that I am only interested in a casual/short-term dating relationship,
> such as dating for a few months by doing fun activities, going to
> parties, attending concerts, etc?
>
>
>
you can't prevent the woman you are dating from falling in love with you or developing deeper feelings for you. *You* may even develop feelings. What if the roles were reversed? What if someone you were dating short-term dumps you after they get tired of you and it's you this time wanting more?
Short-term dating specific sites? Sure. No guarantees.
You may need to consider having a friend with whom you mutually agree to also have sex. Again, no guarantees.
Or you could combine having friends for doing the fun stuff with plus hooking up with women for just sex (from specific sites if there are sites for that).
In the end, sure, you can be upfront all you like,
>
> Hey before we start [hanging out/dating/call it whatever], I just
> wanted to let you know that I'm not interested in a serious
> relationship and I won't be for a while. I'm being upfront with you to
> avoid misunderstandings in the future. I'm only interested in....
>
>
>
No guarantees. This is human nature you are talking about. Just, date responsibly. |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't see *sex* mentioned anywhere, or in reply to Catija's comments. It matters.
If you want to make it crystal clear that you're not interested in any long-term relationships, then put a time limit on it. Honest. Otherwise there's a good chance that the person you're "having fun with" might think they can change your mind. Let them know they can't. So, to pick up where you left off:
>
> You: I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together. [If you also want sex, add that between "hanging out" and "having fun", i.e., "just hanging out, having sex, and having fun together."]
>
> Her: Great, I'm not looking for anything serious either.
>
> You: Really? Great! Because I'm in it for no more than three months at the most, then I'm gone to greener pastures, I promise you. But in the meantime, if you want to have fun [(and sex)], and don't mind that I'm dating others at the same time, I'd love to take you out.
>
>
>
If she goes out with you and complains when you tell her it's over in three months or less, she has absolutely no right to complain.
It's honest, straightforward, and real. Don't be surprised if you don't get many takers, though. But that's good. You don't want to disappoint anyone. | Short term dating relationships are just that *short term.* Meaning that regardless of how you try to frame it, you can only push them so long before people want or expect more.
I applaud your being honest about your intentions, telling people upfront what you're looking for is a good first step, but then you have to be willing to follow through and keep the relationship short.
There's no black and white rule for how long you'll be able to ride one of these situations out before feelings develop, so if it seems like people are getting more attached than you're comfortable with after a few months, you may want to keep things more in the few weeks range.
As an aside I would advise you to get over your fear of being cheated on. It's better to have loved and lost n' all. [Also while dating like this can be fun for a while, it very often gets harder as you get older.](https://youtu.be/ruR4uI8Ift8) |
4,618 | I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc? | 2017/09/26 | [
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] | I don't have much experience with dating. But I want to leave this here.
>
> *When I meet someone to date, how can I communicate clearly that I am only interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc?*
>
>
>
I think the problem here is the words **date** and **relationship**. It's sort of like [my answer to this question](https://interpersonal.stackexchange.com/a/4299/1599), only reversed: **You shouldn't mention those words!**
You are clearly looking for **friends**, not people you can have a short-term dating relationship with. It's okay to look for new friends, to do fun stuff with. But you don't take friends on dates, and you don't have 'relationships' with them (I prefer to call that particular form of a relation 'friendship', just to keep the two separated).
>
> *Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.*
>
>
>
If you mention this on a first date, of course, people might say that they are fine with it. They are on a first date with you, they don't know you. But the fact that they are on a **date** with you, means to me that they are at least interested in trying to see if a **serious relationship** can grow out of it. She might not have been looking for anything serious **right at that moment**. But the fact that she's dating, means that she is looking for something that can grow into something serious.
At least, I've never dated a guy for any other reason. If I don't want a serious relationship or a something casual that can grow into a serious one, I'm not going on a date with you. Then, we're just doing stuff together, without calling it a date.
I don't know how you are meeting these people, but I get the impression that they are firm believers that they are 'on a date' with you. If you get them via dating-apps or websites, I think it might be wise to quit doing so. People are there to find somebody to 'date'. Even though they might not be there to start a serious relationship right away, I think most people on these platforms are hoping for something that can develop into one given the time to grow.
If these are persons that you have a mutual friend with, that mutual friend might have acted like a middle-man. Make sure your friends know that you are willing to be introduced to new people, but that you are only looking for **friends** that share your interests, **not a girlfriend**.
I would believe that in this case, the magic words are **friend** and **shared interests**. And that you should avoid the words **date** and **relationship**. | I don't see *sex* mentioned anywhere, or in reply to Catija's comments. It matters.
If you want to make it crystal clear that you're not interested in any long-term relationships, then put a time limit on it. Honest. Otherwise there's a good chance that the person you're "having fun with" might think they can change your mind. Let them know they can't. So, to pick up where you left off:
>
> You: I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together. [If you also want sex, add that between "hanging out" and "having fun", i.e., "just hanging out, having sex, and having fun together."]
>
> Her: Great, I'm not looking for anything serious either.
>
> You: Really? Great! Because I'm in it for no more than three months at the most, then I'm gone to greener pastures, I promise you. But in the meantime, if you want to have fun [(and sex)], and don't mind that I'm dating others at the same time, I'd love to take you out.
>
>
>
If she goes out with you and complains when you tell her it's over in three months or less, she has absolutely no right to complain.
It's honest, straightforward, and real. Don't be surprised if you don't get many takers, though. But that's good. You don't want to disappoint anyone. |
71,591,314 | I'm working in an Electron application. There are alot of events being passed around with specific listeners for each event. For instance BrowserWindow.on:
```
Electron.BrowserWindow.on(event, listener)
```
`event` can be any of `'always-on-top-changed', 'app-command', etc etc...` . I want a list of all of these events in a single type that I can use, for example, to restrict other functions from passing in an invalid event.
I have tried:
`type BrowserWindowOnEvents = Parameters<InstanceType<typeof Electron.BrowserWindow>['on']>[0];`
But that only gives, at least for Intellisense, the last defined event in BrowserWindow class in electron.d.ts, which is currently `'will-resize'`. I am expecting a list with all valid events.
When I have `new BrowserWindow.on('')` the Intellisense does provide me with the list of possibilities, but I want access to the list when creating a type definition not only when I have an instance of BrowserWindow available.
---
Here's a link to Electron's [BrowserWindow](https://github.com/electron/electron/blob/main/lib/browser/api/browser-window.ts)
And in `electron.d.ts` this is how the methods are defined:
```
class BrowserWindow extends NodeEventEmitter {
// Docs: https://electronjs.org/docs/api/browser-window
/**
* Emitted when the window is set or unset to show always on top of other windows.
*/
on(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
once(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
addListener(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
removeListener(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
...
}
``` | 2022/03/23 | [
"https://Stackoverflow.com/questions/71591314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5839529/"
] | Turns out it is possible to do this, but it's not pretty. The problem is that the `on` method is declared with a separate overload for each event name, and type inference on overloaded functions only considers the last one (in this case the overload for `'will-resize'`).
There is a way to infer types from overloaded functions though ([see this TypeScript issue](https://github.com/microsoft/TypeScript/issues/32164#issuecomment-764660652)):
```
type Args<F extends (...args: any[]) => unknown> = F extends {
(...args: infer A1): void
(...args: infer A2): void
} ? [A1, A2] : never
declare function f(event: 'n1', l: (n: number) => void): void
declare function f(event: 'n2', l: (s: string) => void): void
type TestArgs = Args<typeof f>
// type TestArgs = [
// [event: "n1", l: (n: number) => void],
// [event: "n2", l: (s: string) => void]
// ]
```
The downside is that this requires creating a function object with at least as many overloads as the function we wish to extract the parameter types from. The `on` method on `BrowserWindow` has 36 overloads, so let's use 40 to be on the safe side:
```
type BuildOverloads<
A01 extends unknown[], A02 extends unknown[], A03 extends unknown[],
A04 extends unknown[], A05 extends unknown[], A06 extends unknown[],
A07 extends unknown[], A08 extends unknown[], A09 extends unknown[],
A10 extends unknown[], A11 extends unknown[], A12 extends unknown[],
A13 extends unknown[], A14 extends unknown[], A15 extends unknown[],
A16 extends unknown[], A17 extends unknown[], A18 extends unknown[],
A19 extends unknown[], A20 extends unknown[], A21 extends unknown[],
A22 extends unknown[], A23 extends unknown[], A24 extends unknown[],
A25 extends unknown[], A26 extends unknown[], A27 extends unknown[],
A28 extends unknown[], A29 extends unknown[], A30 extends unknown[],
A31 extends unknown[], A32 extends unknown[], A33 extends unknown[],
A34 extends unknown[], A35 extends unknown[], A36 extends unknown[],
A37 extends unknown[], A38 extends unknown[], A39 extends unknown[],
A40 extends unknown[]
> = {
(...args: A01): unknown; (...args: A02): unknown; (...args: A03): unknown;
(...args: A04): unknown; (...args: A05): unknown; (...args: A06): unknown;
(...args: A07): unknown; (...args: A08): unknown; (...args: A09): unknown;
(...args: A10): unknown; (...args: A11): unknown; (...args: A12): unknown;
(...args: A13): unknown; (...args: A14): unknown; (...args: A15): unknown;
(...args: A16): unknown; (...args: A17): unknown; (...args: A18): unknown;
(...args: A19): unknown; (...args: A20): unknown; (...args: A21): unknown;
(...args: A22): unknown; (...args: A23): unknown; (...args: A24): unknown;
(...args: A25): unknown; (...args: A26): unknown; (...args: A27): unknown;
(...args: A28): unknown; (...args: A29): unknown; (...args: A30): unknown;
(...args: A31): unknown; (...args: A32): unknown; (...args: A33): unknown;
(...args: A34): unknown; (...args: A35): unknown; (...args: A36): unknown;
(...args: A37): unknown; (...args: A38): unknown; (...args: A39): unknown;
(...args: A40): unknown;
}
```
There's a minor issue with the solutions in the issue thread, in that they only work if one of the overloads takes either no parameters or only unknown parameters, which is not the case for `on`. The solution by jcalz doesn't have this problem, but it would require writing 41 \* 40 = 1640 function signatures, which is impractical.
To remedy the problem we can simply add this extra overload by inferring on `T & ((...args: unknown[]) => unknown)` instead of `T`, and removing any `unknown[]` elements from the resulting list.
```
type ElementTypeWithoutUnknown<T extends unknown[]> =
{[K in keyof T]: unknown[] extends T[K] ? never : T[K]}[number]
```
Now we have everything we need to define `GetOverloadParameters`:
```
type GetOverloadParameters<T extends (...args: any) => unknown> =
T & ((...args: unknown[]) => unknown) extends BuildOverloads<
infer A01, infer A02, infer A03, infer A04, infer A05, infer A06, infer A07,
infer A08, infer A09, infer A10, infer A11, infer A12, infer A13, infer A14,
infer A15, infer A16, infer A17, infer A18, infer A19, infer A20, infer A21,
infer A22, infer A23, infer A24, infer A25, infer A26, infer A27, infer A28,
infer A29, infer A30, infer A31, infer A32, infer A33, infer A34, infer A35,
infer A36, infer A37, infer A38, infer A39, infer A40
> ?
ElementTypeWithoutUnknown<[
A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15,
A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, A30,
A31, A32, A33, A34, A35, A36, A37, A38, A39, A40
]> : never
```
And we can apply it like this:
```
type EventName = GetOverloadParameters<Electron.BrowserWindow['on']>[0]
// type EventName = "always-on-top-changed" | "app-command" | .. | "will-resize"
```
(Note that the type `Electron.BrowserWindow` denotes the type of the object rather than the class, so there's no need to do `InstanceType<typeof Electron.BrowserWindow>`.)
Because the union of 36 event names is too big to show in a hover type, we can declare a couple of helpers to group them based on the number of dashes in the name (just to verify they are all present, you won't need to do this in your code):
```
type Dash0<S extends string> = S extends `${string}-${string}` ? never : S
type Dash1<S extends string> = S extends `${string}-${Dash0<infer _>}` ? S : never
type Dash2<S extends string> = S extends `${string}-${Dash1<infer _>}` ? S : never
type Dash3<S extends string> = S extends `${string}-${Dash2<infer _>}` ? S : never
type EventName1 = Dash0<EventName>
// EventName1 = "blur" | "close" | "closed" | "focus" | "hide" | "maximize" |
// "minimize" | "move" | "moved" | "resize" | "resized" |
// "responsive" | "restore" | "show" | "swipe" | "unmaximize" |
// "unresponsive"
type EventName2 = Dash1<EventName>
// EventName2 = "app-command" | "rotate-gesture" | "session-end" | "sheet-begin" |
// "sheet-end" | "will-move" | "will-resize"
type EventName3 = Dash2<EventName>
// EventName3 = "enter-full-screen" | "leave-full-screen" | "page-title-updated" |
// "ready-to-show" | "scroll-touch-begin" | "scroll-touch-edge" |
// "scroll-touch-end" | "system-context-menu"
type EventName4 = Dash3<EventName>
// EventName4 = "always-on-top-changed" | "enter-html-full-screen" |
// "leave-html-full-screen" | "new-window-for-tab"
```
[TypeScript playground](https://www.typescriptlang.org/play?jsx=0#code/JYWwDg9gTgLgBAUQDYFMDGMoQHZwGZYhwDkKqGW2xAUNTAJ5gpwCCUA5gM4A8AYnCgAeMFNgAmnOAAoAdHICGHTgC4487PQDaAXQCUcALwA+OAFdsAa2wQA7thMG4-ISPGSA3tTjS5MxV1VgbDwUKFYARl1VADcIYDEvHwUlQODQ1gAmKLhY+OoAXzgAfjhNFnCAGkztOFVsFGjQ2jF0JEVmPHMMYBx8KQbRGFVibHDiKqRVKWw60xAAI1D9Yxy4sWzchJa0NqgOrpge3Dx+xuwhkmwM8bhJ6RU4Tkwg9mWTTY212gYmOAAVFBPNhcQysJTcH4oCB4fBGagAenh3jgAD0it9GMxkCgQIM-piAOrAGAACwgphgAFVLNY7Nw-gJhKIJGYabZsDoHIl3JoANJwIJwCwoejQ-7aVTmKzsnSM1wsv58moleqNMKqRW87T5TTYOaLKDaDG-AFPbG4874phE0nkqlsuyg814wnEskU6nSumaKW0jnaKqaEZjKpPKAvAOlEbXKp6hahbTaOGI5Fo43MABCpmASDEAHk1UgIPIJNxEiwAAzhOXMyS+mWRysZGtuVle-1VSsAZhbLPrdh0FXLFYALL26w6O6wKwBWcdtv2D6cANnn-Y7w4A7GvJ0vKwAOHftvcVgCcR8XAfL4QrF4bnfC1ZctYX94izefrfXg+vPc-fd3RtwjHf8J2PIC51A18ByvbxylXKDvyA7dEMAh9D1Q8Chzg8Jz0wy9OwyW98LfFgMifJkvzQ8sMg-SiAKwzI-3osCCMyECWOgjc4IySDOKQwiEP4tDMhQ4SsJojDxLYsi8Ok0iu2I+SYOw1guwo+VWIUujNK4vcu2Y3SBPLLsOKMkSWC7PjzMYyyhJsgiTLEhyFKklyVLUuT3O41gRyU7ydGoBw4E8bxZGSAJp0iSVJwAbiSPwUmnLIYvbeLwsSyLu2yddYsSDL-AeSsRxyuKEsK1RKxnUq0vKpLK2XGq-TysLfAq6dNya9l0ra+qK33Lq7B6iKirPQbsBauqspvcbhsyorH1mqaFpSrjJoK+rwi7JaNumkrUua5bKvCaqDu6-LeumxqzqGo6Ik6m6Jru8oBse9bLoW08do+yqiO+kbfuitaLoBzJVty56Mm2t7If24HWtBsjTrWyHrpR3aioyB74ch170Z+zIvphjHKsU2aQfm0mgYhkm1PBsracs6GccZ0z-sptTkZpgm7PJhGOcs7HucRrs8eFgWuyJlmeb88n8nTOAAHEUBgAtQiLEsAAVFHkXERCgHgGSg2n1HoN4uK5bwGQAMmkWmkPN9d9CgrMc3zQti1LRJvCCEIwkrSoBTSf2KwyKpffSbtw+D6cR2jv3pxnePI4rZdk5DzdVJ9mOD3T6dTzz8oK0Lx8S7DoOE-KLsS7j72K8jk6S7T+v-fCTOW4ifcS4LjuyOL3vyKzgfy4j-2ocLjI44HpOB+b0fRInru6-n2TC8UtfA5XrsR5zgy16nrek+X3e5939ut673vJcLvzEhMdFvGdS1XVtD1J24TQ64DztQ5-6vY5-jPBqP92653zg+fu5RA7lHLlXB8U9yhH2RBEZu5RQHhEvuUHufdCLQNooRf+ZEEG8UEoRUBGRMEZGwevL+6lOzb3oYQ0y9CgFdlQV2UBot6HYNvt4JMtQ4CqiaCmAAcnmP4CBVC8GgI8UAYAkDADQMSegVRSShGYMASQ1g4BoBJOgCwcAbB6P1nAAABn8UxagkB7BLPQOAJJ5CSHUHACAHsSz4BkaY+2gFHaTlMTIBWCAzgwBEbrZgjhlaqzcWIbWUAwn6x4NiCgOAZAZiwDYTgoQiTiFsEGHAxAkyaArEaFM3g0wKwACKOJJBWbgABlecYYXjBQaVBUxAASdwTTsDsHyAAWk6d03pliVQDHVHAOpdBMRwCqZwEk4R6mNOeD0lp84OldOWb0gZ7hZk1O4PPAA+kYfIIyJkCKEVAKZvxdkZEWVBIZqy2mDM2f0zpuyFmHOOachpdQxlXOYLsrsdzOIPNBK0zi6yhmvJ2dU25nyTnFDOb8tUtAUwAAlXHpExWENRcBISSEWEWGweKICPBQMwXFaAIDgFQCIVkRxOABP+YgYJoTcTVkcLs2pQTBhspQMmJEZT0TMp5ecPlzZOXVIWaKkJYSBWpmFZCFlvKwk9klXM25Mq+XyqFYE1lYSxzqpJECrVcqESCtROiIAA) | Short answer: not possible, see <https://github.com/microsoft/TypeScript/issues/32164>.
In your case, I recommend hard coding the event types.
Overloads are represented as intersections, not unions. Converting the overloads to unions is messy, but possible. I don't recommend using my solution. The type only works with 1-50 arguments (the file size escalates quickly when adding support for more arguments).
```js
ParameterOfOverloads<electron.BrowserWindow['on']>[number][0]
```
<https://gist.github.com/tscpp/e4d5f7b9cb27f58e71f4e2d788d4fd27> |
311,124 | I can't figure out how to set up a simple search. I am trying to find all messages that 'start with' a particular string. Here is an example of 4 message
```
1) Subject: ABC DEF
2) Subject: ABC XYZ
3) Subject: RE: ABC DEF
4) Subject: FW: ABC XYX
```
From this list; I only want to search for message 1 and message 2. But for some reason; the advanced find only show me options like
```
a) contains
b) is
c) doesn't contain
d) word starts with
..... and so on
```
but none of those work for me :( | 2011/07/16 | [
"https://superuser.com/questions/311124",
"https://superuser.com",
"https://superuser.com/users/90470/"
] | There is no space between NOT and (Subject... ).
the right search is
(subject: "ABC ") and NOT(subject: "RE: ") and NOT(subject: "FW: " ) | Try this:
>
> subject:abc and subject:def not subject:"re:"
>
>
>
<http://www.groovypost.com/forum/microsoft-office/microsoft-outlook-search-syntax-t95537.html> |
35,613,103 | Today i ran into a problem. I was trying to install a plugin via the Wordpress enviroment and all of a sudden I got the following error: "an error occurred while installing IshYoBoy Multicorp Assets: unable to create directory ishyoboy-multicorp-assets."
I have already tried to give the files in wp-content the 777 permission but that didn't work. Installing the plugins locally works though (downloading the plugin and placing it in the destination folder). It feels like I have tried everything I know. | 2016/02/24 | [
"https://Stackoverflow.com/questions/35613103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5967896/"
] | Simply append owner and group arguments to the `synced_folder` config in the Vagrantfile
>
> ,:owner=> 'www-data', :group=>'www-data'
>
>
>
### Example
```
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/precise64"
config.vm.synced_folder "wp-root/", "/var/www",:owner=> 'www-data', :group=>'www-data'
config.vm.network "forwarded_port", guest: 80, host: 8000
end
``` | Make sure that your web server has permission to write to that folder. Changing the permissions to 0777 may not solve the problem, and it's not a great way to go anyway.
If the folder is currently owned by "root" or some other user, try switching the owner to apache, www, or whatever your server uses for ownership using the chown command. |
48,201,696 | I'm loading image url using glide and applying rounded corner transformation. It works fine for first setup of recyclerview. Later when i call `notifydatasetchanged()` after pagination it becomes square. What am I missing?
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0, RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | 2018/01/11 | [
"https://Stackoverflow.com/questions/48201696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923473/"
] | Use this diskCacheStrategy Saves the media item after all transformations to cache.
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0,
RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | If the problem happens after calling `notifydatasetchanged()` then don't use it. In fact, that method takes a lot of CPU resources and recreate every item in recyclerview even these items have been already added.
When paginating use `notifyItemInserted` or `notifyItemRangeInserted`. It'll allow you to avoid your problem. |
48,201,696 | I'm loading image url using glide and applying rounded corner transformation. It works fine for first setup of recyclerview. Later when i call `notifydatasetchanged()` after pagination it becomes square. What am I missing?
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0, RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | 2018/01/11 | [
"https://Stackoverflow.com/questions/48201696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923473/"
] | Use this diskCacheStrategy Saves the media item after all transformations to cache.
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0,
RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | Don't use `notifyDataSetChanged()` method for pagination at all. instead use `notifyItemInserted()`. [DiffUtil](https://developer.android.com/reference/android/support/v7/util/DiffUtil.html) is a better choice for your apps performance.
If you're loading your image inside `onBindViewHolder()` method this problem shouldn't happen. |
48,201,696 | I'm loading image url using glide and applying rounded corner transformation. It works fine for first setup of recyclerview. Later when i call `notifydatasetchanged()` after pagination it becomes square. What am I missing?
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0, RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | 2018/01/11 | [
"https://Stackoverflow.com/questions/48201696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923473/"
] | Use this diskCacheStrategy Saves the media item after all transformations to cache.
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0,
RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | ```
datalist.clear(); //clear old data before adddi
SampleAdapter adapter = (SampleAdapter) recyclerview.getAdapter();
recyclerview.setAdapter(null);
recyclerview.setAdapter(adapter);
datalist.addAll(resource.getData());//add new data
adapter.notifyDataSetChanged();
```
I also had the same problem and fixed it in this way |
48,201,696 | I'm loading image url using glide and applying rounded corner transformation. It works fine for first setup of recyclerview. Later when i call `notifydatasetchanged()` after pagination it becomes square. What am I missing?
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0, RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | 2018/01/11 | [
"https://Stackoverflow.com/questions/48201696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923473/"
] | If the problem happens after calling `notifydatasetchanged()` then don't use it. In fact, that method takes a lot of CPU resources and recreate every item in recyclerview even these items have been already added.
When paginating use `notifyItemInserted` or `notifyItemRangeInserted`. It'll allow you to avoid your problem. | ```
datalist.clear(); //clear old data before adddi
SampleAdapter adapter = (SampleAdapter) recyclerview.getAdapter();
recyclerview.setAdapter(null);
recyclerview.setAdapter(adapter);
datalist.addAll(resource.getData());//add new data
adapter.notifyDataSetChanged();
```
I also had the same problem and fixed it in this way |
48,201,696 | I'm loading image url using glide and applying rounded corner transformation. It works fine for first setup of recyclerview. Later when i call `notifydatasetchanged()` after pagination it becomes square. What am I missing?
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0, RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
``` | 2018/01/11 | [
"https://Stackoverflow.com/questions/48201696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923473/"
] | Don't use `notifyDataSetChanged()` method for pagination at all. instead use `notifyItemInserted()`. [DiffUtil](https://developer.android.com/reference/android/support/v7/util/DiffUtil.html) is a better choice for your apps performance.
If you're loading your image inside `onBindViewHolder()` method this problem shouldn't happen. | ```
datalist.clear(); //clear old data before adddi
SampleAdapter adapter = (SampleAdapter) recyclerview.getAdapter();
recyclerview.setAdapter(null);
recyclerview.setAdapter(adapter);
datalist.addAll(resource.getData());//add new data
adapter.notifyDataSetChanged();
```
I also had the same problem and fixed it in this way |
2,245 | >
> Только три процента всей воды на Земле явля(Е/Ю)тся пресной
>
>
>
What letter should I choose there? Е or Ю? | 2013/05/15 | [
"https://russian.stackexchange.com/questions/2245",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/170/"
] | In this case the following rule would apply (Rosenthal et al., №184.2):
>
> Форма единственного числа сказуемого указывает на совокупность предметов, форма множественного числа – на отдельные предметы. Ср.: *В городе строится пять объектов соцкультбыта* (единое нерасчлененное представление о действии). – *В крупнейших городах страны строятся еще пять объектов соцкультбыта* (расчлененное представление о действии).
>
>
>
Since we do not refer each percent separately, we should use the singular form. | три процента ... являются, так как "являться" - глагол относится к 1 спряжению. <http://www.gramota.ru/class/coach/tbgramota/45_91> |
50,727,539 | I made some elements in JavaScript that i add to the website. When i add an eventlistener to the button, only the first button works and runs the function.
I used to do this before and worked fine, any idea what i'm doing here wrong?
my javascript function:
```js
function laadProjectDetails(){
fetch("restservices/projectdetails")
.then(response => response.json())
.then(function(myJson) {
for (const object of myJson) {
var projextX = '<div class="row"><div class="cause content-box"><div class="col-md-5 col-sm-6"><div class="img-wrapper"><div class="overlay"></div><img class="img-responsive" src="assets/img/causes/img-1.jpg" alt=""></div></div><div class="col-md-7 col-sm-6"><div class="info-block"><h4><a href="#">'+object.projectNaam+'</a></h4><p>'+ object.projectBeschrijving +'</p><div class="foundings"><div class="progress-bar-wrapper min"><div class="progress-bar-outer"><p class="values"><span class="value one">Opgehaald: XXXX</span>-<span class="value two">Doel: €'+object.totaalBedrag+'</span></p><div class="progress-bar-inner"><div class="progress-bar"><span data-percent="55"><span class="pretng">55%</span> </span></div></div></div></div></div><div class="donet_btn"><input id="'+object.projectID+'" type="submit" value="Doneer" class="btn btn-min btn-solid"></input></div></div></div></div></div>';
document.querySelector("#showProject").innerHTML += projextX;
var valueVerwijder = document.querySelector("div.donet_btn input[value='Doneer']");
valueVerwijder.addEventListener("click", doneerFunc);
}
});
}
laadProjectDetails();
function doneerFunc(){
console.log("test");
}
``` | 2018/06/06 | [
"https://Stackoverflow.com/questions/50727539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9528069/"
] | I wasn't satisfied with the previous answer (specially concerning the beta macOS component) ... and I really wanted to install Mojave, so I went hunting for some docs or verification. The closest I got is this quoted answer from Apple Developer Technical Support related to a failed submission with an odd ITMS error: <https://stackoverflow.com/a/44323416/322147>
>
> I looked at the .ipa you provided that was giving trouble, and
> compared it to the one successfully submitted to the App Store. The
> one giving you trouble was built on a beta version of macOS, which is
> not supported for distribution. Apps released to the App Store need to
> be built for a GM version of macOS, with a GM version of Xcode, using
> a GM version of the iOS SDK.
>
>
> Normally, apps submitted with any beta software receive a message
> indicating this problem, and the message you received was completely
> misleading.
>
>
> | No, you can not submit a build of your app that was built with either Xcode 10 or macOS Mojave at this time. Apple does not allow apps built with any beta software to be published. |
67,184,541 | I am trying to extract a CSV report from our company's ASP.NET ReportViewer via selenium.
I have got as far as clicking the the export dropdown menu (see image), but I am unable to click the csv button (which will download the CSV report) I have tried waiting then clicking with no results.
**My code:**
```
driver = webdriver.Chrome(r'C:\Users\User\chromedriver.exe')
url = 'Logon.aspx' # target url
driver.get(url) # open url
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_txtUsername"]').send_keys('_user') # username cred
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_txtPassword"]').send_keys('_pswd') # pass
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_btnLogin"]').click() # click login btn
driver.find_element_by_xpath('//*[@id="JobsReports"]').click() # click job report btn
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_TRCB3"]').click() # click 'Task details' check box
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_RunReportsBtn"]').click() # click view report btn
time.sleep(3)
driver.switch_to.window(driver.window_handles[-1])
driver.implicitly_wait(120)
# driver.find_element_by_xpath('//*[@id="ReportViewer1_ctl05_ctl05_ctl00_ctl00"]/table/tbody/tr/td/input').click()
# driver.implicitly_wait(120)
driver.find_element_by_xpath('//*[@id="ReportViewer1_ctl05_ctl04_ctl00_ButtonLink"]').click() # click save dropdown
driver.implicitly_wait(3)
driver.find_element_by_xpath('/html/body/form/div[3]/div/span/div/table/tbody/tr[3]/td/div/div/div[4]/table/tbody/tr/td/div[2]/div[2]/a').click() # click 'CSV' to download
```
**HTML / Layout:**
[HTML SNIPPET](https://i.stack.imgur.com/jWP9x.png)
```
<div style="border: 1px solid rgb(51, 102, 153); background-color: rgb(221, 238, 247); cursor: pointer;">
<a title="CSV (comma delimited)" alt="CSV (comma delimited)" onclick="$find('ReportViewer1').exportReport('CSV');" href="javascript:void(0)" style="color: rgb(51, 102, 204); font-family: Verdana; font-size: 8pt; padding: 3px 8px 3px 32px; display: block; white-space: nowrap; text-decoration: none;">CSV (comma delimited)</a>
</div>
```
**Error:**
```
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\Onsite_automation\main.py", line 32, in <module>
driver.find_element_by_xpath('/html/body/form/div[3]/div/span/div/table/tbody/tr[3]/td/div/div/div[4]/table/tbody/tr/td/div[2]/div[2]/a').click() # click 'view report' btn
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=90.0.4430.72)
```
Thanks for your help! | 2021/04/20 | [
"https://Stackoverflow.com/questions/67184541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12734203/"
] | You need to await connection first inorder to use execute function:
```
const [rows] = await (await connection()).execute('SELECT * FROM media');
```
OR
```
const conn = await connection();
const [rows] = await conn.execute('SELECT * FROM media');
``` | You need to await the `connection()` itself, then execute:
```js
app.get('/', async () => {
const connected = await connection();
const [rows] = await connected.execute('SELECT * FROM media');
res.send(rows.length);
});
``` |
5,938,594 | I have a range slider on my site for min-max price ranges. On either side of the slider are two text input boxes. I've created a callback function with the slider which adjusts the vals of the text boxes based on a val change within the slider.
At the same time, I would also like to adjust the values of the slider based on changes to th vals of the text boxes. Right now, the change (also tried keyup) event that I'm binding on the text inputs are not changing the values (position) of the two range slider hands. What's wrong here?
```
$('.price_slider').slider({orientation:"horizontal",range:true, animate:200,min:0,max:10000, step:100,value:0,values:[{{min_rent}},{{max_rent}}], slide:function(event,ui){
$('input#lower_bound').val(ui.values[0]);
$('input#upper_bound').val(ui.values[1]);
}
});
$('input#lower_bound').change(function(){
$('.price_slider').slider("values",[$(this).val(),$('input#upper_bound').val()]);
});
$('input#upper_bound').change(function(){
$('.price_slider').slider("values",[$('input#lower_bound').val(),$(this).val()]);
});
```
EDIT--
Matt, I saw your revision. Just curious if your version is more efficient than mine. Mine does seem to be working but I'm clearly not an expert:
```
$lower.add($upper).change(function () {
var lowEnd=parseInt($lower.val());
var highEnd=parseInt($upper.val());
if(highEnd>lowEnd){
$slider.slider('values', 0, parseInt($lower.val(), 10));
$slider.slider('values', 1, parseInt($upper.val(), 10));
}
else{
$slider.slider('values', 0, parseInt($lower.val(), 10));
$slider.slider('values', 1, parseInt($lower.val(), 10));
$upper.val([$lower.val()]);
}
});
``` | 2011/05/09 | [
"https://Stackoverflow.com/questions/5938594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558699/"
] | * For multi-handle sliders, you need to use `'values'` rather than `'value'` (which you're doing) but `'values'` takes this format:
```
.slider( "values" , index , [value] )
```
* You probably want to enforce `max >= min` when setting the slider values based on the textboxes.
* You are passing the initial values to `.slider()` incorrectly, I don't know where that `{{...}}` nonsense came from (is that a jQuery template?).
* It's generally [not a great idea to use underscores in class names](https://developer.mozilla.org/en/underscores_in_class_and_id_names). Use `-` instead of `_`.
The fixes:
```
var $slider = $('.price-slider'),
$lower = $('#lower_bound'),
$upper = $('#upper_bound'),
min_rent = 1000,
max_rent = 9000;
$lower.val(min_rent);
$upper.val(max_rent);
$('.price-slider').slider({
orientation: 'horizontal',
range: true,
animate: 200,
min: 0,
max: 10000,
step: 100,
value: 0,
values: [min_rent, max_rent],
slide: function(event,ui) {
$lower.val(ui.values[0]);
$upper.val(ui.values[1]);
}
});
$lower.change(function () {
var low = $lower.val(),
high = $upper.val();
low = Math.min(low, high);
$lower.val(low);
$slider.slider('values', 0, low);
});
$upper.change(function () {
var low = $lower.val(),
high = $upper.val();
high = Math.max(low, high);
$upper.val(high);
$slider.slider('values', 1, high);
});
```
Demo: <http://jsfiddle.net/mattball/pLP2e/> | According to the [jQuery UI documentation](http://jqueryui.com/demos/slider/#method-values), `slider('values')` takes index as the second param and value as the third. Try this:
```
$('input#lower_bound').change(function(){
$('.price_slider').slider("values",0,$(this).val());
$('.price_slider').slider("values",1,$('input#upper_bound').val());
});
$('input#upper_bound').change(function(){
$('.price_slider').slider("values",0,$('input#lower_bound').val());
$('.price_slider').slider("values",1,$(this).val());
});
``` |
15,226,630 | I'm struggling on replacing text in each link.
```
$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';
if(preg_match_all($reg_ex, $text, $urls))
{
foreach($urls[0] as $url)
{
echo $replace = str_replace($url,'http://www.sometext'.$url, $text);
}
}
```
From the code above, I'm getting 3x the same text, and the links are changed one by one: everytime is replaced only one link - because I use foreach, I know.
But I don't know how to replace them all at once.
Your help would be great! | 2013/03/05 | [
"https://Stackoverflow.com/questions/15226630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/548278/"
] | You don't use regexes on html. use [DOM](http://php.net/dom) instead. That being said, your bug is here:
```
$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---
```
you never update $text, so you continually trash the replacement on every iteration of the loop. You probably want
```
$text = str_replace(...., $text);
```
instead, so the changes "propagate" | If you want the final variable to contain all replacements change it so something like this...
You basically are not passing the replaced string back into the "subject". I assume that is what you are expecting since it's a bit difficult to understand the question.
```
$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';
if(preg_match_all($reg_ex, $text, $urls))
{
$replace = $text;
foreach($urls[0] as $url) {
$replace = str_replace($url,'http://www.sometext'.$url, $replace);
}
echo $replace;
}
``` |
11,332,269 | I need to create route `/branch` which run script `/lib/branch.rb`, I need to display only one string which displayed in browser my current git branch which deployed at staging server. I already write script, but cant understand how to mount it to rails routes | 2012/07/04 | [
"https://Stackoverflow.com/questions/11332269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/548618/"
] | Try the following solutions by Directly targeting the `ul`
***Solution A***:
---
```js
// previous (following) is very inefficient and slow:
// -- $(this).find("ul.sub-menu").not("ul.sub-menu li ul.sub-menu").slideDown();
// Rather, target the exact ULs which are Direct Children
$("ul.menu").find('li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').slideUp();
// If something Slides Down, it should slide up as well,
// instead of plain hide(), your choice - :)
}
);
```
***Solution B***:
---
for more Precision over both ULs
**Update**: Solution A works fine and makes B redundant
```
$("ul.menu").find('> li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').hide();
}
);
$("ul.sub-menu").find('> li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').hide();
}
);
```
Check the **[Fiddle](http://jsfiddle.net/OMS_/XDkXq/)** | This is untested .. and you have to expand it a bit.
```
$('ul.menu li').siblings('ul:first-child').on('click', function() {
if($(this).is(':visible')) {
$(this).hide();
}
else {
$(this).show();
}
})
$('ul.menu li').siblings('ul:first-child').hover(
function() {
$(this).show();
},
function() {
$(this).hide();
}
)
```
Edit: As I see your structure is inconsistent. Sometimes you place a list IN a li element, sometimes it is placed as a sibling... |
32,811,437 | Is it wrong way to pass $\_GET variable in MVC design?
```
http://localhost/video?id=123
```
I started to learn MCV design pattern and some people were telling me, that I'm doing wrong. The correct way would be:
```
http://localhost/video/?id=123
```
They were saying its kinda of 'standard' for passing $\_GET in MVC. The slash isnt needed only if you access file directly, like:
```
http://localhost/video.php?id=123
``` | 2015/09/27 | [
"https://Stackoverflow.com/questions/32811437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This has nothing to do with MVC. MVC is just a way to organize your code.
The way you rewrite/route URLs to controllers is up to you. Both ways work, as long as the URL matches what you defined on your backend! | When passing parameters that would bring up information from your DB or http server is ok to use GET.
When sending information to modify the state of anything, change data in your DB or on your http server you should always use POST |
72,170,760 | I'm new in VBA and actually don't know how to deal with that task. Maybe you can help me.
I have two tables in two sheets.
Table from sheet 1 is updated daily.
What I need to do is check if any value in column A (sheet 1) is in column A (sheet 2).
If yes, then do nothing.
If no, then copy whole row into the table in sheet 2.
Basing on google results I started to write some code but I stuck.
```
Dim source As Worksheet
Dim finaltbl As Worksheet
Dim rngsource As Range
Dim rngfinaltbl As Range
'Set Workbook
Set source = ThisWorkbook.Worksheets("Sheet 1")
Set finaltbl = ThisWorkbook.Worksheets("Sheet 2")
'Set Column
Set rngsource = source.Columns("A")
Set rngfinaltbl = finaltbl.Columns("A")
```
I assume that next I need to write some loop but I really don't know how it works. | 2022/05/09 | [
"https://Stackoverflow.com/questions/72170760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902492/"
] | Update Worksheet With Missing (Unique) Rows (Dictionary)
--------------------------------------------------------
* Adjust the values in the constants section.
```vb
Sub UpdateData()
' Source
Const sName As String = "Sheet1"
Const sFirstCellAddress As String = "A2"
' Destination
Const dName As String = "Sheet2"
Const dFirstCellAddress As String = "A2"
' Reference the destination worksheet.
Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets(dName)
Dim drg As Range
Dim dCell As Range
Dim drCount As Long
' Reference the destination data range.
With dws.Range(dFirstCellAddress)
Set dCell = .Resize(dws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If dCell Is Nothing Then Exit Sub ' no data in column range
drCount = dCell.Row - .Row + 1
Set drg = .Resize(drCount)
End With
Dim Data As Variant
' Write the values from the destination range to an array.
If drCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = drg.Value
Else
Data = drg.Value
End If
' Write the unique values from the array to a dictionary.
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim Key As Variant
Dim dr As Long
For dr = 1 To drCount
Key = Data(dr, 1)
If Not IsError(Key) Then ' exclude errors
If Len(Key) > 0 Then ' exclude blanks
dict(Key) = Empty
End If
End If
Next dr
' Reference the source worksheet.
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets(sName)
Dim srg As Range
Dim sCell As Range
Dim srCount As Long
' Reference the source data range.
With sws.Range(sFirstCellAddress)
Set sCell = .Resize(sws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If sCell Is Nothing Then Exit Sub ' no data in column range
srCount = sCell.Row - .Row + 1
Set srg = .Resize(srCount)
End With
' Write the values from the source range to an array.
If srCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = srg.Value
Else
Data = srg.Value
End If
Dim surg As Range
Dim sr As Long
' Loop through the source values...
For sr = 1 To srCount
Key = Data(sr, 1)
If Not IsError(Key) Then ' exclude errors
If Len(Key) > 0 Then ' exclude blanks
If Not dict.Exists(Key) Then ' if source value doesn't exist...
dict(Key) = Empty ' ... add it (to the dictionary)...
If surg Is Nothing Then ' and combine the cell into a range.
Set surg = srg.Cells(sr)
Else
Set surg = Union(surg, srg.Cells(sr))
End If
End If
End If
End If
Next sr
' Copy all source rows in one go below ('.Offset(1)') the last cell.
If Not surg Is Nothing Then
surg.EntireRow.Copy dCell.Offset(1).EntireRow
End If
MsgBox "Data updated.", vbInformation
End Sub
``` | No you don't need a loop. You need the Find function for a Range
See [Documentation for Find Method (Excel)](https://learn.microsoft.com/en-us/office/vba/api/excel.range.find)
also [Excel VBA Find A Complete Guide](https://excelmacromastery.com/excel-vba-find/) |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | Given your original problem statement,
>
> I need to use lists for my program and needed to decide if I use std::vector or std::list. The problem with vector is that there is no remove method and with list that there is no operator [].
>
>
>
there is no need to create your own list class (this is not a wise design choice anyway, because `std::list` does not have a virtual destructor, which is a strong indication that it is not intended to be used as a base class).
You can still achieve what you want using `std::vector` and the `std::remove` function. If `v` is a `std::vector<T>`, then to remove the value `value`, you can simply write:
```
#include <vector>
#include <algorithm>
T value = ...; // whatever
v.erase(std::remove(v.begin(), v.end(), value), v.end());
``` | Vectors have the [erase method](http://www.cppreference.com/wiki/stl/vector/erase) that can remove elements. Is that not sufficient? |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | Given your original problem statement,
>
> I need to use lists for my program and needed to decide if I use std::vector or std::list. The problem with vector is that there is no remove method and with list that there is no operator [].
>
>
>
there is no need to create your own list class (this is not a wise design choice anyway, because `std::list` does not have a virtual destructor, which is a strong indication that it is not intended to be used as a base class).
You can still achieve what you want using `std::vector` and the `std::remove` function. If `v` is a `std::vector<T>`, then to remove the value `value`, you can simply write:
```
#include <vector>
#include <algorithm>
T value = ...; // whatever
v.erase(std::remove(v.begin(), v.end(), value), v.end());
``` | In addition to other excellent comments, the best way to extend a standard container is not by derivation, but writing free functions. For instance, see how [Boost String Algorithms](http://www.boost.org/doc/libs/1_37_0/doc/html/string_algo.html) can be used to extend `std::string` and other string classes. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | Depending on your needs, you should use `std::vector` (if you need often appends/removes at the end, and random access), or `std::deque` (if you need often appends/removes at the end or at the beginning, and your dataset is huge, and still want random access). Here is a good picture showing you how to make the decision:
[](https://i.stack.imgur.com/qWf2C.png)
(source: [adrinael.net](http://adrinael.net/containerchoice.png)) | You have to move all your template code into header. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | Given your original problem statement,
>
> I need to use lists for my program and needed to decide if I use std::vector or std::list. The problem with vector is that there is no remove method and with list that there is no operator [].
>
>
>
there is no need to create your own list class (this is not a wise design choice anyway, because `std::list` does not have a virtual destructor, which is a strong indication that it is not intended to be used as a base class).
You can still achieve what you want using `std::vector` and the `std::remove` function. If `v` is a `std::vector<T>`, then to remove the value `value`, you can simply write:
```
#include <vector>
#include <algorithm>
T value = ...; // whatever
v.erase(std::remove(v.begin(), v.end(), value), v.end());
``` | The obvious stuff has already been described in details:
But the methods you choose to implement??
* Destructor.
+ Not required compiler will generate that for you.
* The two different versions of operator[] are pointless
+ Also you should be uisng std::list::size\_type as the index
+ Unless you intend to support negative indexes.
* There are no const versions of operator[]
* If you are going to implement [] you should also do at()
* You missed out all the different ways of constructing a list.
* Containers should define several types internally
+ see <http://www.sgi.com/tech/stl/Container.html> |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | You have to move all your template code into header. | There is no need to call destructor of std::list , because you already derive from std::list when destructor called for myList automatically std::list destructor will be called. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | Vectors have the [erase method](http://www.cppreference.com/wiki/stl/vector/erase) that can remove elements. Is that not sufficient? | You have to move all your template code into header. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | Depending on your needs, you should use `std::vector` (if you need often appends/removes at the end, and random access), or `std::deque` (if you need often appends/removes at the end or at the beginning, and your dataset is huge, and still want random access). Here is a good picture showing you how to make the decision:
[](https://i.stack.imgur.com/qWf2C.png)
(source: [adrinael.net](http://adrinael.net/containerchoice.png)) | In addition to other excellent comments, the best way to extend a standard container is not by derivation, but writing free functions. For instance, see how [Boost String Algorithms](http://www.boost.org/doc/libs/1_37_0/doc/html/string_algo.html) can be used to extend `std::string` and other string classes. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | The obvious stuff has already been described in details:
But the methods you choose to implement??
* Destructor.
+ Not required compiler will generate that for you.
* The two different versions of operator[] are pointless
+ Also you should be uisng std::list::size\_type as the index
+ Unless you intend to support negative indexes.
* There are no const versions of operator[]
* If you are going to implement [] you should also do at()
* You missed out all the different ways of constructing a list.
* Containers should define several types internally
+ see <http://www.sgi.com/tech/stl/Container.html> | There is no need to call destructor of std::list , because you already derive from std::list when destructor called for myList automatically std::list destructor will be called. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | All template code should be put in header file. This fill fix linking problems (that's the simplest way).
The reason it happens is because compilers compiles every source (.cc) file separately from other files. On the other hand it needs to know what code exactly it needs to create (i.e. what is the T in template is substituted with), and it has no other way to know it unless the programmer tells it explicitly or includes all the code when template instantiation happens. I.e. when mylist.cc is compiled, it knows nothing about mylist users and what code needs to be created. On the other hand if listuser.cc is compiled, and all the mylist code is present, the compiler creates needed mylist code. You can read more about it in [here](http://www.iis.sinica.edu.tw/~kathy/vcstl/templates.htm) or in Stroustrup.
Your code has problems, what if user requests negative or too large (more than amount of elements in the list). And i didn't look too much.
Besides, i don't know how u plan to use it, but your operator[] is O(N) time, which will probably easily lead to O(N\*N) loops... | In addition to other excellent comments, the best way to extend a standard container is not by derivation, but writing free functions. For instance, see how [Boost String Algorithms](http://www.boost.org/doc/libs/1_37_0/doc/html/string_algo.html) can be used to extend `std::string` and other string classes. |
366,432 | I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas? | 2008/12/14 | [
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | All template code should be put in header file. This fill fix linking problems (that's the simplest way).
The reason it happens is because compilers compiles every source (.cc) file separately from other files. On the other hand it needs to know what code exactly it needs to create (i.e. what is the T in template is substituted with), and it has no other way to know it unless the programmer tells it explicitly or includes all the code when template instantiation happens. I.e. when mylist.cc is compiled, it knows nothing about mylist users and what code needs to be created. On the other hand if listuser.cc is compiled, and all the mylist code is present, the compiler creates needed mylist code. You can read more about it in [here](http://www.iis.sinica.edu.tw/~kathy/vcstl/templates.htm) or in Stroustrup.
Your code has problems, what if user requests negative or too large (more than amount of elements in the list). And i didn't look too much.
Besides, i don't know how u plan to use it, but your operator[] is O(N) time, which will probably easily lead to O(N\*N) loops... | The obvious stuff has already been described in details:
But the methods you choose to implement??
* Destructor.
+ Not required compiler will generate that for you.
* The two different versions of operator[] are pointless
+ Also you should be uisng std::list::size\_type as the index
+ Unless you intend to support negative indexes.
* There are no const versions of operator[]
* If you are going to implement [] you should also do at()
* You missed out all the different ways of constructing a list.
* Containers should define several types internally
+ see <http://www.sgi.com/tech/stl/Container.html> |
10,453,431 | Is there any open source findbugs detectors extensions, espcially for performance bugs, for low-latency? I didn't find any meaningful extension beyond barebone findbugs impl. | 2012/05/04 | [
"https://Stackoverflow.com/questions/10453431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294552/"
] | Your code seems ok - did you copy the db to the ressource folder of your project?
**EDIT**
Make sure you access your db file with something like that:
```
- (void) initializeDB {
// Get the database from the application bundle
NSString* path = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
NSLog(@"Opening Database");
}
else
{
// Call close to properly clean up
sqlite3_close(database);
NSAssert1(0, @"Error: failed to open database: '%s'.",
sqlite3_errmsg(database));
}
}
``` | The database file you add to the project will be embedded in the main `NSBundle` (see `[NSBundle mainBundle]`).
In order to do what you want, you need to copy the database from the main bundle to the documents folder before trying to access it. Otherwise, as you are experiencing, you will not be able to find the SQLite DB on the document's folder. |
10,453,431 | Is there any open source findbugs detectors extensions, espcially for performance bugs, for low-latency? I didn't find any meaningful extension beyond barebone findbugs impl. | 2012/05/04 | [
"https://Stackoverflow.com/questions/10453431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294552/"
] | Your code seems ok - did you copy the db to the ressource folder of your project?
**EDIT**
Make sure you access your db file with something like that:
```
- (void) initializeDB {
// Get the database from the application bundle
NSString* path = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
NSLog(@"Opening Database");
}
else
{
// Call close to properly clean up
sqlite3_close(database);
NSAssert1(0, @"Error: failed to open database: '%s'.",
sqlite3_errmsg(database));
}
}
``` | You can copy your database, click finder and write this address(/Users/administrator/Library/Application Support/iPhone Simulator/6.1/Applications/) in finder click ok.
You will get documentary path.
Open your project document file and paste your database.... |
10,453,431 | Is there any open source findbugs detectors extensions, espcially for performance bugs, for low-latency? I didn't find any meaningful extension beyond barebone findbugs impl. | 2012/05/04 | [
"https://Stackoverflow.com/questions/10453431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294552/"
] | The database file you add to the project will be embedded in the main `NSBundle` (see `[NSBundle mainBundle]`).
In order to do what you want, you need to copy the database from the main bundle to the documents folder before trying to access it. Otherwise, as you are experiencing, you will not be able to find the SQLite DB on the document's folder. | You can copy your database, click finder and write this address(/Users/administrator/Library/Application Support/iPhone Simulator/6.1/Applications/) in finder click ok.
You will get documentary path.
Open your project document file and paste your database.... |
2,318,002 | $$|x-2|+|x+3|= 5$$
What are the real values of $x$ satisfies the equation?
I tried doing this but it somehow did not work. Could someone explaim why please? Here's my workings :
$$|x-2|+|x+3|=5$$
$$\Rightarrow (x-2)+(x+3)=5$$
$$\Rightarrow x+2+x+3=5$$
$$\Rightarrow x=6$$
$$\Rightarrow x=3$$
The answer is $[-3,2]$ | 2017/06/11 | [
"https://math.stackexchange.com/questions/2318002",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/454081/"
] | Hint:
For a number to be bigger than $340$.
The first digit can be either $3$ or $4$.
If the first digit is $3$, the second digit must be $4$ and the last digit can be anything.
If the first digit is $4$, the last two digit can be anything.
Can you compute the probability now? | In general suppose we have an alphabet of $n$ characters and a fixed permutation $a\_1,a\_2,\dots, a\_k$ of them. We select a permutation of length $k$ of the alphabet randomly, what is the probability it is less than or equal to $a\_1,a\_2,\dots, a\_n$?
This is given by the formula:
$$\frac{1+\sum\limits\_{i=1}^{k-1} f\_i(n-i)^{\underline {k-i}}}{n^{\underline k}}$$
where $x^{\underline n}$ is the falling factorial and $f\_i$ is the number of letters larger than $a\_n$ in the alphabet that do not appear among $a\_0,a\_1,\dots, a\_n$.
This can be calculated in time $\mathcal O (k\log(k))$ |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | Your main method calls the methods but does not use the values returned from those methods.
You should change your `main` method as follows.
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
Change your addSugar() method as follows.
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
//Update occupiedSpace here.
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
System.out.println("I added "+addedAmount + "to the bowl");
// Update occupiedSpace here.
}
}
```
You are not updating your occupiedSpace field when you add sugar.That's why it always stays same. | You should replace
```
sugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
```
by
```
public SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
``` |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | Your code is wrong unfortunately. You Should change this function
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
System.out.println("0");}
}
```
with
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
occupiedSpace = totalCapacity-availableSpace; // you must also write this to change the ocuuppied space too
System.out.println(availableSpace);
}
}
```
Because you construct your sugar bowl with 200 capacity and addin 100 to it later. So
```
if (addedAmount>availableSpace)
```
100 > 200 returns false and it goes directly to the else block which just prints out '0'. This is the logic error you made. But don't worry we all have been there ;)
Actually the line
`occupiedSpace = totalCapacity-availableSpace;`
is essential like
`availableSpace = availableSpace - addedAmount;`
since you used **occupiedSpace** as a property. The formula you wrote at the beginning of the class only executes once, when you call the constructor(and initially both of the values you suctract are 0 since they are primitive int) and **occupiedSpace** stays as **0** unless you change it with some other function call.
But instead if you want **occupiedSpace** or **availableSpace** to be calculated each time you need it you should delete one of them, hence you need only the other one and the **totalCapacity**. Other one can be calculated each time by subtracting the one from **totalCapacity**. If I were you I would use
```
public int getOccupiedSpace(){
return totalCapacity-availableSpace;
}
```
instead of using (which are by the way useles for your case)
```
private int occupiedSpace = totalCapacity-availableSpace;
```
which is just the same
```
private int occupiedSpace = 0;
```
or
```
private int occupiedSpace ;
``` | You should replace
```
sugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
```
by
```
public SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
``` |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).
You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).
I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace;//starts at 0, because there's nothing in the bowl.
/**
* Constructor for the sugar bowl.
* @param totalCapacity The total capacity of the bowl.
*/
public SugarBowl (int totalCapacity){
this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
occupiedSpace = 0;
}
/**
* Shows how much sugar can fit in a spoon.
* @return The size of the spoon
*/
public int spoon(){
return spoonSize;
}
/**
* Returns amount of sugar in the bowl.
* @return The amount of occupied space
*/
public int occupied(){
return occupiedSpace;
}
/**
* Removes the amount of sugar based on the
* number of scoops passed into it.
* @param numberOfScoops The number of scoops
* @return The amount of sugar removed
*/
public int scoops (int numberOfScoops){
int possibleAmountTaken = numberOfScoops * spoonSize;
int actualAmountTaken = 0;
//Think about sugar, even if there is less sugar than the spoon size,
//can a spoon still remove that amount?
//aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
if (possibleAmountTaken<=occupiedSpace){
actualAmountTaken = possibleAmountTaken;
}
else{
//there may still be sugar, just not enough for every scoop, you still have to remove it
//actualAmountTaken = ???
}
occupiedSpace = occupiedSpace - actualAmountTaken;
//what about availableSpace?
//availableSpace = ???
return actualAmountTaken;
}
/**
* Adds the specified amount of sugar to the bowl.
*
* @param addedAmount The amount of sugar added to the bowl
* @return The overflow amount of sugar or 0 if there was no overflow
*/
public int addSugar (int addedAmount){
int overflow = 0;
if (addedAmount>availableSpace){
overflow = addedAmount-availableSpace;
//your bowl is going to be full, what happens to occupiedSpace and availableSpace?
//availableSpace = ???
//occupiedSpace = ???
}
else{
//overflow is already 0 so you don't have to do anything with it
//update availableSpace and occupiedSpace
//availableSpace = ???
//occupiedSpace = ???
}
return overflow;
}
}
```
With your above main example:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
**UPDATE**
The reason you would use this.totalCapacity is because of the following lines of code:
```
public class SugarBowl {
private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
//..
public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
//..
```
Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:
```
public class SugarBowl {
private int bowlTotalCapacity; //totalCapacity for this object
//..
public SugarBowl (int totalCapacity){
bowlTotalCapacity = totalCapacity;
//..
```
You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>.
Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:
```
public class ThisExample {
private int wrongExample = 0;
private int thisExample = 0;
public ThisExample (int wrongExample, int thisExample){
wrongExample = wrongExample;
this.thisExample = thisExample;
}
public int getThisExample(){
return thisExample;
}
public int getWrongExample(){
return wrongExample;
}
}
```
Running the following may help you understand better:
```
public class ThisExampleMain {
public static void main(String[] args) {
ThisExample ts = new ThisExample(50, 50);
//you want this to be 50 but it ends up being 0:
System.out.println("Wrong: " + ts.getWrongExample());
//this returns the correct answer:
System.out.println("Right: " + ts.getThisExample());
}
}
``` | Your code is wrong unfortunately. You Should change this function
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
System.out.println("0");}
}
```
with
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
occupiedSpace = totalCapacity-availableSpace; // you must also write this to change the ocuuppied space too
System.out.println(availableSpace);
}
}
```
Because you construct your sugar bowl with 200 capacity and addin 100 to it later. So
```
if (addedAmount>availableSpace)
```
100 > 200 returns false and it goes directly to the else block which just prints out '0'. This is the logic error you made. But don't worry we all have been there ;)
Actually the line
`occupiedSpace = totalCapacity-availableSpace;`
is essential like
`availableSpace = availableSpace - addedAmount;`
since you used **occupiedSpace** as a property. The formula you wrote at the beginning of the class only executes once, when you call the constructor(and initially both of the values you suctract are 0 since they are primitive int) and **occupiedSpace** stays as **0** unless you change it with some other function call.
But instead if you want **occupiedSpace** or **availableSpace** to be calculated each time you need it you should delete one of them, hence you need only the other one and the **totalCapacity**. Other one can be calculated each time by subtracting the one from **totalCapacity**. If I were you I would use
```
public int getOccupiedSpace(){
return totalCapacity-availableSpace;
}
```
instead of using (which are by the way useles for your case)
```
private int occupiedSpace = totalCapacity-availableSpace;
```
which is just the same
```
private int occupiedSpace = 0;
```
or
```
private int occupiedSpace ;
``` |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).
You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).
I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace;//starts at 0, because there's nothing in the bowl.
/**
* Constructor for the sugar bowl.
* @param totalCapacity The total capacity of the bowl.
*/
public SugarBowl (int totalCapacity){
this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
occupiedSpace = 0;
}
/**
* Shows how much sugar can fit in a spoon.
* @return The size of the spoon
*/
public int spoon(){
return spoonSize;
}
/**
* Returns amount of sugar in the bowl.
* @return The amount of occupied space
*/
public int occupied(){
return occupiedSpace;
}
/**
* Removes the amount of sugar based on the
* number of scoops passed into it.
* @param numberOfScoops The number of scoops
* @return The amount of sugar removed
*/
public int scoops (int numberOfScoops){
int possibleAmountTaken = numberOfScoops * spoonSize;
int actualAmountTaken = 0;
//Think about sugar, even if there is less sugar than the spoon size,
//can a spoon still remove that amount?
//aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
if (possibleAmountTaken<=occupiedSpace){
actualAmountTaken = possibleAmountTaken;
}
else{
//there may still be sugar, just not enough for every scoop, you still have to remove it
//actualAmountTaken = ???
}
occupiedSpace = occupiedSpace - actualAmountTaken;
//what about availableSpace?
//availableSpace = ???
return actualAmountTaken;
}
/**
* Adds the specified amount of sugar to the bowl.
*
* @param addedAmount The amount of sugar added to the bowl
* @return The overflow amount of sugar or 0 if there was no overflow
*/
public int addSugar (int addedAmount){
int overflow = 0;
if (addedAmount>availableSpace){
overflow = addedAmount-availableSpace;
//your bowl is going to be full, what happens to occupiedSpace and availableSpace?
//availableSpace = ???
//occupiedSpace = ???
}
else{
//overflow is already 0 so you don't have to do anything with it
//update availableSpace and occupiedSpace
//availableSpace = ???
//occupiedSpace = ???
}
return overflow;
}
}
```
With your above main example:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
**UPDATE**
The reason you would use this.totalCapacity is because of the following lines of code:
```
public class SugarBowl {
private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
//..
public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
//..
```
Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:
```
public class SugarBowl {
private int bowlTotalCapacity; //totalCapacity for this object
//..
public SugarBowl (int totalCapacity){
bowlTotalCapacity = totalCapacity;
//..
```
You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>.
Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:
```
public class ThisExample {
private int wrongExample = 0;
private int thisExample = 0;
public ThisExample (int wrongExample, int thisExample){
wrongExample = wrongExample;
this.thisExample = thisExample;
}
public int getThisExample(){
return thisExample;
}
public int getWrongExample(){
return wrongExample;
}
}
```
Running the following may help you understand better:
```
public class ThisExampleMain {
public static void main(String[] args) {
ThisExample ts = new ThisExample(50, 50);
//you want this to be 50 but it ends up being 0:
System.out.println("Wrong: " + ts.getWrongExample());
//this returns the correct answer:
System.out.println("Right: " + ts.getThisExample());
}
}
``` | Your main method calls the methods but does not use the values returned from those methods.
You should change your `main` method as follows.
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
Change your addSugar() method as follows.
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
//Update occupiedSpace here.
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
System.out.println("I added "+addedAmount + "to the bowl");
// Update occupiedSpace here.
}
}
```
You are not updating your occupiedSpace field when you add sugar.That's why it always stays same. |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).
You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).
I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace;//starts at 0, because there's nothing in the bowl.
/**
* Constructor for the sugar bowl.
* @param totalCapacity The total capacity of the bowl.
*/
public SugarBowl (int totalCapacity){
this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
occupiedSpace = 0;
}
/**
* Shows how much sugar can fit in a spoon.
* @return The size of the spoon
*/
public int spoon(){
return spoonSize;
}
/**
* Returns amount of sugar in the bowl.
* @return The amount of occupied space
*/
public int occupied(){
return occupiedSpace;
}
/**
* Removes the amount of sugar based on the
* number of scoops passed into it.
* @param numberOfScoops The number of scoops
* @return The amount of sugar removed
*/
public int scoops (int numberOfScoops){
int possibleAmountTaken = numberOfScoops * spoonSize;
int actualAmountTaken = 0;
//Think about sugar, even if there is less sugar than the spoon size,
//can a spoon still remove that amount?
//aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
if (possibleAmountTaken<=occupiedSpace){
actualAmountTaken = possibleAmountTaken;
}
else{
//there may still be sugar, just not enough for every scoop, you still have to remove it
//actualAmountTaken = ???
}
occupiedSpace = occupiedSpace - actualAmountTaken;
//what about availableSpace?
//availableSpace = ???
return actualAmountTaken;
}
/**
* Adds the specified amount of sugar to the bowl.
*
* @param addedAmount The amount of sugar added to the bowl
* @return The overflow amount of sugar or 0 if there was no overflow
*/
public int addSugar (int addedAmount){
int overflow = 0;
if (addedAmount>availableSpace){
overflow = addedAmount-availableSpace;
//your bowl is going to be full, what happens to occupiedSpace and availableSpace?
//availableSpace = ???
//occupiedSpace = ???
}
else{
//overflow is already 0 so you don't have to do anything with it
//update availableSpace and occupiedSpace
//availableSpace = ???
//occupiedSpace = ???
}
return overflow;
}
}
```
With your above main example:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
**UPDATE**
The reason you would use this.totalCapacity is because of the following lines of code:
```
public class SugarBowl {
private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
//..
public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
//..
```
Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:
```
public class SugarBowl {
private int bowlTotalCapacity; //totalCapacity for this object
//..
public SugarBowl (int totalCapacity){
bowlTotalCapacity = totalCapacity;
//..
```
You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>.
Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:
```
public class ThisExample {
private int wrongExample = 0;
private int thisExample = 0;
public ThisExample (int wrongExample, int thisExample){
wrongExample = wrongExample;
this.thisExample = thisExample;
}
public int getThisExample(){
return thisExample;
}
public int getWrongExample(){
return wrongExample;
}
}
```
Running the following may help you understand better:
```
public class ThisExampleMain {
public static void main(String[] args) {
ThisExample ts = new ThisExample(50, 50);
//you want this to be 50 but it ends up being 0:
System.out.println("Wrong: " + ts.getWrongExample());
//this returns the correct answer:
System.out.println("Right: " + ts.getThisExample());
}
}
``` | The addSugar method as required by the spec should return an int:
addSugar method should also update both availableSpace and occupiedSpace.
in main you are calling one.occupied() method but you are not doing anything with that value,perhaps you want to print it to see it.
the following is your addSugar method and main.
```
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
return remainingAmount;
}
else
{
availableSpace = availableSpace - addedAmount;
occupiedSpace = occupiedSpace + addedAmount;
return 0;
}
}
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("The occupied Space is: " + one.occupied());
System.out.println("The addSugar() method is returning " + one.addSugar(300));
System.out.println("The occupied Space now is: " + one.occupied());
}
```
} |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).
You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).
I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace;//starts at 0, because there's nothing in the bowl.
/**
* Constructor for the sugar bowl.
* @param totalCapacity The total capacity of the bowl.
*/
public SugarBowl (int totalCapacity){
this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
occupiedSpace = 0;
}
/**
* Shows how much sugar can fit in a spoon.
* @return The size of the spoon
*/
public int spoon(){
return spoonSize;
}
/**
* Returns amount of sugar in the bowl.
* @return The amount of occupied space
*/
public int occupied(){
return occupiedSpace;
}
/**
* Removes the amount of sugar based on the
* number of scoops passed into it.
* @param numberOfScoops The number of scoops
* @return The amount of sugar removed
*/
public int scoops (int numberOfScoops){
int possibleAmountTaken = numberOfScoops * spoonSize;
int actualAmountTaken = 0;
//Think about sugar, even if there is less sugar than the spoon size,
//can a spoon still remove that amount?
//aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
if (possibleAmountTaken<=occupiedSpace){
actualAmountTaken = possibleAmountTaken;
}
else{
//there may still be sugar, just not enough for every scoop, you still have to remove it
//actualAmountTaken = ???
}
occupiedSpace = occupiedSpace - actualAmountTaken;
//what about availableSpace?
//availableSpace = ???
return actualAmountTaken;
}
/**
* Adds the specified amount of sugar to the bowl.
*
* @param addedAmount The amount of sugar added to the bowl
* @return The overflow amount of sugar or 0 if there was no overflow
*/
public int addSugar (int addedAmount){
int overflow = 0;
if (addedAmount>availableSpace){
overflow = addedAmount-availableSpace;
//your bowl is going to be full, what happens to occupiedSpace and availableSpace?
//availableSpace = ???
//occupiedSpace = ???
}
else{
//overflow is already 0 so you don't have to do anything with it
//update availableSpace and occupiedSpace
//availableSpace = ???
//occupiedSpace = ???
}
return overflow;
}
}
```
With your above main example:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
**UPDATE**
The reason you would use this.totalCapacity is because of the following lines of code:
```
public class SugarBowl {
private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
//..
public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
//..
```
Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:
```
public class SugarBowl {
private int bowlTotalCapacity; //totalCapacity for this object
//..
public SugarBowl (int totalCapacity){
bowlTotalCapacity = totalCapacity;
//..
```
You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>.
Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:
```
public class ThisExample {
private int wrongExample = 0;
private int thisExample = 0;
public ThisExample (int wrongExample, int thisExample){
wrongExample = wrongExample;
this.thisExample = thisExample;
}
public int getThisExample(){
return thisExample;
}
public int getWrongExample(){
return wrongExample;
}
}
```
Running the following may help you understand better:
```
public class ThisExampleMain {
public static void main(String[] args) {
ThisExample ts = new ThisExample(50, 50);
//you want this to be 50 but it ends up being 0:
System.out.println("Wrong: " + ts.getWrongExample());
//this returns the correct answer:
System.out.println("Right: " + ts.getThisExample());
}
}
``` | You can add the `main()` method into your `sugarBowl` class. You don't need a separate class to run it.
I'd modify your main like this:
```
public class RunSugarBowl {
public static void main(String[] args) {
sugarBowl one = new sugarBowl(200);
one.occupied();
one.addSugar(100);
}
}
```
Or you could rename your class and its constructor to `SugarBowl`. I'd recommend the second one, because it's consistent with the Sun Java coding standards. |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | Your main method calls the methods but does not use the values returned from those methods.
You should change your `main` method as follows.
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
Change your addSugar() method as follows.
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
//Update occupiedSpace here.
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
System.out.println("I added "+addedAmount + "to the bowl");
// Update occupiedSpace here.
}
}
```
You are not updating your occupiedSpace field when you add sugar.That's why it always stays same. | You can add the `main()` method into your `sugarBowl` class. You don't need a separate class to run it.
I'd modify your main like this:
```
public class RunSugarBowl {
public static void main(String[] args) {
sugarBowl one = new sugarBowl(200);
one.occupied();
one.addSugar(100);
}
}
```
Or you could rename your class and its constructor to `SugarBowl`. I'd recommend the second one, because it's consistent with the Sun Java coding standards. |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).
You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).
I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace;//starts at 0, because there's nothing in the bowl.
/**
* Constructor for the sugar bowl.
* @param totalCapacity The total capacity of the bowl.
*/
public SugarBowl (int totalCapacity){
this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
occupiedSpace = 0;
}
/**
* Shows how much sugar can fit in a spoon.
* @return The size of the spoon
*/
public int spoon(){
return spoonSize;
}
/**
* Returns amount of sugar in the bowl.
* @return The amount of occupied space
*/
public int occupied(){
return occupiedSpace;
}
/**
* Removes the amount of sugar based on the
* number of scoops passed into it.
* @param numberOfScoops The number of scoops
* @return The amount of sugar removed
*/
public int scoops (int numberOfScoops){
int possibleAmountTaken = numberOfScoops * spoonSize;
int actualAmountTaken = 0;
//Think about sugar, even if there is less sugar than the spoon size,
//can a spoon still remove that amount?
//aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
if (possibleAmountTaken<=occupiedSpace){
actualAmountTaken = possibleAmountTaken;
}
else{
//there may still be sugar, just not enough for every scoop, you still have to remove it
//actualAmountTaken = ???
}
occupiedSpace = occupiedSpace - actualAmountTaken;
//what about availableSpace?
//availableSpace = ???
return actualAmountTaken;
}
/**
* Adds the specified amount of sugar to the bowl.
*
* @param addedAmount The amount of sugar added to the bowl
* @return The overflow amount of sugar or 0 if there was no overflow
*/
public int addSugar (int addedAmount){
int overflow = 0;
if (addedAmount>availableSpace){
overflow = addedAmount-availableSpace;
//your bowl is going to be full, what happens to occupiedSpace and availableSpace?
//availableSpace = ???
//occupiedSpace = ???
}
else{
//overflow is already 0 so you don't have to do anything with it
//update availableSpace and occupiedSpace
//availableSpace = ???
//occupiedSpace = ???
}
return overflow;
}
}
```
With your above main example:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
**UPDATE**
The reason you would use this.totalCapacity is because of the following lines of code:
```
public class SugarBowl {
private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
//..
public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
//..
```
Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:
```
public class SugarBowl {
private int bowlTotalCapacity; //totalCapacity for this object
//..
public SugarBowl (int totalCapacity){
bowlTotalCapacity = totalCapacity;
//..
```
You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>.
Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:
```
public class ThisExample {
private int wrongExample = 0;
private int thisExample = 0;
public ThisExample (int wrongExample, int thisExample){
wrongExample = wrongExample;
this.thisExample = thisExample;
}
public int getThisExample(){
return thisExample;
}
public int getWrongExample(){
return wrongExample;
}
}
```
Running the following may help you understand better:
```
public class ThisExampleMain {
public static void main(String[] args) {
ThisExample ts = new ThisExample(50, 50);
//you want this to be 50 but it ends up being 0:
System.out.println("Wrong: " + ts.getWrongExample());
//this returns the correct answer:
System.out.println("Right: " + ts.getThisExample());
}
}
``` | You should replace
```
sugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
```
by
```
public SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
``` |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | Your code is wrong unfortunately. You Should change this function
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
System.out.println("0");}
}
```
with
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
occupiedSpace = totalCapacity-availableSpace; // you must also write this to change the ocuuppied space too
System.out.println(availableSpace);
}
}
```
Because you construct your sugar bowl with 200 capacity and addin 100 to it later. So
```
if (addedAmount>availableSpace)
```
100 > 200 returns false and it goes directly to the else block which just prints out '0'. This is the logic error you made. But don't worry we all have been there ;)
Actually the line
`occupiedSpace = totalCapacity-availableSpace;`
is essential like
`availableSpace = availableSpace - addedAmount;`
since you used **occupiedSpace** as a property. The formula you wrote at the beginning of the class only executes once, when you call the constructor(and initially both of the values you suctract are 0 since they are primitive int) and **occupiedSpace** stays as **0** unless you change it with some other function call.
But instead if you want **occupiedSpace** or **availableSpace** to be calculated each time you need it you should delete one of them, hence you need only the other one and the **totalCapacity**. Other one can be calculated each time by subtracting the one from **totalCapacity**. If I were you I would use
```
public int getOccupiedSpace(){
return totalCapacity-availableSpace;
}
```
instead of using (which are by the way useles for your case)
```
private int occupiedSpace = totalCapacity-availableSpace;
```
which is just the same
```
private int occupiedSpace = 0;
```
or
```
private int occupiedSpace ;
``` | You can add the `main()` method into your `sugarBowl` class. You don't need a separate class to run it.
I'd modify your main like this:
```
public class RunSugarBowl {
public static void main(String[] args) {
sugarBowl one = new sugarBowl(200);
one.occupied();
one.addSugar(100);
}
}
```
Or you could rename your class and its constructor to `SugarBowl`. I'd recommend the second one, because it's consistent with the Sun Java coding standards. |
14,059,274 | I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
``` | 2012/12/27 | [
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] | Your code is wrong unfortunately. You Should change this function
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
System.out.println("0");}
}
```
with
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
occupiedSpace = totalCapacity-availableSpace; // you must also write this to change the ocuuppied space too
System.out.println(availableSpace);
}
}
```
Because you construct your sugar bowl with 200 capacity and addin 100 to it later. So
```
if (addedAmount>availableSpace)
```
100 > 200 returns false and it goes directly to the else block which just prints out '0'. This is the logic error you made. But don't worry we all have been there ;)
Actually the line
`occupiedSpace = totalCapacity-availableSpace;`
is essential like
`availableSpace = availableSpace - addedAmount;`
since you used **occupiedSpace** as a property. The formula you wrote at the beginning of the class only executes once, when you call the constructor(and initially both of the values you suctract are 0 since they are primitive int) and **occupiedSpace** stays as **0** unless you change it with some other function call.
But instead if you want **occupiedSpace** or **availableSpace** to be calculated each time you need it you should delete one of them, hence you need only the other one and the **totalCapacity**. Other one can be calculated each time by subtracting the one from **totalCapacity**. If I were you I would use
```
public int getOccupiedSpace(){
return totalCapacity-availableSpace;
}
```
instead of using (which are by the way useles for your case)
```
private int occupiedSpace = totalCapacity-availableSpace;
```
which is just the same
```
private int occupiedSpace = 0;
```
or
```
private int occupiedSpace ;
``` | Your main method calls the methods but does not use the values returned from those methods.
You should change your `main` method as follows.
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
Change your addSugar() method as follows.
```
public void addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
//Update occupiedSpace here.
System.out.println("Sugar bowl completely full. You got left: "+ remainingAmount);}
else{
availableSpace = availableSpace - addedAmount; //this ensures available space changes after you add sugar
System.out.println("I added "+addedAmount + "to the bowl");
// Update occupiedSpace here.
}
}
```
You are not updating your occupiedSpace field when you add sugar.That's why it always stays same. |
1,690,743 | I'm investigating a possible memory leak which is causing an "Error creating window handle" Win32Exception in my .NET 2.0 WinForms app. This is related to number of Handles and number of USER objects (most likely) so I'm trying to log these metrics the next time the exception is thrown.
HandleCount is easy to find: `Process.HandleCount`.
Does anyone know how to find the Number of USER objects? (Value can be seen in a column of the Task Manager->Processes) .NET or win API functions will do.
Thanks! | 2009/11/06 | [
"https://Stackoverflow.com/questions/1690743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177227/"
] | Try [GetGuiResources](http://msdn.microsoft.com/en-us/library/ms683192(VS.85).aspx) which you can call using [P/Invoke](http://www.pinvoke.net/default.aspx/user32/GetGuiResources.html?DelayRedirect=1) | You can also see this in Windows Task Manager.
1. Select "Process" tab.
2. Select View > "Select Columns..." and check "User Objects" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.