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
|
---|---|---|---|---|---|
55,508,892 | I have a button to backup my local database(SQLITE) to another path so that I can email the file to me. How can I copy the SQLite data to my for example downloads folder?
Here is the code of my backup button:
```
private void BtnBackup_Clicked(object sender, EventArgs e)
{
string fileName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "backend.db3");
string backupfile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "backup.db3");
File.Copy(fileName, backupfile, true);
}
```
I can check if the data has been copied the problem is when I go to the directory no files is being shown | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I guess your database is MS SQL Server.
SQL Server stores time in `HH:MI:SS` format.
Use `TimeSpan` in your model to store/get the data.
Here is another possible solution: [How to save time only without the date using ASP.NET MVC 5 Data Annotation "DataType.Time?](https://stackoverflow.com/questions/24693572/how-to-save-time-only-without-the-date-using-asp-net-mvc-5-data-annotation-data) | ```
DateTime newintime = DateTime.Parse(Request["intime"].ToLongTimeString()); //change here
DateTime newouttime = DateTime.Parse(Request["out_time"].ToLongTimeString());// here also
model = db.bookm.Where(x=>x.intime>= newintime && x.out_time <= newouttime ).First();
```
user ToLongTimeString(); |
17,528,159 | How to remove curly brackets in R?
Eg. "{abcd}" to "abcd"
How can I use gsub function in R to do this? If any other method is available, please suggest. | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2560936/"
] | Try this
```
gsub("\\{|\\}", "", "{abcd}")
[1] "abcd"
```
Or this
```
gsub("[{}]", "", "{abcd}")
``` | ```
x <- "{abcd}"
gsub("^\\{+(.+)\\}+$", '\\1', x)
```
This will remove all braces on either end of the string. The difference between this and @Dickoa's answer is that this would leave any braces inside the string alone. |
17,528,159 | How to remove curly brackets in R?
Eg. "{abcd}" to "abcd"
How can I use gsub function in R to do this? If any other method is available, please suggest. | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2560936/"
] | Try this
```
gsub("\\{|\\}", "", "{abcd}")
[1] "abcd"
```
Or this
```
gsub("[{}]", "", "{abcd}")
``` | I tend to do it in 2 steps with the argument `fixed = TRUE`, which will speed up things quite a bit.
```
x <- "{abcd}"
res1 = gsub("{", "", x, fixed = TRUE)
res1 = gsub("}", "", res1, fixed = TRUE)
```
and some benchmarks will tell you thats it about twice as fast:
```
mc = microbenchmark::microbenchmark(times = 300,
a={
gsub("\\{|\\}", "", x)
},
b = {
gsub("[{}]", "", x)
},
c = {
gsub("^\\{+(.+)\\}+$", '\\1', x)
},
d = {
res2 = gsub("{", "", x, fixed = TRUE)
gsub("}", "", res2, fixed = TRUE)
}
)
mc
```
>
>
> ```
> Unit: microseconds
> expr min lq mean median uq max neval
> a 5.120 5.121 5.864220 5.6900 5.690 18.774 300
> b 5.120 5.121 5.947683 5.6900 5.690 21.050 300
> c 6.827 7.112 8.027910 7.3965 7.965 35.841 300
> d 1.707 2.277 2.877600 2.8450 2.846 14.223 300
>
> ```
>
> |
17,528,159 | How to remove curly brackets in R?
Eg. "{abcd}" to "abcd"
How can I use gsub function in R to do this? If any other method is available, please suggest. | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2560936/"
] | ```
x <- "{abcd}"
gsub("^\\{+(.+)\\}+$", '\\1', x)
```
This will remove all braces on either end of the string. The difference between this and @Dickoa's answer is that this would leave any braces inside the string alone. | I tend to do it in 2 steps with the argument `fixed = TRUE`, which will speed up things quite a bit.
```
x <- "{abcd}"
res1 = gsub("{", "", x, fixed = TRUE)
res1 = gsub("}", "", res1, fixed = TRUE)
```
and some benchmarks will tell you thats it about twice as fast:
```
mc = microbenchmark::microbenchmark(times = 300,
a={
gsub("\\{|\\}", "", x)
},
b = {
gsub("[{}]", "", x)
},
c = {
gsub("^\\{+(.+)\\}+$", '\\1', x)
},
d = {
res2 = gsub("{", "", x, fixed = TRUE)
gsub("}", "", res2, fixed = TRUE)
}
)
mc
```
>
>
> ```
> Unit: microseconds
> expr min lq mean median uq max neval
> a 5.120 5.121 5.864220 5.6900 5.690 18.774 300
> b 5.120 5.121 5.947683 5.6900 5.690 21.050 300
> c 6.827 7.112 8.027910 7.3965 7.965 35.841 300
> d 1.707 2.277 2.877600 2.8450 2.846 14.223 300
>
> ```
>
> |
51,859,100 | After trying to install 'models' module I get this error:
```
C:\Users\Filip>pip install models
Collecting models
Using cached https://files.pythonhosted.org/packages/92/3c/ac1ddde60c02b5a46993bd3c6f4c66a9dbc100059da8333178ce17a22db5/models-0.9.3.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Filip\AppData\Local\Temp\pip-install-_exhlsc1\models\setup.py", line 25, in <module>
import models
File "C:\Users\Filip\AppData\Local\Temp\pip-install-_exhlsc1\models\models\__init__.py", line 23, in <module>
from base import *
ModuleNotFoundError: No module named 'base'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Filip\AppData\Local\Temp\pip-install-_exhlsc1\models\
```
If I try to install module 'base' this error shows up:
```
C:\Users\Filip>pip install base
Collecting base
Using cached https://files.pythonhosted.org/packages/1b/e5/464fcdb2cdbafc65f0b2da261dda861fa51d80e1a4985a2bb00ced080549/base-1.0.4.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Filip\AppData\Local\Temp\pip-install-ueghc4dh\base\setup.py", line 40, in <module>
LONG_DESCRIPTION = read("README.rst")
File "C:\Users\Filip\AppData\Local\Temp\pip-install-ueghc4dh\base\setup.py", line 21, in read
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
File "c:\users\filip\appdata\local\programs\python\python37-32\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 5: character maps to <undefined>
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Filip\AppData\Local\Temp\pip-install-ueghc4dh\base\
```
If I attempt to install other packages, everything works, setuptools and pip are updated.
It's crucial I have this module for my project and I can't do shit without it. | 2018/08/15 | [
"https://Stackoverflow.com/questions/51859100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9990279/"
] | It looks like `models` [was renamed](https://pypi.org/project/models/) to [pymodels](https://pypi.org/project/pymodels/) then renamed again to [doqu](https://pypi.org/project/doqu/) [(source code)](https://bitbucket.org/neithere/doqu/) which I was able to install the latest version from pypi. Is this legacy code? Will Doqu work for your purposes?
`pip install doqu` | There was a problem like that on the codecademy.com FLASKFM project. If you try to run code on your local IDE will give an error. Because of module.py file not updating yet. After updating modul.py file your main server app for Flask project should work. |
69,669,752 | I'm using an angular material tree to display a deeply nested object. While building the tree, how do I store the current path along with the values?
```
const TREE_DATA = JSON.parse(JSON.stringify({
"cars": [
{
"model": "",
"make": "Audi",
"year": ""
},
{
"model": "A8",
"make": "",
"year": "2007"
}
],
"toys": {
"color": "Black",
"type": [
{
"brand": "",
"price": "$100"
}
]
},
"id": "xyz",
"books": [
{
"publisher": [
{
"authors": []
}
]
}
],
"extra": "test"
}));
@Injectable()
export class FileDatabase {
dataChange = new BehaviorSubject<FileNode[]>([]);
get data(): FileNode[] { return this.dataChange.value; }
constructor() {
this.initialize();
}
initialize() {
const dataObject = JSON.parse(TREE_DATA);
const data = this.buildFileTree(dataObject, 0);
this.dataChange.next(data);
}
buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] {
return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
const value = obj[key];
const node = new FileNode();
node.filename = key;
if (value != null) {
if (typeof value === 'object') {
node.children = this.buildFileTree(value, level + 1);
} else {
node.type = value;
}
}
return accumulator.concat(node);
}, []);
}
}
```
Currently, the buildFileTree function returns:
```
[
{
"filename": "cars",
"children": [
{
"filename": "0",
"children": [
{
"filename": "model",
"type": ""
},
{
"filename": "make",
"type": "Audi"
},
{
"filename": "year",
"type": ""
}
]
},
{
"filename": "1",
"children": [
{
"filename": "model",
"type": "A8"
},
{
"filename": "make",
"type": ""
},
{
"filename": "year",
"type": "2007"
}
]
}
]
},
{
"filename": "toys",
"children": [
{
"filename": "color",
"type": "Black"
},
{
"filename": "type",
"children": [
{
"filename": "0",
"children": [
{
"filename": "brand",
"type": ""
},
{
"filename": "price",
"type": "$100"
}
]
}
]
}
]
},
{
"filename": "id",
"type": "a"
},
{
"filename": "books",
"children": [
{
"filename": "0",
"children": [
{
"filename": "publisher",
"children": [
{
"filename": "0",
"children": [
{
"filename": "authors",
"type": []
}
]
}
]
}
]
}
]
},
{
"filename": "extra",
"type": "test"
}
]
```
While building this tree, how can I add the path to every "type" at every level? Something like "path": "cars.0.model" for the first "type" and so on. | 2021/10/21 | [
"https://Stackoverflow.com/questions/69669752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8882952/"
] | See this issue on TypeScript's GitHub project: [Module path maps are not resolved in emitted code (#10866)](https://github.com/microsoft/TypeScript/issues/10866)
tl;dr
=====
* TypeScript won't rewrite your module paths
* `paths` was designed to help TypeScript understand path aliases used by bundlers
* You'll either need to:
+ use a bundler, such as [webpack](https://webpack.js.org/), and configure its own path maps
+ use a build time tool, such as [tspath](https://www.npmjs.com/package/tspath), to rewrite the paths
+ modify the runtime module resolver, with something like [module-alias](https://www.npmjs.com/package/module-alias) | I've been stuck with this issue for 2 whole days trying to find something that works. @Wing's answer is correct, if you're using plain `tsc` with no other tools, then Node won't know what you mean by `@/` (or whatever your alias is) in your imports.
I've tried a few different approaches and I've found one that required no configuration.
What **worked**:
At the end of my journey I came across a package that is still actively being maintained: [tsc-alias](https://www.npmjs.com/package/tsc-alias). The only thing I needed to do was add `&& tsc-alias -p tsconfig.json` to my `tsc` command in my build script and voilà, it works. So your full command would be something like `tsc -p tsconfig.json && tsc-alias -p tsconfig.json`.
What I tried that **didn't** work:
* I tried "module-alias" and I couldn't get it to work.
* I tried "tsconfig-paths" as suggested by @AlexMorley-Finch with no luck as well. The package seems to be finding the modules but there seems to be a bug that causes the path of the modules not to be mapped correctly (there's an issue open for it).
* I then came across `tscpaths`. This package requires you to explicitly specify your project, src dir and out dir. I got it to work after figuring out my outdir needed to be `./build/src` instead of `./build`. The caveat here: this package hasn't been touched since May 2019 as of writing this. |
449,283 | I have a collection of reviewers who are rating applications. Each application is reviewed by at least two people and they give a score between 0 and 50 among various criteria.
Looking at the mean for each reviewer, it's seems a few rated more harshly than others, and that they give disproportionately lower scores to applicants who by luck happen to get evaluated by more critical reviewers.
The mean of all applications reviews is 34.5. There are 22 reviewers, and their means range from 29.7 to 38.7. The standard deviation of population for all applications is 5.6.
I'm wondering how to go about adjusting the mean for reviewers to create a more equitable rating among all applicants, or if these numbers are within the normal expected variation. Thanks in advance.
[](https://i.stack.imgur.com/029nX.png) | 2020/02/13 | [
"https://stats.stackexchange.com/questions/449283",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/273625/"
] | Hopefully this isn't overkill, but I think this is a case where creating a linear model, and looking at the estimated marginal means, would make sense. Estimated marginal means are adjusted for the other terms in the model. That is, the E.M. mean score for student A can be adjusted for the effect of Evaluator 1. That is, how much higher or lower Evaluator 1 tends to rate students relative to the other evaluators.
Minimally, you can conduct a classic anova to see if there is a significant effect of Evaluator.
I have an example of this below in R.
***Edit:*** I suppose for this approach to make sense --- that is, be fair --- each evaluator should have evaluated relatively many students, and a random or representative cross-section of students. There is always a chance that an evaluator just happens to evaluate e.g. a group of poor students. In this case we would inaccurately suspect the evaluator of being a tough evaluator, when in fact it was just that their students were poor. But having multiple evaluators per student also makes this less likely.
---
Create some toy data
```
Data = read.table(header=T, text="
Student Evaluator Score
a 1 95
a 2 80
b 2 60
b 3 50
c 3 82
c 1 92
d 1 93
d 2 84
e 2 62
e 3 55
f 1 94
f 3 75
")
Data$Evaluator = factor(Data$Evaluator)
```
Create linear model
```
model = lm(Score ~ Student + Evaluator, data=Data)
```
Classic anova to see if there is an effect of Evaluator
```
require(car)
Anova(model)
### Anova Table (Type II tests)
###
### Sum Sq Df F value Pr(>F)
### Student 1125.5 5 20.699 0.005834 **
### Evaluator 414.5 2 19.058 0.009021 **
### Residuals 43.5 4
```
So, it looks like there is a significant effect of Evaluator.
Look at simple arithmetic means
```
require(FSA)
Summarize(Score ~ Student, data=Data)
### Student n mean sd min Q1 median Q3 max
### 1 a 2 87.5 10.606602 80 83.75 87.5 91.25 95
### 2 b 2 55.0 7.071068 50 52.50 55.0 57.50 60
### 3 c 2 87.0 7.071068 82 84.50 87.0 89.50 92
### 4 d 2 88.5 6.363961 84 86.25 88.5 90.75 93
### 5 e 2 58.5 4.949747 55 56.75 58.5 60.25 62
### 6 f 2 84.5 13.435029 75 79.75 84.5 89.25 94
```
Look at the adjusted means for Student
```
require(emmeans)
emmeans(model, ~ Student)
### Student emmean SE df lower.CL upper.CL
### a 83.7 2.46 4 76.8 90.5
### b 59.4 2.46 4 52.6 66.2
### c 86.4 2.46 4 79.6 93.2
### d 84.7 2.46 4 77.8 91.5
### e 62.9 2.46 4 56.1 69.7
### f 83.9 2.46 4 77.1 90.7
###
### Results are averaged over the levels of: Evaluator
### Confidence level used: 0.95
```
Note that some students' scores went up and others went down relative to arithmetic means. | *@Sal Mangiafico* is on the right track, so I'd just add my few cents to his answer. The phenomenon you are describing is called *examiner effect*, and you can google for this term to find more hints on solving this problem.
Are you familiar with [Item Response Theory](https://en.wikipedia.org/wiki/Item_response_theory)? This is a theory, or rather a family of models used in psychometry for [solving](https://stats.stackexchange.com/questions/140561/what-is-a-good-method-to-identify-outliers-in-exam-data/140609#140609) similar [problems](https://stats.stackexchange.com/questions/277733/interdependence-of-hyperparameters-of-bernouilli-laws/277739#277739). The simplest of those models is the [Rash model](https://stats.stackexchange.com/questions/141886/count-data-as-a-dependent-variable-consist-of-five-levels-likert-scale/141912#141912), where the $i$-th student's response (binary), to the $j$-th question is modelled using a latent variables model
$$ P(X\_{ij} = 1) = \frac{\exp(\theta\_i - \beta\_j)}{1+\exp(\theta\_i - \beta\_j)} $$
where $\theta\_i$ is the student's ability and $\beta\_j$ is the item's difficulty. Of course, we can easily adapt the model to non-binary answers by not using the logistic function in here, or using something else, when we generalize the model structure as $E[X\_{ij}] = g(\theta\_i - \beta\_j)$. As you can see, and as said by *@Sal Mangiafico*, this is just basically an ANOVA in disguise. Such models can be used for finding the "true" ability level of a student $\theta\_i$, correcting for the difficulty of the questions. What *@Sal Mangiafico* described is exactly the same kind of model, but in his answer he assumed a fixed-effects model, while [we would often assume](https://stats.stackexchange.com/questions/58050/measuring-some-of-the-patients-more-than-once/135957#135957) a random- (or mixed-) effects models for such problems. You can find examples of re-defining IRT models, as mixed-effects models in the paper by [De Boeck et al (2011)](https://www.jstatsoft.org/article/view/v039i12).
De Boeck, P., Bakker, M., Zwitser, R., Nivard, M., Hofman, A., Tuerlinckx, F., & Partchev, I. (2011). [The estimation of item response models with the lmer function from the lme4 package in R.][6] \*Journal of Statistical Software, 39\*(12), 1-28. |
35,827,150 | I struggle since a few days to get a correct provisioning profile.
I am an independent iOS dev with my own iTunes connect account but I recently started to develop for a development team. Since then, I can't get a correct provisionning profile to run my app from xCode to my iPhone.
iOS documentation describes how to create certificates and provisionning profiles but it doesn't identify who needs to do each step (either me the developer, either the development team manager).
Could you please describe who needs to do the following step :
1. Create a development certificate. To me, it should be me as it is me who develops. Then, I send it to the dev team manager who adds it in his member center.
2. App ID : The dev team manager create the app ID with a specific bundle ID
3. Devices : The dev team manager adds my iPhone UDID.
4. Provisioning profile : The dev team manager creates it from my certificates, the app ID and my device. Then, he sends me the file and I just have to double-click on it.
However, this doesn't seem to work. Any idea how I can obtain a valid provisioning profile.
PS 1 : I have been added in Itunes Connect and I can access to the app details.
PS 2 : Bundle ID of the app in xCode and iTunes connect are the same (I've checked a hundred times). | 2016/03/06 | [
"https://Stackoverflow.com/questions/35827150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2521010/"
] | Each team member is responsible for creating their own key/cert pair and adding it to their machine via Keychain Access. That is for Development builds. Distribution certs can only be created by an admin.
To create an app Id or provision on the member center you need to have admin access. If you don't have admin access then you have to rely on someone who does to create those. They would be responsible for making sure your device and cert are attached to then development provision for your app.
Your problem could also be that your code signing settings are not setup correctly in the project. You should set provision to Automatic and identity to iOSDeveloper. This lets Xcode figure it out and also allows you to share the project in a team setting without code signing issues | Ok, here are the steps:
1. Generate a new CSR from Keychain.
2. Go to iTunes Connect.
3. In Certificate section:
* Download Apple's World Wide Relations Authority Certificate using CSR.
* Download iOS Developer Certificate using CSR.
4. Add both these certificates to Keychain.
5. In Provisional Profile Section:
* Download a new provisional profile which includes this developer certificate.
6. Add this profile to Xcode.
7. In Xcode, go to Build Settings --> Code Signing --> Set provisional profile.
8. Run project.
This should do it for you.
Good luck. |
6,685,140 | I have many web applications in a Visual Studio solution.
All have the same post build command:
```
xcopy "$(TargetDir)*.dll" "D:\Project\bin" /i /d /y
```
It would be useful to avoid replacing newer files with old ones (e.g. someone could accidentally add a reference to an old version of a DLL).
How can I use xcopy to replace old files only with **newer DLL files** generated by Visual Studio? | 2011/07/13 | [
"https://Stackoverflow.com/questions/6685140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66708/"
] | From typing "help xcopy" at the command line:
```
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
```
So you already are using xcopy to only replace old files with new ones. If that's not happening, you may have to swap the positions of the `/i` and `/d` switches. | Not tested, but I use a similar command script for these sorts of tasks.
```
set DIR_DEST=D:\Project\bin
pushd "$(TargetDir)"
::
:: Move Files matching pattern and delete them
::
for %%g in (*.dll) do (xcopy "%%g" "%DIR_DEST%" /D /Y & del "%%g")
::
:: Move Files matching pattern
::
:: for %%g in (*.dll) do (xcopy "%%g" "%DIR_DEST%" /D /Y )
popd
``` |
6,685,140 | I have many web applications in a Visual Studio solution.
All have the same post build command:
```
xcopy "$(TargetDir)*.dll" "D:\Project\bin" /i /d /y
```
It would be useful to avoid replacing newer files with old ones (e.g. someone could accidentally add a reference to an old version of a DLL).
How can I use xcopy to replace old files only with **newer DLL files** generated by Visual Studio? | 2011/07/13 | [
"https://Stackoverflow.com/questions/6685140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66708/"
] | From typing "help xcopy" at the command line:
```
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
```
So you already are using xcopy to only replace old files with new ones. If that's not happening, you may have to swap the positions of the `/i` and `/d` switches. | User following command to copy all new and modified file from source to destination
xcopy c:\source d:\destination /D /I /E /Y
/D to check any modified file are there
/I If the destination does not exist and copying more than one file, assumes that destination must be a directory.
/E To copy directory and sub directories
/Y to suppress any over write prompt. |
6,685,140 | I have many web applications in a Visual Studio solution.
All have the same post build command:
```
xcopy "$(TargetDir)*.dll" "D:\Project\bin" /i /d /y
```
It would be useful to avoid replacing newer files with old ones (e.g. someone could accidentally add a reference to an old version of a DLL).
How can I use xcopy to replace old files only with **newer DLL files** generated by Visual Studio? | 2011/07/13 | [
"https://Stackoverflow.com/questions/6685140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66708/"
] | User following command to copy all new and modified file from source to destination
xcopy c:\source d:\destination /D /I /E /Y
/D to check any modified file are there
/I If the destination does not exist and copying more than one file, assumes that destination must be a directory.
/E To copy directory and sub directories
/Y to suppress any over write prompt. | Not tested, but I use a similar command script for these sorts of tasks.
```
set DIR_DEST=D:\Project\bin
pushd "$(TargetDir)"
::
:: Move Files matching pattern and delete them
::
for %%g in (*.dll) do (xcopy "%%g" "%DIR_DEST%" /D /Y & del "%%g")
::
:: Move Files matching pattern
::
:: for %%g in (*.dll) do (xcopy "%%g" "%DIR_DEST%" /D /Y )
popd
``` |
10,214,949 | I have a function defined that way:
```
var myObject = new Object();
function myFunction(someString){
myObject.someString= 0;
}
```
The problem is `someString` is taken as the string `someString` instead of the value of that variable.
So, after I use that function several times over with different `someString`'s, I would like to get an object with all the values for each someString.
But when I loop through that object
The only result I get is `someString : 0`
I want to get:
```
John : 0
James : 0
Alex : 0 etc....
```
How do I do that? Thanks a lot in advance | 2012/04/18 | [
"https://Stackoverflow.com/questions/10214949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1290170/"
] | You can use the associative array approach:
```
var someString = 'asdf';
myObject[someString] = 0; // {asdf: 0}
myObject['foo'] = 'bar';
```
You can basically use any string to retrieve your method/parameter.
```
var i = 1;
myObject['test' + i] = i + 1; // gives us {test1: 2}
``` | Try this
```
var myObject = new Object();
function myFunction(someString){
myObject[someString]= 0;
}
``` |
69,619,770 | I have a df that looks like this:
[](https://i.stack.imgur.com/PBVX9.png)
I want to remove the part that is equal to `ID` from `Name`, and then build three new variable which equal to the last two digit of `Name`, the 3 place in `Name', and 4th place in` Name". sth that will look like the following:
[](https://i.stack.imgur.com/DPIQY.png)
What should I do in order to achieve this goal?
```
df<-structure(list(Name = c("LABCPCM01", "TUNISCN02", "HONORCN01",
"KUCCLCN02", "LABCPBF03", "LABCPBF04", "MFHLBCM01", "MFHLBCF01",
"DRLLBCN01", "QDSWRCN03", "QDSWRCN04", "UTSWLHN01", "MGHCCBN02",
"JHDPCHM01", "UNILBCF03", "UTSWLGN03", "PHCI0CN01", "PHCI0CN02"
), ID = c("LABCP", "TUNIS", "HONOR", "KUCCL", "LABCP", "LABCP",
"MFHLB", "MFHLB", "DRLLB", "QDSWR", "QDSWR", "UTSWL", "MGHCC",
"JHDPC", "UNILB", "UTSWL", "PHCI0", "PHCI0")), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))
``` | 2021/10/18 | [
"https://Stackoverflow.com/questions/69619770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13631281/"
] | Use [`split`](https://docs.python.org/3/library/stdtypes.html#str.split), then reverse the string and finally [`capitalize`](https://docs.python.org/3/library/stdtypes.html#str.capitalize):
```
s = 'this is the best'
res = " ".join([si[::-1].capitalize() for si in s.split()])
print(res)
```
**Output**
```
Siht Si Eht Tseb
``` | Just do:
```
" ".join([str(i[::-1]).title() for i in input.split()])
``` |
69,619,770 | I have a df that looks like this:
[](https://i.stack.imgur.com/PBVX9.png)
I want to remove the part that is equal to `ID` from `Name`, and then build three new variable which equal to the last two digit of `Name`, the 3 place in `Name', and 4th place in` Name". sth that will look like the following:
[](https://i.stack.imgur.com/DPIQY.png)
What should I do in order to achieve this goal?
```
df<-structure(list(Name = c("LABCPCM01", "TUNISCN02", "HONORCN01",
"KUCCLCN02", "LABCPBF03", "LABCPBF04", "MFHLBCM01", "MFHLBCF01",
"DRLLBCN01", "QDSWRCN03", "QDSWRCN04", "UTSWLHN01", "MGHCCBN02",
"JHDPCHM01", "UNILBCF03", "UTSWLGN03", "PHCI0CN01", "PHCI0CN02"
), ID = c("LABCP", "TUNIS", "HONOR", "KUCCL", "LABCP", "LABCP",
"MFHLB", "MFHLB", "DRLLB", "QDSWR", "QDSWR", "UTSWL", "MGHCC",
"JHDPC", "UNILB", "UTSWL", "PHCI0", "PHCI0")), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))
``` | 2021/10/18 | [
"https://Stackoverflow.com/questions/69619770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13631281/"
] | Use [`split`](https://docs.python.org/3/library/stdtypes.html#str.split), then reverse the string and finally [`capitalize`](https://docs.python.org/3/library/stdtypes.html#str.capitalize):
```
s = 'this is the best'
res = " ".join([si[::-1].capitalize() for si in s.split()])
print(res)
```
**Output**
```
Siht Si Eht Tseb
``` | The other answers here works as well. But I think this will be a lot easier to understand.
```
s = 'this is the best'
words = s.split() # Split into list of each word
res = ''
for word in words:
word = word[::-1] # Reverse the word
word = word.capitalize() + ' ' # Capitalize and add empty space
res += word # Append the word to the output string
print(res)
``` |
39,937,368 | I want to know if it's authorized to avoid Thread deadlocks by making the threads not starting at the same time? Is there an other way to avoid the deadlocks in the following code?
Thanks in advance!
```
public class ThreadDeadlocks {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 t1 = new ThreadDemo1();
ThreadDemo2 t2 = new ThreadDemo2();
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
t2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
``` | 2016/10/08 | [
"https://Stackoverflow.com/questions/39937368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5398064/"
] | There are two ways to get a deadlock:
1. Lock escalation. For example, a thread holding a shareable read
lock tries to escalate to an exclusive write lock. If more than one
thread holding a read lock tries to escalate to a write lock, a
deadlock results. This doesn't apply to what you're doing. (Offhand, I don't even know if it's *possible* to escalate a lock in Java.)
2. Unspecified lock order. If thread A locks object 1, then tries to lock object 2, while thread B locks object 2 then tries to lock object 1, a deadlock can result. This is exactly what you're doing.
Those are the only ways to get a deadlock. Every deadlock scenario will come down to one of those.
If you don't want deadlocks, don't do either of those. Never escalate a lock, and always specify lock order.
Those are the only ways to prevent deadlocks. Monkeying around with thread timing by delaying things is not guaranteed to work. | No, starting threads at different times is not a way to avoid deadlocks - in fact, what you'd be trying with different start times is a heuristic to serialize their critical sections. ++ see why at the and of this answer
[Edited with a solution]
>
> Is there an other way to avoid the deadlocks in the following code?
>
>
>
The simplest way is to acquire the locks in the same order *on both threads*
```
synchronized(Lock1) {
// do some work
synchronized(Lock2) {
// do some other work and commit (make changes visible)
}
}
```
If the logic of your code dictates you can't do that, then use `java.util.concurrent.locks` classes. For example
```
ReentrantLock Lock1=new ReentrantLock();
ReentrantLock Lock2=new ReentrantLock();
private static class ThreadDemo1 extends Thread {
public void run() {
while(true) {
Lock1.lock(); // will block until available
System.out.println("Thread 1: Holding lock 1...");
try {
// Do some preliminary work here, but do not "commit" yet
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 1: Waiting for lock 2...");
if(!Lock2.tryLock(30, TimeUnit.MILLISECOND)) {
System.out.println("Thread 1: not getting a hold on lock 2...");
// altruistic behaviour: if I can't do it, let others
// do their work with Lock1, I'll try later
System.out.println("Thread 1: release lock 1 and wait a bit");
Lock1.unlock();
Thread.sleep(30);
System.out.println("Thread 1: Discarding the work done before, will retry getting lock 1");
}
else {
System.out.println("Thread 1: got a hold on lock 2...");
break;
}
}
// if we got here, we know we are holding both locks
System.out.println("Thread 1: both locks available, complete the work");
// work...
Lock2.unlock(); // release the locks in the reverse...
Lock1.unlock(); // ... order of acquisition
}
}
// do the same for the second thread
```
---
++ To demonstrate why delays in starting the threads at different times is not a foolproof solution, think if you can afford to delay one of the threads by 10 seconds in the example below. Then think what will you do *if you don't actually know how long to wait*.
```
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
// modelling a workload here:
// can take anywhere up to 10 seconds
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
// modelling a workload here:
// can take anywhere up to 10 seconds
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
``` |
39,937,368 | I want to know if it's authorized to avoid Thread deadlocks by making the threads not starting at the same time? Is there an other way to avoid the deadlocks in the following code?
Thanks in advance!
```
public class ThreadDeadlocks {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 t1 = new ThreadDemo1();
ThreadDemo2 t2 = new ThreadDemo2();
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
t2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
``` | 2016/10/08 | [
"https://Stackoverflow.com/questions/39937368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5398064/"
] | There are two ways to get a deadlock:
1. Lock escalation. For example, a thread holding a shareable read
lock tries to escalate to an exclusive write lock. If more than one
thread holding a read lock tries to escalate to a write lock, a
deadlock results. This doesn't apply to what you're doing. (Offhand, I don't even know if it's *possible* to escalate a lock in Java.)
2. Unspecified lock order. If thread A locks object 1, then tries to lock object 2, while thread B locks object 2 then tries to lock object 1, a deadlock can result. This is exactly what you're doing.
Those are the only ways to get a deadlock. Every deadlock scenario will come down to one of those.
If you don't want deadlocks, don't do either of those. Never escalate a lock, and always specify lock order.
Those are the only ways to prevent deadlocks. Monkeying around with thread timing by delaying things is not guaranteed to work. | As the other mentioned, delays won't help because threads by their nature have unknown start time. When you call start() on a thread, it becomes runnable, but you cannot know when it will be running. |
39,937,368 | I want to know if it's authorized to avoid Thread deadlocks by making the threads not starting at the same time? Is there an other way to avoid the deadlocks in the following code?
Thanks in advance!
```
public class ThreadDeadlocks {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 t1 = new ThreadDemo1();
ThreadDemo2 t2 = new ThreadDemo2();
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
t2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
``` | 2016/10/08 | [
"https://Stackoverflow.com/questions/39937368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5398064/"
] | There are two ways to get a deadlock:
1. Lock escalation. For example, a thread holding a shareable read
lock tries to escalate to an exclusive write lock. If more than one
thread holding a read lock tries to escalate to a write lock, a
deadlock results. This doesn't apply to what you're doing. (Offhand, I don't even know if it's *possible* to escalate a lock in Java.)
2. Unspecified lock order. If thread A locks object 1, then tries to lock object 2, while thread B locks object 2 then tries to lock object 1, a deadlock can result. This is exactly what you're doing.
Those are the only ways to get a deadlock. Every deadlock scenario will come down to one of those.
If you don't want deadlocks, don't do either of those. Never escalate a lock, and always specify lock order.
Those are the only ways to prevent deadlocks. Monkeying around with thread timing by delaying things is not guaranteed to work. | I'm assuming this is just demo code, so you already know that playing with sleeps is not guaranteed to work (as stressed in other answers).
In your demo code I see two options to try avoid the deadlock:
* Remove any sleep within the body of the functions executed by the threads and just put a single, long enough, sleep between the start of the two threads; in practical terms, this should give enough time to the first thread to be scheduled and complete its work, then the second thread will acquire both locks without contention. But, you already know, scheduling policies are not under your control and this is not guaranteed to work at all.
* Do acquire locks in the same order in both threads, without using any sleep at all, i.e.
```
synchronized (Lock1) {
synchronized (Lock2) {
// ...
}
}
```
This is guaranteed to remove any possible deadlock, because the first thread to acquire `Lock1` will gain the possibility to complete its work while blocking the other thread until completion.
UPDATE:
To understand why acquiring locks in the same order is the only guaranteed way to avoid deadlock, you should recall what's the whole purpose of locks.
A thread is said to own a lock between the time it has acquired the lock and released the lock. As long as a thread owns a lock, no other thread can acquire the same lock. In fact, the other thread will block when it attempts to acquire the same lock.
Every object in Java has an intrinsic lock associated with it. The synchronized statement let you automatically acquire the intrinsic lock of the specified object and release it after code execution. |
18,837,093 | I'm converting pdf files to images with ImageMagic, everything is ok until I use `-resize` option, then I get image with black background. I use this command:
```
convert -density 400 image.pdf -resize 25% image.png
```
I need to use `-resize` option otherwise I get really large image. Is there any other option which I can use to resize image or is there option to set background in white. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18837093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581710/"
] | ```
Select
City,
Sum(Money),
Sum(Case When Age < 30 Then 1 Else 0 End),
Sum(Case When Age > 30 Then 1 Else 0 End)
From
table
Group By
City
``` | You can use this Query,
```
SELECT City,
SUM(Money),
SUM(case when Age < 30 then 1 else 0 end),
SUM(case when Age > 30 then 1 else 0 end)
FROM tableA
GROUP BY City
``` |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | You can use profiler (for ex. JProfiler) for view memory usage by classes. Or , how mentioned Areo, just print memory usage:
```
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used Memory before" + usedMemoryBefore);
// working code here
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore));
``` | Here is a sample code to run memory usage in a separate thread. Since the GC can be triggered anytime when the process is running, this will record memory usage every second and report out the maximum memory used.
The `runnable` is the actual process that needs measuring, and `runTimeSecs` is the expected time the process will run. This is to ensure the thread calculating memory does not terminate before the actual process.
```
public void recordMemoryUsage(Runnable runnable, int runTimeSecs) {
try {
CompletableFuture<Void> mainProcessFuture = CompletableFuture.runAsync(runnable);
CompletableFuture<Void> memUsageFuture = CompletableFuture.runAsync(() -> {
long mem = 0;
for (int cnt = 0; cnt < runTimeSecs; cnt++) {
long memUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
mem = memUsed > mem ? memUsed : mem;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
;
System.out.println("Max memory used (gb): " + mem/1000000000D);
});
CompletableFuture<Void> allOf = CompletableFuture.allOf(mainProcessFuture, memUsageFuture);
allOf.get();
} catch (Exception e) {
e.printStackTrace();
}
}
``` |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | Here is an example from Netty which does something similar: [MemoryAwareThreadPoolExecutor](http://grepcode.com/file/repo1.maven.org/maven2/org.jboss.netty/netty/3.0.0.CR1/org/jboss/netty/handler/execution/MemoryAwareThreadPoolExecutor.java). Guava's [cache class](https://code.google.com/p/guava-libraries/wiki/CachesExplained) has also a size based eviction. You could look at these sources and copy what they are doing. In particular, Here is how Netty is [estimating object sizes](http://grepcode.com/file/repo1.maven.org/maven2/com.ning/metrics.goodwill-access/0.0.10/org/jboss/netty/util/DefaultObjectSizeEstimator.java?av=h#DefaultObjectSizeEstimator). In essence, you'd estimate the size of the objects you generate in the method and keep a count.
Getting overall memory information (like how much heap is available/used) will help you decide how much memory usage to allocate to the method, but not to track how much memory was used by the individual method calls.
Having said that, it's very rare that you legitimately need this. In most cases, capping the memory usage by limiting how many objects can be there at a given point (e.g. by using a bounded queue) is good enough and is much, much simpler to implement. | The easiest way to estimate memory usage is to use methods from `Runtime` class.
--------------------------------------------------------------------------------
**I suggest not to rely on it, but use it only for approximate estimations. Ideally you should only log this information and analyze it on your own, without using it for automation of your test or code.**
Probably it isn't very reliable, but in closed environment like unit test it may give you estimate close to reality.
Especially there is no guarantee that after calling `System.gc()` garbage collector will run when we expect it (it is only a suggestion for GC), there are precision limitations of the `freeMemory` method described there: <https://stackoverflow.com/a/17376879/1673775> and there might be more caveats.
### Solution:
```
private static final long BYTE_TO_MB_CONVERSION_VALUE = 1024 * 1024;
@Test
public void memoryUsageTest() {
long memoryUsageBeforeLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory before loading some data: " + memoryUsageBeforeLoadingData + " MB");
List<SomeObject> somethingBigLoadedFromDatabase = loadSomethingBigFromDatabase();
long memoryUsageAfterLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory after loading some data: " + memoryUsageAfterLoadingData + " MB");
log.debug("Difference: " + (memoryUsageAfterLoadingData - memoryUsageBeforeLoadingData) + " MB");
someOperations(somethingBigLoadedFromDatabase);
}
private long getCurrentlyUsedMemory() {
System.gc();
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / BYTE_TO_MB_CONVERSION_VALUE;
}
``` |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | To measure current memory usage use :
`Runtime.getRuntime().freeMemory()` ,
`Runtime.getRuntime().totalMemory()`
Here is a good example:
[get OS-level system information](https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information)
But this measurement is not precise but it can give you much information.
Another problem is with `GC` which is unpredictable. | This question is a bit tricky, due to the way in which Java can allocate a lot of short-lived objects during processing, which will subsequently be collected during garbage collection. In the accepted answer, we cannot say with any certainty that garbage collection has been run at any given time. Even if we introduce a loop structure, with multiple `System.gc()` calls, garbage collection might run in between our method calls.
A better way is to instead use some variation of what is suggested in <https://cruftex.net/2017/03/28/The-6-Memory-Metrics-You-Should-Track-in-Your-Java-Benchmarks.html>, where `System.gc()` is triggered but we also wait for the reported GC count to increase:
```
long getGcCount() {
long sum = 0;
for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) {
long count = b.getCollectionCount();
if (count != -1) { sum += count; }
}
return sum;
}
long getReallyUsedMemory() {
long before = getGcCount();
System.gc();
while (getGcCount() == before);
return getCurrentlyAllocatedMemory();
}
long getCurrentlyAllocatedMemory() {
final Runtime runtime = Runtime.getRuntime();
return (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024);
}
```
This still gives only an approximation of the memory actually allocated by your code at a given time, but the value is typically much closer to what one would usually be interested in. |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | To measure current memory usage use :
`Runtime.getRuntime().freeMemory()` ,
`Runtime.getRuntime().totalMemory()`
Here is a good example:
[get OS-level system information](https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information)
But this measurement is not precise but it can give you much information.
Another problem is with `GC` which is unpredictable. | Here is an example from Netty which does something similar: [MemoryAwareThreadPoolExecutor](http://grepcode.com/file/repo1.maven.org/maven2/org.jboss.netty/netty/3.0.0.CR1/org/jboss/netty/handler/execution/MemoryAwareThreadPoolExecutor.java). Guava's [cache class](https://code.google.com/p/guava-libraries/wiki/CachesExplained) has also a size based eviction. You could look at these sources and copy what they are doing. In particular, Here is how Netty is [estimating object sizes](http://grepcode.com/file/repo1.maven.org/maven2/com.ning/metrics.goodwill-access/0.0.10/org/jboss/netty/util/DefaultObjectSizeEstimator.java?av=h#DefaultObjectSizeEstimator). In essence, you'd estimate the size of the objects you generate in the method and keep a count.
Getting overall memory information (like how much heap is available/used) will help you decide how much memory usage to allocate to the method, but not to track how much memory was used by the individual method calls.
Having said that, it's very rare that you legitimately need this. In most cases, capping the memory usage by limiting how many objects can be there at a given point (e.g. by using a bounded queue) is good enough and is much, much simpler to implement. |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | I can think of several options:
* Finding out how much memory your method requires via a microbenchmark (i.e. [jmh](http://openjdk.java.net/projects/code-tools/jmh/)).
* Building allocation strategies based on heuristic estimation. There are several open source solutions implementing class size estimation i.e. [ClassSize](http://svn.apache.org/repos/asf/hbase/branches/0.89-fb/src/main/java/org/apache/hadoop/hbase/util/ClassSize.java). A much easier way could be utilizing a cache which frees rarely used objects (i.e. Guava's Cache). As mentioned by @EnnoShioji, Guava's cache has memory-based eviction policies.
You can also write your own benchmark test which counts memory. The idea is to
1. Have a single thread running.
2. Create a new array to store your objects to allocate. So these objects won't be collected during GC run.
3. `System.gc()`, `memoryBefore = runtime.totalMemory() - runtime.freeMemory()`
4. Allocate your objects. Put them into the array.
5. `System.gc()`, `memoryAfter = runtime.totalMemory() - runtime.freeMemory()`
This is a technique I used in my [lightweight micro-benchmark tool](https://github.com/chaschev/experiments-with-microbes/blob/master/src/test/java/com/chaschev/microbe/samples/MemConsumptionTest.java) which is capable of measuring memory allocation with byte-precision. | The easiest way to estimate memory usage is to use methods from `Runtime` class.
--------------------------------------------------------------------------------
**I suggest not to rely on it, but use it only for approximate estimations. Ideally you should only log this information and analyze it on your own, without using it for automation of your test or code.**
Probably it isn't very reliable, but in closed environment like unit test it may give you estimate close to reality.
Especially there is no guarantee that after calling `System.gc()` garbage collector will run when we expect it (it is only a suggestion for GC), there are precision limitations of the `freeMemory` method described there: <https://stackoverflow.com/a/17376879/1673775> and there might be more caveats.
### Solution:
```
private static final long BYTE_TO_MB_CONVERSION_VALUE = 1024 * 1024;
@Test
public void memoryUsageTest() {
long memoryUsageBeforeLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory before loading some data: " + memoryUsageBeforeLoadingData + " MB");
List<SomeObject> somethingBigLoadedFromDatabase = loadSomethingBigFromDatabase();
long memoryUsageAfterLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory after loading some data: " + memoryUsageAfterLoadingData + " MB");
log.debug("Difference: " + (memoryUsageAfterLoadingData - memoryUsageBeforeLoadingData) + " MB");
someOperations(somethingBigLoadedFromDatabase);
}
private long getCurrentlyUsedMemory() {
System.gc();
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / BYTE_TO_MB_CONVERSION_VALUE;
}
``` |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | To measure current memory usage use :
`Runtime.getRuntime().freeMemory()` ,
`Runtime.getRuntime().totalMemory()`
Here is a good example:
[get OS-level system information](https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information)
But this measurement is not precise but it can give you much information.
Another problem is with `GC` which is unpredictable. | The easiest way to estimate memory usage is to use methods from `Runtime` class.
--------------------------------------------------------------------------------
**I suggest not to rely on it, but use it only for approximate estimations. Ideally you should only log this information and analyze it on your own, without using it for automation of your test or code.**
Probably it isn't very reliable, but in closed environment like unit test it may give you estimate close to reality.
Especially there is no guarantee that after calling `System.gc()` garbage collector will run when we expect it (it is only a suggestion for GC), there are precision limitations of the `freeMemory` method described there: <https://stackoverflow.com/a/17376879/1673775> and there might be more caveats.
### Solution:
```
private static final long BYTE_TO_MB_CONVERSION_VALUE = 1024 * 1024;
@Test
public void memoryUsageTest() {
long memoryUsageBeforeLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory before loading some data: " + memoryUsageBeforeLoadingData + " MB");
List<SomeObject> somethingBigLoadedFromDatabase = loadSomethingBigFromDatabase();
long memoryUsageAfterLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory after loading some data: " + memoryUsageAfterLoadingData + " MB");
log.debug("Difference: " + (memoryUsageAfterLoadingData - memoryUsageBeforeLoadingData) + " MB");
someOperations(somethingBigLoadedFromDatabase);
}
private long getCurrentlyUsedMemory() {
System.gc();
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / BYTE_TO_MB_CONVERSION_VALUE;
}
``` |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | You can use profiler (for ex. JProfiler) for view memory usage by classes. Or , how mentioned Areo, just print memory usage:
```
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used Memory before" + usedMemoryBefore);
// working code here
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore));
``` | The easiest way to estimate memory usage is to use methods from `Runtime` class.
--------------------------------------------------------------------------------
**I suggest not to rely on it, but use it only for approximate estimations. Ideally you should only log this information and analyze it on your own, without using it for automation of your test or code.**
Probably it isn't very reliable, but in closed environment like unit test it may give you estimate close to reality.
Especially there is no guarantee that after calling `System.gc()` garbage collector will run when we expect it (it is only a suggestion for GC), there are precision limitations of the `freeMemory` method described there: <https://stackoverflow.com/a/17376879/1673775> and there might be more caveats.
### Solution:
```
private static final long BYTE_TO_MB_CONVERSION_VALUE = 1024 * 1024;
@Test
public void memoryUsageTest() {
long memoryUsageBeforeLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory before loading some data: " + memoryUsageBeforeLoadingData + " MB");
List<SomeObject> somethingBigLoadedFromDatabase = loadSomethingBigFromDatabase();
long memoryUsageAfterLoadingData = getCurrentlyUsedMemory();
log.debug("Used memory after loading some data: " + memoryUsageAfterLoadingData + " MB");
log.debug("Difference: " + (memoryUsageAfterLoadingData - memoryUsageBeforeLoadingData) + " MB");
someOperations(somethingBigLoadedFromDatabase);
}
private long getCurrentlyUsedMemory() {
System.gc();
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / BYTE_TO_MB_CONVERSION_VALUE;
}
``` |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | I can think of several options:
* Finding out how much memory your method requires via a microbenchmark (i.e. [jmh](http://openjdk.java.net/projects/code-tools/jmh/)).
* Building allocation strategies based on heuristic estimation. There are several open source solutions implementing class size estimation i.e. [ClassSize](http://svn.apache.org/repos/asf/hbase/branches/0.89-fb/src/main/java/org/apache/hadoop/hbase/util/ClassSize.java). A much easier way could be utilizing a cache which frees rarely used objects (i.e. Guava's Cache). As mentioned by @EnnoShioji, Guava's cache has memory-based eviction policies.
You can also write your own benchmark test which counts memory. The idea is to
1. Have a single thread running.
2. Create a new array to store your objects to allocate. So these objects won't be collected during GC run.
3. `System.gc()`, `memoryBefore = runtime.totalMemory() - runtime.freeMemory()`
4. Allocate your objects. Put them into the array.
5. `System.gc()`, `memoryAfter = runtime.totalMemory() - runtime.freeMemory()`
This is a technique I used in my [lightweight micro-benchmark tool](https://github.com/chaschev/experiments-with-microbes/blob/master/src/test/java/com/chaschev/microbe/samples/MemConsumptionTest.java) which is capable of measuring memory allocation with byte-precision. | Here is an example from Netty which does something similar: [MemoryAwareThreadPoolExecutor](http://grepcode.com/file/repo1.maven.org/maven2/org.jboss.netty/netty/3.0.0.CR1/org/jboss/netty/handler/execution/MemoryAwareThreadPoolExecutor.java). Guava's [cache class](https://code.google.com/p/guava-libraries/wiki/CachesExplained) has also a size based eviction. You could look at these sources and copy what they are doing. In particular, Here is how Netty is [estimating object sizes](http://grepcode.com/file/repo1.maven.org/maven2/com.ning/metrics.goodwill-access/0.0.10/org/jboss/netty/util/DefaultObjectSizeEstimator.java?av=h#DefaultObjectSizeEstimator). In essence, you'd estimate the size of the objects you generate in the method and keep a count.
Getting overall memory information (like how much heap is available/used) will help you decide how much memory usage to allocate to the method, but not to track how much memory was used by the individual method calls.
Having said that, it's very rare that you legitimately need this. In most cases, capping the memory usage by limiting how many objects can be there at a given point (e.g. by using a bounded queue) is good enough and is much, much simpler to implement. |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | You can use profiler (for ex. JProfiler) for view memory usage by classes. Or , how mentioned Areo, just print memory usage:
```
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used Memory before" + usedMemoryBefore);
// working code here
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore));
``` | To measure current memory usage use :
`Runtime.getRuntime().freeMemory()` ,
`Runtime.getRuntime().totalMemory()`
Here is a good example:
[get OS-level system information](https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information)
But this measurement is not precise but it can give you much information.
Another problem is with `GC` which is unpredictable. |
19,785,290 | Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
```
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
```
What is the right approach to do this? Or this is not possible/not feasible? | 2013/11/05 | [
"https://Stackoverflow.com/questions/19785290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990089/"
] | Here is an example from Netty which does something similar: [MemoryAwareThreadPoolExecutor](http://grepcode.com/file/repo1.maven.org/maven2/org.jboss.netty/netty/3.0.0.CR1/org/jboss/netty/handler/execution/MemoryAwareThreadPoolExecutor.java). Guava's [cache class](https://code.google.com/p/guava-libraries/wiki/CachesExplained) has also a size based eviction. You could look at these sources and copy what they are doing. In particular, Here is how Netty is [estimating object sizes](http://grepcode.com/file/repo1.maven.org/maven2/com.ning/metrics.goodwill-access/0.0.10/org/jboss/netty/util/DefaultObjectSizeEstimator.java?av=h#DefaultObjectSizeEstimator). In essence, you'd estimate the size of the objects you generate in the method and keep a count.
Getting overall memory information (like how much heap is available/used) will help you decide how much memory usage to allocate to the method, but not to track how much memory was used by the individual method calls.
Having said that, it's very rare that you legitimately need this. In most cases, capping the memory usage by limiting how many objects can be there at a given point (e.g. by using a bounded queue) is good enough and is much, much simpler to implement. | This question is a bit tricky, due to the way in which Java can allocate a lot of short-lived objects during processing, which will subsequently be collected during garbage collection. In the accepted answer, we cannot say with any certainty that garbage collection has been run at any given time. Even if we introduce a loop structure, with multiple `System.gc()` calls, garbage collection might run in between our method calls.
A better way is to instead use some variation of what is suggested in <https://cruftex.net/2017/03/28/The-6-Memory-Metrics-You-Should-Track-in-Your-Java-Benchmarks.html>, where `System.gc()` is triggered but we also wait for the reported GC count to increase:
```
long getGcCount() {
long sum = 0;
for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) {
long count = b.getCollectionCount();
if (count != -1) { sum += count; }
}
return sum;
}
long getReallyUsedMemory() {
long before = getGcCount();
System.gc();
while (getGcCount() == before);
return getCurrentlyAllocatedMemory();
}
long getCurrentlyAllocatedMemory() {
final Runtime runtime = Runtime.getRuntime();
return (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024);
}
```
This still gives only an approximation of the memory actually allocated by your code at a given time, but the value is typically much closer to what one would usually be interested in. |
39,410,484 | I have `View` with some components handles. I can change color of label like this.
`labelHandle.setForeground(Color.Blue);`
I want to make text of this `label` blinking - the idea is that on the `View` I will have method `blink(Boolean on)` and if I call `blink(true)` the method will start new thread which will be class implementing `Runnable`.
loop of `run()` will be something like this
```
run() {
for(;;) {
if(finished == true) break;
Thread.sleep(300);
//this will do the blinking
if(finished == true) break; //if durring sleep finish was called => end
if(change) labelHandle.setForeground(Color.Blue);
else labelHandle.setForeground(Color.Black);
change = (change) ? false : true; //switch the condition
}
}
```
There will be some important points:
```
boolean finished - says if the thread is finished, the loop for bliniking
void fihish() {this.finished = false;} //stops the thread job
boolean change - switch for the collors, each end of loop switch this value, if its true set one color, if its false sets another => here we have blinking ...
```
Until here its pretty clear how to do it. The main idea is make thread which will carry about the blinking.
In view I will call:
```
blink(true);
blink(false);
```
which will stars and stops the thread.
At one time only one view can be active, so I want have only one thread for blinking, which can be used with more views. The thread will be class implementing `Runnable` and should be `Singleton` to ensure, there will be only one thread.
Is it good idea to make `Singleton` thread like this? (Good or bad practice) | 2016/09/09 | [
"https://Stackoverflow.com/questions/39410484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097772/"
] | Just set the `.RequestTimeout` [property](https://msdn.microsoft.com/en-us/library/aa239748(v=vs.60).aspx):
```
With FTP
.URL = strHostName
.Protocol = 2
.UserName = strUserName
.Password = strPassWord
.RequestTimeout 5 '<------
.Execute , "Get " + strRemoteFileName + " " + strLocalFileName
``` | You should control this in your `.StillExecuting` loop
This should work I think. It mostly depends on what your `inet` class is: *custom* or *MSINET.OCX reference*. If it's custom you should have declared the `cancel` method.
```
Dim dtStart As Date
dtStart = Now
.Execute , "Get " + strRemoteFileName + " " + strLocalFileName
Do While .StillExecuting
If DateDiff("s", Now, dtStart) > 5 Then
' Cancel after5 seconds
.Cancel
.Execute , "CLOSE" ' Close the connection
MsgBox "Download cancelled after 5 seconds"
End If
DoEvents
Loop
``` |
4,631,616 | my code broke somewhere along the way, and crashes when using the navigation bar buttons.
Error message:
`*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView newMemoViewController:didAddMemo:]: unrecognized selector sent to instance 0x5b55a60'`
When debugging, the program does run the `cancel` method, and throws an exception at the `@synthesize` line. However, I cannot see anything wrong with it.
The symptoms are identical, so I am including the relevant code only for the `Cancel` button:
**NewMemoViewController.h**
```
#import <UIKit/UIKit.h>
@protocol NewMemoDelegate;
@class AKVoiceMemo;
@interface NewMemoViewController : UIViewController {
@private
AKVoiceMemo *voiceMemo;
id <NewMemoDelegate> delegate;
}
@property (nonatomic, retain) AKVoiceMemo *voiceMemo;
@property (nonatomic, assign) id <NewMemoDelegate> delegate;
@end
@protocol NewMemoDelegate <NSObject>
- (void)newMemoViewController:(NewMemoViewController *)newMemoViewController didAddMemo:(AKVoiceMemo *)voiceMemo;
@end
```
**NewMemoViewController.m**
```
#import "NewMemoViewController.h"
@synthesize delegate;
- (void)viewDidLoad {
UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)];
self.navigationItem.leftBarButtonItem = cancelButtonItem;
[cancelButtonItem release];
}
- (void)cancel {
[self.delegate newMemoViewController:self didAddMemo:nil];
}
```
Your help would be appreciated.
**Edit**: the delegate is the `RootViewController`:
```
- (void)newMemoViewController:(NewMemoViewController *)newMemoViewController didAddMemo:(AKVoiceMemo *)voiceMemo {
if (voiceMemo){
// Show the note in a new view controller
// TODO: Implement this
}
[self dismissModalViewControllerAnimated:YES];
}
``` | 2011/01/08 | [
"https://Stackoverflow.com/questions/4631616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560496/"
] | You're probably setting the delegate of `NewMemoViewController` to a `UIView` object instead of an object that implements the `NewMemoDelegate` protocol.
The error message is telling you that a `newMemoViewController:didAddMemo:` message was sent to a `UIView` object and the `UIView` object didn't know what to do with it. Since your `cancel` method calls `newMemoViewController:didAddMemo:` on the delegate, it is the *delegate* which is the `UIView` object that doesn't recognize the `newMemoViewController:didAddMemo:` message. In other words, your delegate is a `UIView` and it doesn't implement the `NewMemoDelegate` protocol.
If you are correctly setting the delegate, then @jtbandes makes a great point: The delegate is probably being released and a `UIView` object is taking over the same memory location, thus "becoming" the delegate by accident. You're doing the right thing by using the `assign` attribute for your delegate; that's fairly standard Cocoa practice. However, you do need to make sure that the delegate is retained by another object, and *that* object needs to make sure that the delegate sticks around as long as `NewMemoViewController` needs it to. | I'm guessing you've over-released the delegate. I notice you have `@property (assign) ... delegate;`. This means that whenever you set the delegate, that object must be retained by something else as well.
The other possibility is the delegate is actually a UIView, but I'm guessing it's the other case. |
23,824,950 | ```
<li class="row">
<div class="small-6 column center">
<img src="test.jpg">
</div>
<div class="small-6 column center">
<p>hello</p>
</div>
</li>
```
I wish to make the hello p in the centre (vertically and horizontally) of it's column.
I do this with the styles:
```
p{
bottom: 0;
left: 0;
margin: auto;
position: absolute;
top: 0;
right: 0;
}
```
The problem is, the second column is not the same height as the first column. How can I make it so that it is?
Here's my styles for columns:
```
.row{
width: 100%;
float: left;
.column{
width: 100%;
position: relative;
float: left;
display: block;
background: yellow;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
}
.small-1 {
width: 8.33333%; }
.small-2 {
width: 16.66667%;}
.small-3 {
width: 25%;}
.small-4 {
width: 33.33333%; }
.small-5 {
width: 41.66667%; }
.small-6 {
width: 50%; }
.small-7 {
width: 58.33333%; }
.small-8 {
width: 66.66667%; }
.small-9 {
width: 75%; }
.small-10 {
width: 83.33333%; }
.small-11 {
width: 91.66667%; }
.small-12 {
width: 100%; }
}
.pull-left{
float: left;
}
.pull-right{
float: right;
}
.center{
text-align: center;
}
``` | 2014/05/23 | [
"https://Stackoverflow.com/questions/23824950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013512/"
] | try this:-
```
#include<stdio.h>
#include<stdlib.h>
/*Queue has five properties. capacity stands for the maximum number of elements Queue can hold.
Size stands for the current size of the Queue and elements is the array of elements. front is the
index of first element (the index at which we remove the element) and rear is the index of last element
(the index at which we insert the element) */
typedef struct Queue
{
int capacity;
int size;
int front;
int rear;
int *elements;
}Queue;
/* crateQueue function takes argument the maximum number of elements the Queue can hold, creates
a Queue according to it and returns a pointer to the Queue. */
Queue * createQueue(int maxElements)
{
/* Create a Queue */
Queue *Q;
Q = (Queue *)malloc(sizeof(Queue));
/* Initialise its properties */
Q->elements = (int *)malloc(sizeof(int)*maxElements);
Q->size = 0;
Q->capacity = maxElements;
Q->front = 0;
Q->rear = -1;
/* Return the pointer */
return Q;
}
void Dequeue(Queue *Q)
{
/* If Queue size is zero then it is empty. So we cannot pop */
if(Q->size==0)
{
printf("Queue is Empty\n");
return;
}
/* Removing an element is equivalent to incrementing index of front by one */
else
{
Q->size--;
Q->front++;
/* As we fill elements in circular fashion */
if(Q->front==Q->capacity)
{
Q->front=0;
}
}
return;
}
int front(Queue *Q)
{
if(Q->size==0)
{
printf("Queue is Empty\n");
exit(0);
}
/* Return the element which is at the front*/
return Q->elements[Q->front];
}
void Enqueue(Queue *Q,int element)
{
/* If the Queue is full, we cannot push an element into it as there is no space for it.*/
if(Q->size == Q->capacity)
{
printf("Queue is Full\n");
}
else
{
Q->size++;
Q->rear = Q->rear + 1;
/* As we fill the queue in circular fashion */
if(Q->rear == Q->capacity)
{
Q->rear = 0;
}
/* Insert the element in its rear side */
Q->elements[Q->rear] = element;
}
return;
}
int main()
{
Queue *Q = createQueue(5);
Enqueue(Q,1);
Enqueue(Q,2);
Enqueue(Q,3);
Enqueue(Q,4);
printf("Front element is %d\n",front(Q));
Enqueue(Q,5);
Dequeue(Q);
Enqueue(Q,6);
printf("Front element is %d\n",front(Q));
}
``` | A solution using double pointers is probably the best. You are implementing a priority queue technically, not a list. You implement it by keeping a linked list that is sorted. The dequeue operation on a priority queue will remove the first item from the list.
As this is a homework assignment I set it up for you but you need to complete the rest so you can actually learn the important stuff.
EXIT CONDITION HERE -> This is where you want to check when you have found the item where you will insert after. Write this condition so that the loop exits when this occurs.
EDIT ^^ -> When I say the item where you will insert after what I mean is that the item you currently are looking at is the first item that is "greater" than temp. `queue` will be pointing to the next pointer to that item. I also added a line in the code that will make set `temp`'s next to point to that item. When you update `*queue` you are saying that you want to make the next pointer on the previous item point to `*temp`.
update the pointer here -> This is where you update `queue` to point to the next pointer of the next person in the list/queue.
```
typedef struct Person {
char name[20];
int age;
struct Person *next;
} Person;
void enqueue(Person **queue, char *name, int age) {
Person *temp = calloc(1, sizeof(Person));
strncpy(temp->name, name, 20);
temp->age = age;
while (*queue && "EXIT CONDITION HERE")
//update the pointer here;
temp->next = *queue; //forgot this line originally. You need it!!
*queue = temp; //.this sets the next pointer of last item or head to temp
}
...
Person *queue = NULL;
enqueue(&queue, "Bob", 10);
enqueue(&queue, "John", 5);
Then print the list to check that enqueue works correctly.
``` |
23,824,950 | ```
<li class="row">
<div class="small-6 column center">
<img src="test.jpg">
</div>
<div class="small-6 column center">
<p>hello</p>
</div>
</li>
```
I wish to make the hello p in the centre (vertically and horizontally) of it's column.
I do this with the styles:
```
p{
bottom: 0;
left: 0;
margin: auto;
position: absolute;
top: 0;
right: 0;
}
```
The problem is, the second column is not the same height as the first column. How can I make it so that it is?
Here's my styles for columns:
```
.row{
width: 100%;
float: left;
.column{
width: 100%;
position: relative;
float: left;
display: block;
background: yellow;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
}
.small-1 {
width: 8.33333%; }
.small-2 {
width: 16.66667%;}
.small-3 {
width: 25%;}
.small-4 {
width: 33.33333%; }
.small-5 {
width: 41.66667%; }
.small-6 {
width: 50%; }
.small-7 {
width: 58.33333%; }
.small-8 {
width: 66.66667%; }
.small-9 {
width: 75%; }
.small-10 {
width: 83.33333%; }
.small-11 {
width: 91.66667%; }
.small-12 {
width: 100%; }
}
.pull-left{
float: left;
}
.pull-right{
float: right;
}
.center{
text-align: center;
}
``` | 2014/05/23 | [
"https://Stackoverflow.com/questions/23824950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013512/"
] | try this:-
```
#include<stdio.h>
#include<stdlib.h>
/*Queue has five properties. capacity stands for the maximum number of elements Queue can hold.
Size stands for the current size of the Queue and elements is the array of elements. front is the
index of first element (the index at which we remove the element) and rear is the index of last element
(the index at which we insert the element) */
typedef struct Queue
{
int capacity;
int size;
int front;
int rear;
int *elements;
}Queue;
/* crateQueue function takes argument the maximum number of elements the Queue can hold, creates
a Queue according to it and returns a pointer to the Queue. */
Queue * createQueue(int maxElements)
{
/* Create a Queue */
Queue *Q;
Q = (Queue *)malloc(sizeof(Queue));
/* Initialise its properties */
Q->elements = (int *)malloc(sizeof(int)*maxElements);
Q->size = 0;
Q->capacity = maxElements;
Q->front = 0;
Q->rear = -1;
/* Return the pointer */
return Q;
}
void Dequeue(Queue *Q)
{
/* If Queue size is zero then it is empty. So we cannot pop */
if(Q->size==0)
{
printf("Queue is Empty\n");
return;
}
/* Removing an element is equivalent to incrementing index of front by one */
else
{
Q->size--;
Q->front++;
/* As we fill elements in circular fashion */
if(Q->front==Q->capacity)
{
Q->front=0;
}
}
return;
}
int front(Queue *Q)
{
if(Q->size==0)
{
printf("Queue is Empty\n");
exit(0);
}
/* Return the element which is at the front*/
return Q->elements[Q->front];
}
void Enqueue(Queue *Q,int element)
{
/* If the Queue is full, we cannot push an element into it as there is no space for it.*/
if(Q->size == Q->capacity)
{
printf("Queue is Full\n");
}
else
{
Q->size++;
Q->rear = Q->rear + 1;
/* As we fill the queue in circular fashion */
if(Q->rear == Q->capacity)
{
Q->rear = 0;
}
/* Insert the element in its rear side */
Q->elements[Q->rear] = element;
}
return;
}
int main()
{
Queue *Q = createQueue(5);
Enqueue(Q,1);
Enqueue(Q,2);
Enqueue(Q,3);
Enqueue(Q,4);
printf("Front element is %d\n",front(Q));
Enqueue(Q,5);
Dequeue(Q);
Enqueue(Q,6);
printf("Front element is %d\n",front(Q));
}
``` | The following code should do the work. It will add to the list in increasing age order:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node_t {
int age;
char *name;
struct _node_t *nextPtr;
} node_t;
node_t *node;
void enqueue(char *name, int age)
{
node_t *p, *prev, *n;
/* if empty list create first element and return */
if (node == NULL)
{
node = (node_t *)malloc(sizeof(node_t));
node->nextPtr = NULL;
node->name = (char *)malloc(strlen(name) + 1);
strcpy(node->name, name);
node->age = age;
return;
}
p = prev = node;
/* search last element or element with superior age value */
while((p->nextPtr != NULL) && strcmp(p->name, name) < 0)
{
prev = p;
p = p->nextPtr;
}
if (strcmp(p->name, name) == 0)
{
while((p->nextPtr != NULL) && p->age < age)
{
prev = p;
p = p->nextPtr;
}
}
/* create the new element and store the data */
n = (node_t *)malloc(sizeof(node_t));
n->name = (char *)malloc(strlen(name) + 1);
strcpy(n->name, name);
n->age = age;
/* insert the new element */
if ((strcmp(p->name, name) < 0) || (strcmp(p->name, name) == 0 && p->age < age))
{
n->nextPtr = p->nextPtr;
p->nextPtr = n;
}
else
{
n->nextPtr = p;
if (prev->nextPtr == p)
{
prev->nextPtr = n;
}
else if (node == p)
{
node = n;
}
}
}
void printNodes()
{
node_t *p;
p = node;
while(p != NULL)
{
printf("%s, %d\n", p->name, p->age);
p = p->nextPtr;
}
}
int main(int argc, char **argv)
{
node = NULL;
enqueue("Kill", 15);
enqueue("Bill", 2);
enqueue("Kill", 7);
printNodes();
return 0;
}
```
So the following adding:
```
enqueue("Kill", 15);
enqueue("Bill", 2);
enqueue("Kill", 7);
```
Will store it in the order printed by `printNodes()`:
```
Bill, 2
Kill, 7
Kill, 15
```
UPDATED:
Added name sorting then age. |
1,115,973 | I've noticed an increasing number of jobs that are asking for experience with data mining and business intelligence technologies. This sounds like an incredibly broad topic but where would one go if they wanted to develop at least a partial understanding of this stuff if it were to come up in an interview? | 2009/07/12 | [
"https://Stackoverflow.com/questions/1115973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132153/"
] | A very good book with practical examples is the
[Programming Collective Intelligence: Building Smart Web 2.0 Applications](https://rads.stackoverflow.com/amzn/click/com/0596529325) by Toby Segaran. | Go read [Data Mining: Practical Machine Learning Tools and Techniques (Second Edition)](http://www.cs.waikato.ac.nz/~ml/weka/book.html).
Then use [Weka](http://www.cs.waikato.ac.nz/~ml/weka/index.html) on a pet project. Despite the name, this is a good book, and the Weka package has several levels of entry into the data-m... er machine-learning world. |
1,115,973 | I've noticed an increasing number of jobs that are asking for experience with data mining and business intelligence technologies. This sounds like an incredibly broad topic but where would one go if they wanted to develop at least a partial understanding of this stuff if it were to come up in an interview? | 2009/07/12 | [
"https://Stackoverflow.com/questions/1115973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132153/"
] | Go read [Data Mining: Practical Machine Learning Tools and Techniques (Second Edition)](http://www.cs.waikato.ac.nz/~ml/weka/book.html).
Then use [Weka](http://www.cs.waikato.ac.nz/~ml/weka/index.html) on a pet project. Despite the name, this is a good book, and the Weka package has several levels of entry into the data-m... er machine-learning world. | Consider reading [Ralph Kimball's books](http://www.amazon.com/s/ref=nb_ss?url=search-alias%3Daps&field-keywords=ralph+kimball&x=0&y=0) for an introduction to Business Intelligence.
Also, try to not stick to one technolgy-vendor, every company has its own biased vision of BI, you'll need a 360 overview. |
1,115,973 | I've noticed an increasing number of jobs that are asking for experience with data mining and business intelligence technologies. This sounds like an incredibly broad topic but where would one go if they wanted to develop at least a partial understanding of this stuff if it were to come up in an interview? | 2009/07/12 | [
"https://Stackoverflow.com/questions/1115973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132153/"
] | Go read [Data Mining: Practical Machine Learning Tools and Techniques (Second Edition)](http://www.cs.waikato.ac.nz/~ml/weka/book.html).
Then use [Weka](http://www.cs.waikato.ac.nz/~ml/weka/index.html) on a pet project. Despite the name, this is a good book, and the Weka package has several levels of entry into the data-m... er machine-learning world. | Maybe you can also try to work with real BI - it is almost impossible to get in contact with data-filled and running SAS, MS, Oracle etc. I work in a team which integrates BI BellaDati for enterprises. For try-out and personal purposes it is free with some datastore limitations ( <http://www.trgiman.eu/en/belladati/product/personal> ).
BellaDati is also used as a learning tool on technical universities focused on practical application of data mining and analysis. The final manager-level dashboards examples of BellaDati can be seen at <http://mercato.belladati.com/bi/mercato/show/worldexchanges>
You can work here with SQL datasources, flat files, web services and play. From my own experience - to show real samples of market analysis practise (like case study etc.) is good for an interview.
I wish you luck,
Peter |
1,115,973 | I've noticed an increasing number of jobs that are asking for experience with data mining and business intelligence technologies. This sounds like an incredibly broad topic but where would one go if they wanted to develop at least a partial understanding of this stuff if it were to come up in an interview? | 2009/07/12 | [
"https://Stackoverflow.com/questions/1115973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132153/"
] | A very good book with practical examples is the
[Programming Collective Intelligence: Building Smart Web 2.0 Applications](https://rads.stackoverflow.com/amzn/click/com/0596529325) by Toby Segaran. | Consider reading [Ralph Kimball's books](http://www.amazon.com/s/ref=nb_ss?url=search-alias%3Daps&field-keywords=ralph+kimball&x=0&y=0) for an introduction to Business Intelligence.
Also, try to not stick to one technolgy-vendor, every company has its own biased vision of BI, you'll need a 360 overview. |
1,115,973 | I've noticed an increasing number of jobs that are asking for experience with data mining and business intelligence technologies. This sounds like an incredibly broad topic but where would one go if they wanted to develop at least a partial understanding of this stuff if it were to come up in an interview? | 2009/07/12 | [
"https://Stackoverflow.com/questions/1115973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132153/"
] | A very good book with practical examples is the
[Programming Collective Intelligence: Building Smart Web 2.0 Applications](https://rads.stackoverflow.com/amzn/click/com/0596529325) by Toby Segaran. | Maybe you can also try to work with real BI - it is almost impossible to get in contact with data-filled and running SAS, MS, Oracle etc. I work in a team which integrates BI BellaDati for enterprises. For try-out and personal purposes it is free with some datastore limitations ( <http://www.trgiman.eu/en/belladati/product/personal> ).
BellaDati is also used as a learning tool on technical universities focused on practical application of data mining and analysis. The final manager-level dashboards examples of BellaDati can be seen at <http://mercato.belladati.com/bi/mercato/show/worldexchanges>
You can work here with SQL datasources, flat files, web services and play. From my own experience - to show real samples of market analysis practise (like case study etc.) is good for an interview.
I wish you luck,
Peter |
18,219 | I'm going to try to provide a high level overview of the issue - realizing that more details/info will be necessary - but I don't want to write a novel that seems too overwhelming for people to respond to :)
**Background**:
Let's say I have 3 sets (A, B, C) of irregular point data of varying quality; A is "better" than B and B is "better" than C. One or more data sets might have data for a given point.
**Goal**:
Create a grid/map that contains the "best" possible data.
**Example/Possible Solution**:
Use some sort of inverse distance weighted algorithm in combination w/somehow weighting the better datasets more than the lower quality data sets.
Please feel free to post follow-up questions as I know my original post is rather vague. Thanks in advance. | 2011/12/26 | [
"https://gis.stackexchange.com/questions/18219",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/1384/"
] | When "best" is interpreted as "minimum variance unbiased estimator," then **the answer is [cokriging](http://www.gammadesign.com/gswinhelp/kriging_and_cokriging/cokriging.htm)**. This technique views the three datasets as realizations of three correlated spatial stochastic processes. It characterizes the process and their correlations by means of a preliminary analysis, "variography." The variography can be informed by additional considerations such as the relative quality of the datasets: this would cause the analyst to prefer variogram models that assign higher variances to the lower-quality datasets. Then, the co-kriging algorithm itself uses the data and the variographic output (a set of "pseudo co-variograms") to predict any desired linear combination of the three datasets (such as the mean values of dataset "A" within specified grid cells).
**A simple, limiting version of co-kriging** supposes the three datasets are not correlated with each other at all. In this case, each of the datasets can be kriged separately. (This means a variogram model is fit to each dataset separately and used separately to interpolate the data values onto a grid of specified locations.) The kriging output includes a kriging variance. Assuming each dataset represents the same physical quantity, the question becomes how to combine the three estimated values at each grid point into the "best" possible estimate of that quantity. The answer is to take a weighted average of the three estimates, using the reciprocals of the kriging variances as the weights. The result remains unbiased because the three inputs are unbiased by construction; weighting inversely by variance assures the result has the smallest variance, which is exactly what "best" was assumed to mean.
**Kriging and co-kriging are available** in the Geostatistical Analyst add-on for ArcGIS (at an extra cost) and in freely available software such as the [gstat](http://www.itc.nl/~rossiter/teach/R/R_ck.pdf) package for R. These are not activities to be undertaken casually: they are sophisticated, comprehensive analyses of the data that become valid *only* as a result of reasoned, accurate statistical characterization. Although software for kriging and co-kriging has long been available in many GIS environments, IMHO **kriging is *not* an activity to be performed solely by a GIS analyst**, because it requires close collaboration both with a seasoned statistician and an expert in the field of study. (Occasionally two of these three roles or even all three may be adequately filled by the same person, but this is rare.) It is one of those especially dangerous capabilities of a GIS because kriging *output* is easily created by anyone who can push the right buttons (a task that can be learned in 30 minutes with ESRI's excellent tutorial on Geostatistical Analyst, for instance) and will often *look* correct but is just the "GO" part of the proverbial [GIGO](http://en.wikipedia.org/wiki/Garbage_in,_garbage_out). | One thing I can come up with is to use simulation. For each of your observations you have a probability distribution, e.g. a normal distribution. For the low quality observations these probablity distributions are larger. From each of these observations you can draw a realization of the prob. distribution, interpolate the values, resulting in a map. Doing this a few thousand times will get you a probability distribution for each gridpoint in the inteprolation. From this you can extract for example the mean. In addition, you can use the probability distributions at the interpolation gridpoints to get an estimate of the uncertainty at each location. You probably cannot draw independent values at of your observations, but have to draw with a spatial dependency between the points.
I'm not sure how this would work from a statistical point of view using e.g. kriging, i.e. is the prob. distribution at the interpolation points valid given all the statistical assumptions in the realizations of the input points.
This kind of thing can probably most easily be done in a programming environment such as R or matlab. |
60,512,703 | In my Laravel-5.8, I passed data from controller to view using JSON.
```
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$maxscore2 = 1;
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore,
'maxscore2' => $maxscore2
]);
}
```
**Route**
```
Route::get('get/findScore','Appraisal\AppraisalGoalsController@findScore')
->name('get.scores.all');
```
**View**
```
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
@foreach ($categories as $category)
@unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
@if ($category->children)
@foreach ($category->children as $child)
@unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
@endunless
@endforeach
@endif
@endunless
@endforeach
</select>
</div>
</div>
<input type="text" id="max_score" value="max_score" class="form-control" >
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
console.log(data.maxscore);
console.log(data.maxscore2);
$('#max_score').val(data.maxscore);
},
error:function(){
}
});
});
});
</script>
```
When I click on the dropdown on change, I got these:
Console:
[](https://i.stack.imgur.com/MHyiJ.png)
textbox:
[](https://i.stack.imgur.com/zZEvl.png)
I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only the 75 in the textbox.
How do I get this resolved?
Thank you. | 2020/03/03 | [
"https://Stackoverflow.com/questions/60512703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12510040/"
] | It seems to me that the LoginController is unnecessary.
The spring security configuration has already defined the authenticationProvider to authenticate your login, you don't need another Controller to do the same thing.
Try this:
1. remove the LoginController
2. change the login success URL to '/homeLogged'
```
http
.formLogin()
.defaultSuccessUrl("/homeLogged", true)
.permitAll();
```
And if you want to use your own custom login page, say login.jsp, you can add it after the formLogin() like this:
```
http
.formLogin().loginPage("/login.jsp")
.defaultSuccessUrl("/homeLogged", true)
.permitAll();
```
And in your login.jsp, you shall have three elements:
1. action: "login", which will post the request to url: login
2. username field
3. password field
and your authenticator defined in the your security config will authenticate the username and password and then redirect to the successful URL. | You're not really using Spring Security to its full extent. There might be a way to make it work using this strange way of logging in but what I would suggest is that you just do things the Spring way:
Make the entity you're using for logging in (`User.class` for example) implements Spring's [UserDetails](https://docs.spring.io/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/userdetails/UserDetails.html) interface (don't forget to add logic to the boolean methods like `isEnabled()` so that they don't always return false). Then choose a service to implement Spring's [UserDetailsService](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetailsService.html) interface which forces you to override the method `loadUserByUsername()` which is used to get the user from the database. And lastly in your `SecurityConfig` switch `auth.authenticationProvider(authenticationProvider);` with `auth.userDetailsService(userService).passwordEncoder(passwordEncoder);` where `userService` is the `@Component` class which implements UserDetailsService and `passwordEncoder` is just a [BCryptPasswordEncoder](https://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/apidocs/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.html) `@Bean`
```
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
};
``` |
20,254,934 | This question is **only for Python programmers**. This question is **not duplicate not working** [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) see explanation bottom.
---
I want to add/subtract for any float some smallest values which will change this float value about one bit of [mantissa/significant part](http://en.wikipedia.org/wiki/Floating_point). How to calculate such small number efficiently in **pure Python**.
For example I have such array of x:
```
xs = [1e300, 1e0, 1e-300]
```
What will be function for it to generate **the smallest value**? All assertion should be valid.
```
for x in xs:
assert x < x + smallestChange(x)
assert x > x - smallestChange(x)
```
Consider that `1e308 + 1 == 1e308` since `1` does means `0` for mantissa so `smallestChange' should be dynamic.
Pure Python solution will be the best.
---
**Why this is not duplicate of [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount)** - two simple tests prove it with invalid results.
(1) The question is not aswered in [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) difference:
**[Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) just not works try this code**:
```
import math
epsilon = math.ldexp(1.0, -53) # smallest double that 0.5+epsilon != 0.5
maxDouble = float(2**1024 - 2**971) # From the IEEE 754 standard
minDouble = math.ldexp(1.0, -1022) # min positive normalized double
smallEpsilon = math.ldexp(1.0, -1074) # smallest increment for doubles < minFloat
infinity = math.ldexp(1.0, 1023) * 2
def nextafter(x,y):
"""returns the next IEEE double after x in the direction of y if possible"""
if y==x:
return y #if x==y, no increment
# handle NaN
if x!=x or y!=y:
return x + y
if x >= infinity:
return infinity
if x <= -infinity:
return -infinity
if -minDouble < x < minDouble:
if y > x:
return x + smallEpsilon
else:
return x - smallEpsilon
m, e = math.frexp(x)
if y > x:
m += epsilon
else:
m -= epsilon
return math.ldexp(m,e)
print nextafter(0.0, -1.0), 'nextafter(0.0, -1.0)'
print nextafter(-1.0, 0.0), 'nextafter(-1.0, 0.0)'
```
Results of [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) is invalid:
```
>>> nextafter(0.0, -1)
0.0
```
Should be nonzero.
```
>>> nextafter(-1,0)
-0.9999999999999998
```
Should be '-0.9999999999999999'.
(2) It was not asked how to add/substract the smallest value but was asked how to add/substract value in specific direction - propose solution is need to know x and y. Here is required to know only x.
(3) Propose solution in [Increment a python floating point value by the smallest possible amount](https://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount) will not work on border conditions. | 2013/11/27 | [
"https://Stackoverflow.com/questions/20254934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665926/"
] | ```
>>> (1.0).hex()
'0x1.0000000000000p+0'
>>> float.fromhex('0x0.0000000000001p+0')
2.220446049250313e-16
>>> 1.0 + float.fromhex('0x0.0000000000001p+0')
1.0000000000000002
>>> (1.0 + float.fromhex('0x0.0000000000001p+0')).hex()
'0x1.0000000000001p+0'
```
Just use the same sign and exponent. | [Mark Dickinson's answer to a duplicate](https://stackoverflow.com/a/10426033/49793) fares much better, but still fails to give the correct results for the parameters `(0, 1)`.
This is probably a good starting point for a pure Python solution. However, getting this exactly right in all cases is not easy, as there are many corner cases. So you should have a really good unit test suite to cover all corner cases.
Whenever possible, you should consider using one of the solutions that are based on the well-tested C runtime function instead (i.e. via `ctypes` or `numpy`).
You mentioned somewhere that you are concerned about the memory overhead of `numpy`. However, the effect of this one function on your working set shout be very small, certainly not several Megabytes (that might be virtual memory or private bytes.) |
68,018,124 | My Loading component:
```
import React from 'react'
export default class Loading extends React.Component {
constructor(props) {
super(props)
this.state = {
display: 'none'
}
}
render() {
return (
<div className="loading" style={{display: this.state.display}}>
<span></span>
</div>
)
}
}
```
And I want change `display` from `App.js`
```
Loading.setState ...
```
Or
```
var lng = new Loading()
lng.setState ...
```
Both of them not work
I want can change state from another class or function | 2021/06/17 | [
"https://Stackoverflow.com/questions/68018124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11259682/"
] | If you want to change `display` from `App.js`:
1. Pass it as prop to `Loading` component, and keep the state at `App.js`.
2. pass some prop from `App.js` and when it changes - change the state
of `display` in `App.js`
3. Use some global state/store manager like [Redux](https://react-redux.js.org/introduction/getting-started) or built-in [useContext](https://reactjs.org/docs/hooks-reference.html#usecontext) react-hook, in this case you will be able to change from any component connected to store | [Solution sample](https://codesandbox.io/s/gallant-mccarthy-xf98m?file=/src/App.js:0-485)
A simple solution can be found in a code sandbox example. |
13,306,013 | I have a Master Page based Web site that has menu functionality. CSS is read from a Style.css file successfully. I have now added a seperate Login.aspx page which functions fine, but does not pick up the Account.css file, which has the specific css for the Login page. I do not want the login page to refernence the master page.
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<link href="Account.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$('.grid_12').fadeIn(1750);
});
</script>
</head>
```
I would appreciate any insight, as I have tried referencing the Account.css file path every way i can think of:
```
href="./Account.css"
href="Account.css"
href="~/Account.css"
```
I have now placed the Login.aspx page and Account.css file in a new login folder at website root. | 2012/11/09 | [
"https://Stackoverflow.com/questions/13306013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1811813/"
] | There may be a region that your are using form authentication.
If yes then you can use
```
<location path="Account.css">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
```
Inside
```
<appSettings></appSettings>
```
Else you can use
```
<style type="text/css" src='<%= ResolveUrl("Account.css")%>'></script>
``` | Seems you are hosting your site on IIS in a virtual directory. If you do that, your path must reflect the virtual directory.
```
href="/virtualDir/Account.css"
```
To do this is asp.net use [`ResolveClientUrl`](http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveclienturl.aspx)
```
href="<%= ResolveClientUrl("~/Account.css") %>"
``` |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | If you have installed, for example, php 5.4 it could be switched in the following way to php 5.5:
```
$ php --version
PHP 5.4.32 (cli) (built: Aug 26 2014 15:14:01)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
$ brew unlink php54
$ brew switch php55 5.5.16
$ php --version
PHP 5.5.16 (cli) (built: Sep 9 2014 14:27:18)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
``` | if @simon's answer is not working in some of the mac's please follow the below process.
If you have already installed swiftgen using the following commands:
$ `brew update`
$ `brew install swiftgen`
then follow the steps below in order to run swiftgen with older version.
Step 1: `brew uninstall swiftgen`
Step 2: Navigate to: <https://github.com/SwiftGen/SwiftGen/releases>
and download the swiftgen with version: swiftgen-4.2.0.zip.
Unzip the package in any of the directories.
Step 3:
Execute the following in a terminal:
```
$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/
$ swiftgen --version
```
You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)
[](https://i.stack.imgur.com/YKnK2.png) |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | **[This is probably the best way as of 11.1.2022](https://stackoverflow.com/a/9832084/1574376):**
To install a specific version, e.g. postgresql 9.5 you simply run:
```
$ brew install [email protected]
```
To list the available versions run a search with @:
```
$ brew search postgresql@
==> Formulae
postgresql postgresql@11 postgresql@13 [email protected] qt-postgresql
postgresql@10 postgresql@12 [email protected] [email protected] postgrest
==> Casks
navicat-for-postgresql
```
---
**DEPRECATED in Homebrew 2.6.0 (December 2020):**
The usage info:
```
Usage: brew switch <formula> <version>
```
Example:
```
brew switch mysql 5.5.29
```
You can find the versions installed on your system with `info`.
```
brew info mysql
```
And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:
```
brew switch mysql 0
```
---
**Update (15.10.2014):**
The `brew versions` command has been removed from brew, but, if you do wish to use this command first run `brew tap homebrew/boneyard`.
The recommended way to install an old version is to install from the `homebrew/versions` repo as follows:
```
$ brew tap homebrew/versions
$ brew install mysql55
```
---
For detailed info on all the ways to install an older version of a formula read [this answer](https://stackoverflow.com/a/4158763/1574376). | if @simon's answer is not working in some of the mac's please follow the below process.
If you have already installed swiftgen using the following commands:
$ `brew update`
$ `brew install swiftgen`
then follow the steps below in order to run swiftgen with older version.
Step 1: `brew uninstall swiftgen`
Step 2: Navigate to: <https://github.com/SwiftGen/SwiftGen/releases>
and download the swiftgen with version: swiftgen-4.2.0.zip.
Unzip the package in any of the directories.
Step 3:
Execute the following in a terminal:
```
$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/
$ swiftgen --version
```
You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)
[](https://i.stack.imgur.com/YKnK2.png) |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | **[This is probably the best way as of 11.1.2022](https://stackoverflow.com/a/9832084/1574376):**
To install a specific version, e.g. postgresql 9.5 you simply run:
```
$ brew install [email protected]
```
To list the available versions run a search with @:
```
$ brew search postgresql@
==> Formulae
postgresql postgresql@11 postgresql@13 [email protected] qt-postgresql
postgresql@10 postgresql@12 [email protected] [email protected] postgrest
==> Casks
navicat-for-postgresql
```
---
**DEPRECATED in Homebrew 2.6.0 (December 2020):**
The usage info:
```
Usage: brew switch <formula> <version>
```
Example:
```
brew switch mysql 5.5.29
```
You can find the versions installed on your system with `info`.
```
brew info mysql
```
And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:
```
brew switch mysql 0
```
---
**Update (15.10.2014):**
The `brew versions` command has been removed from brew, but, if you do wish to use this command first run `brew tap homebrew/boneyard`.
The recommended way to install an old version is to install from the `homebrew/versions` repo as follows:
```
$ brew tap homebrew/versions
$ brew install mysql55
```
---
For detailed info on all the ways to install an older version of a formula read [this answer](https://stackoverflow.com/a/4158763/1574376). | `brew switch libfoo mycopy`
You can use `brew switch` to switch between versions of the same package, if it's installed as versioned subdirectories under `Cellar/<packagename>/`
This will list versions installed ( for example I had `Cellar/sdl2/2.0.3`, I've compiled into `Cellar/sdl2/2.0.4`)
```
brew info sdl2
```
Then to switch between them
```
brew switch sdl2 2.0.4
brew info
```
Info now shows `*` next to the 2.0.4
To install under `Cellar/<packagename>/<version>` from source you can do for example
```
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
```
check where it gets installed with
```
make install -n
```
if all looks correct
```
make install
```
Then from `cd $(brew --Cellar)` do the switch between version.
I'm using `brew version 0.9.5` |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | Sadly `brew switch` is deprecated in [Homebrew 2.6.0](https://brew.sh/2020/12/01/homebrew-2.6.0/) (December 2020)
```
$ brew switch
Error: Unknown command: switch
```
TLDR, to switch to `package` version `10`:
```sh
brew unlink package
brew link package@10
```
---
To use another version of a package, for example `node`:
* First, ensure that the specific version is installed using `brew list`. My package here is `node` (16) and `node@14`.
```
➜ ~ brew list
==> Formulae
node
node@14
➜ ~ node -v
v16.1.0
```
* Unlink the current package: `brew unlink node`.
```
➜ ~ brew unlink node
Unlinking /usr/local/Cellar/node/16.1.0... 7 symlinks removed.
```
* Link the correct version
```
➜ ~ brew link node@14
Linking /usr/local/Cellar/node@14/14.16.1_1... 3857 symlinks created.
If you need to have this software first in your PATH instead consider running:
echo 'export PATH="/usr/local/opt/node@14/bin:$PATH"' >> ~/.zshrc
➜ ~ node -v
v14.16.1
``` | Homebrew removed `brew switch` subcommand in [Homebrew 2.6.0](https://brew.sh/2020/12/01/homebrew-2.6.0/). Get it back from [here](https://github.com/laggardkernel/homebrew-tap#external-commands).
```sh
brew tap laggardkernel/tap
brew switch --help
```
---
### name@version formula
There's mainly two ways to switch to an old version of an app.
If it's a bigger version change. Homebrew may have created a versioned package in the repo. Like `go`, `[email protected]`, they are two different formulae, installed into two different locations.
```sh
# install the old one
brew install [email protected]
# link the executable into /usr/local/bin, or /opt/homebrew/bin
brew link --overwrite --force [email protected]
```
### brew switch
But not every package has a versioned variant. If you just upgraded to the new version and the old one is still in your system, skip step 1, 2.
1. In this situation, search in the [homebrew-core](https://github.com/Homebrew/homebrew-core/) repo and download the specific formula. e.g. [mysql 8.0.23](https://github.com/Homebrew/homebrew-core/blob/58946207e43b0e7222f6c920ef4b053e52baf76d/Formula/mysql.rb)
2. Download the **raw** file, and install from it `brew install /path/to/downloaded/mysql.rb`.
3. Now both the latest and the old 8.0.23 (same formula `mysql`) exist, switch (link out) the old version with `brew switch mysql 8.0.23`
`brew info mysql` will list all the old version still exist.
Step 1, 2 could be replaced by `brew extract`, but that requires user maintain its own tap. I won't cover it here, just search it if you're interested. |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | **[This is probably the best way as of 11.1.2022](https://stackoverflow.com/a/9832084/1574376):**
To install a specific version, e.g. postgresql 9.5 you simply run:
```
$ brew install [email protected]
```
To list the available versions run a search with @:
```
$ brew search postgresql@
==> Formulae
postgresql postgresql@11 postgresql@13 [email protected] qt-postgresql
postgresql@10 postgresql@12 [email protected] [email protected] postgrest
==> Casks
navicat-for-postgresql
```
---
**DEPRECATED in Homebrew 2.6.0 (December 2020):**
The usage info:
```
Usage: brew switch <formula> <version>
```
Example:
```
brew switch mysql 5.5.29
```
You can find the versions installed on your system with `info`.
```
brew info mysql
```
And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:
```
brew switch mysql 0
```
---
**Update (15.10.2014):**
The `brew versions` command has been removed from brew, but, if you do wish to use this command first run `brew tap homebrew/boneyard`.
The recommended way to install an old version is to install from the `homebrew/versions` repo as follows:
```
$ brew tap homebrew/versions
$ brew install mysql55
```
---
For detailed info on all the ways to install an older version of a formula read [this answer](https://stackoverflow.com/a/4158763/1574376). | Homebrew removed `brew switch` subcommand in [Homebrew 2.6.0](https://brew.sh/2020/12/01/homebrew-2.6.0/). Get it back from [here](https://github.com/laggardkernel/homebrew-tap#external-commands).
```sh
brew tap laggardkernel/tap
brew switch --help
```
---
### name@version formula
There's mainly two ways to switch to an old version of an app.
If it's a bigger version change. Homebrew may have created a versioned package in the repo. Like `go`, `[email protected]`, they are two different formulae, installed into two different locations.
```sh
# install the old one
brew install [email protected]
# link the executable into /usr/local/bin, or /opt/homebrew/bin
brew link --overwrite --force [email protected]
```
### brew switch
But not every package has a versioned variant. If you just upgraded to the new version and the old one is still in your system, skip step 1, 2.
1. In this situation, search in the [homebrew-core](https://github.com/Homebrew/homebrew-core/) repo and download the specific formula. e.g. [mysql 8.0.23](https://github.com/Homebrew/homebrew-core/blob/58946207e43b0e7222f6c920ef4b053e52baf76d/Formula/mysql.rb)
2. Download the **raw** file, and install from it `brew install /path/to/downloaded/mysql.rb`.
3. Now both the latest and the old 8.0.23 (same formula `mysql`) exist, switch (link out) the old version with `brew switch mysql 8.0.23`
`brew info mysql` will list all the old version still exist.
Step 1, 2 could be replaced by `brew extract`, but that requires user maintain its own tap. I won't cover it here, just search it if you're interested. |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | Homebrew removed `brew switch` subcommand in [Homebrew 2.6.0](https://brew.sh/2020/12/01/homebrew-2.6.0/). Get it back from [here](https://github.com/laggardkernel/homebrew-tap#external-commands).
```sh
brew tap laggardkernel/tap
brew switch --help
```
---
### name@version formula
There's mainly two ways to switch to an old version of an app.
If it's a bigger version change. Homebrew may have created a versioned package in the repo. Like `go`, `[email protected]`, they are two different formulae, installed into two different locations.
```sh
# install the old one
brew install [email protected]
# link the executable into /usr/local/bin, or /opt/homebrew/bin
brew link --overwrite --force [email protected]
```
### brew switch
But not every package has a versioned variant. If you just upgraded to the new version and the old one is still in your system, skip step 1, 2.
1. In this situation, search in the [homebrew-core](https://github.com/Homebrew/homebrew-core/) repo and download the specific formula. e.g. [mysql 8.0.23](https://github.com/Homebrew/homebrew-core/blob/58946207e43b0e7222f6c920ef4b053e52baf76d/Formula/mysql.rb)
2. Download the **raw** file, and install from it `brew install /path/to/downloaded/mysql.rb`.
3. Now both the latest and the old 8.0.23 (same formula `mysql`) exist, switch (link out) the old version with `brew switch mysql 8.0.23`
`brew info mysql` will list all the old version still exist.
Step 1, 2 could be replaced by `brew extract`, but that requires user maintain its own tap. I won't cover it here, just search it if you're interested. | In case `brew switch` produces an error (in this example trying to switch to node version 14):
```
> brew switch node 14
Error: Calling `brew switch` is disabled! Use `brew link` @-versioned formulae instead.
```
The correct way switching versions would be :
```
> brew link --overwrite node@14
``` |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | Sadly `brew switch` is deprecated in [Homebrew 2.6.0](https://brew.sh/2020/12/01/homebrew-2.6.0/) (December 2020)
```
$ brew switch
Error: Unknown command: switch
```
TLDR, to switch to `package` version `10`:
```sh
brew unlink package
brew link package@10
```
---
To use another version of a package, for example `node`:
* First, ensure that the specific version is installed using `brew list`. My package here is `node` (16) and `node@14`.
```
➜ ~ brew list
==> Formulae
node
node@14
➜ ~ node -v
v16.1.0
```
* Unlink the current package: `brew unlink node`.
```
➜ ~ brew unlink node
Unlinking /usr/local/Cellar/node/16.1.0... 7 symlinks removed.
```
* Link the correct version
```
➜ ~ brew link node@14
Linking /usr/local/Cellar/node@14/14.16.1_1... 3857 symlinks created.
If you need to have this software first in your PATH instead consider running:
echo 'export PATH="/usr/local/opt/node@14/bin:$PATH"' >> ~/.zshrc
➜ ~ node -v
v14.16.1
``` | if @simon's answer is not working in some of the mac's please follow the below process.
If you have already installed swiftgen using the following commands:
$ `brew update`
$ `brew install swiftgen`
then follow the steps below in order to run swiftgen with older version.
Step 1: `brew uninstall swiftgen`
Step 2: Navigate to: <https://github.com/SwiftGen/SwiftGen/releases>
and download the swiftgen with version: swiftgen-4.2.0.zip.
Unzip the package in any of the directories.
Step 3:
Execute the following in a terminal:
```
$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/
$ swiftgen --version
```
You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)
[](https://i.stack.imgur.com/YKnK2.png) |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | Homebrew removed `brew switch` subcommand in [Homebrew 2.6.0](https://brew.sh/2020/12/01/homebrew-2.6.0/). Get it back from [here](https://github.com/laggardkernel/homebrew-tap#external-commands).
```sh
brew tap laggardkernel/tap
brew switch --help
```
---
### name@version formula
There's mainly two ways to switch to an old version of an app.
If it's a bigger version change. Homebrew may have created a versioned package in the repo. Like `go`, `[email protected]`, they are two different formulae, installed into two different locations.
```sh
# install the old one
brew install [email protected]
# link the executable into /usr/local/bin, or /opt/homebrew/bin
brew link --overwrite --force [email protected]
```
### brew switch
But not every package has a versioned variant. If you just upgraded to the new version and the old one is still in your system, skip step 1, 2.
1. In this situation, search in the [homebrew-core](https://github.com/Homebrew/homebrew-core/) repo and download the specific formula. e.g. [mysql 8.0.23](https://github.com/Homebrew/homebrew-core/blob/58946207e43b0e7222f6c920ef4b053e52baf76d/Formula/mysql.rb)
2. Download the **raw** file, and install from it `brew install /path/to/downloaded/mysql.rb`.
3. Now both the latest and the old 8.0.23 (same formula `mysql`) exist, switch (link out) the old version with `brew switch mysql 8.0.23`
`brew info mysql` will list all the old version still exist.
Step 1, 2 could be replaced by `brew extract`, but that requires user maintain its own tap. I won't cover it here, just search it if you're interested. | `brew switch libfoo mycopy`
You can use `brew switch` to switch between versions of the same package, if it's installed as versioned subdirectories under `Cellar/<packagename>/`
This will list versions installed ( for example I had `Cellar/sdl2/2.0.3`, I've compiled into `Cellar/sdl2/2.0.4`)
```
brew info sdl2
```
Then to switch between them
```
brew switch sdl2 2.0.4
brew info
```
Info now shows `*` next to the 2.0.4
To install under `Cellar/<packagename>/<version>` from source you can do for example
```
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
```
check where it gets installed with
```
make install -n
```
if all looks correct
```
make install
```
Then from `cd $(brew --Cellar)` do the switch between version.
I'm using `brew version 0.9.5` |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | **[This is probably the best way as of 11.1.2022](https://stackoverflow.com/a/9832084/1574376):**
To install a specific version, e.g. postgresql 9.5 you simply run:
```
$ brew install [email protected]
```
To list the available versions run a search with @:
```
$ brew search postgresql@
==> Formulae
postgresql postgresql@11 postgresql@13 [email protected] qt-postgresql
postgresql@10 postgresql@12 [email protected] [email protected] postgrest
==> Casks
navicat-for-postgresql
```
---
**DEPRECATED in Homebrew 2.6.0 (December 2020):**
The usage info:
```
Usage: brew switch <formula> <version>
```
Example:
```
brew switch mysql 5.5.29
```
You can find the versions installed on your system with `info`.
```
brew info mysql
```
And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:
```
brew switch mysql 0
```
---
**Update (15.10.2014):**
The `brew versions` command has been removed from brew, but, if you do wish to use this command first run `brew tap homebrew/boneyard`.
The recommended way to install an old version is to install from the `homebrew/versions` repo as follows:
```
$ brew tap homebrew/versions
$ brew install mysql55
```
---
For detailed info on all the ways to install an older version of a formula read [this answer](https://stackoverflow.com/a/4158763/1574376). | In case `brew switch` produces an error (in this example trying to switch to node version 14):
```
> brew switch node 14
Error: Calling `brew switch` is disabled! Use `brew link` @-versioned formulae instead.
```
The correct way switching versions would be :
```
> brew link --overwrite node@14
``` |
13,477,363 | I have a few kegs of the same package in `/usr/local/Cellar/libfoo` like `/usr/local/Cellar/libfoo/1.0.1`, `/usr/local/Cellar/libfoo/HEAD` and `/usr/local/Cellar/libfoo/mycopy`
How can I brew link to a specific version? | 2012/11/20 | [
"https://Stackoverflow.com/questions/13477363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16998/"
] | `brew switch libfoo mycopy`
You can use `brew switch` to switch between versions of the same package, if it's installed as versioned subdirectories under `Cellar/<packagename>/`
This will list versions installed ( for example I had `Cellar/sdl2/2.0.3`, I've compiled into `Cellar/sdl2/2.0.4`)
```
brew info sdl2
```
Then to switch between them
```
brew switch sdl2 2.0.4
brew info
```
Info now shows `*` next to the 2.0.4
To install under `Cellar/<packagename>/<version>` from source you can do for example
```
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
```
check where it gets installed with
```
make install -n
```
if all looks correct
```
make install
```
Then from `cd $(brew --Cellar)` do the switch between version.
I'm using `brew version 0.9.5` | if @simon's answer is not working in some of the mac's please follow the below process.
If you have already installed swiftgen using the following commands:
$ `brew update`
$ `brew install swiftgen`
then follow the steps below in order to run swiftgen with older version.
Step 1: `brew uninstall swiftgen`
Step 2: Navigate to: <https://github.com/SwiftGen/SwiftGen/releases>
and download the swiftgen with version: swiftgen-4.2.0.zip.
Unzip the package in any of the directories.
Step 3:
Execute the following in a terminal:
```
$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/
$ swiftgen --version
```
You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)
[](https://i.stack.imgur.com/YKnK2.png) |
1,113,332 | In my lecture notes we have the following:
We have that $f(x, y), g(x, y) \in \mathbb{C}[x, y]$
$$f(x,y)=a\_0(y)+a\_1(y)x+ \dots +a\_n(y)x^n \\ g(x, y)=b\_0(y)+b\_1(y)x+ \dots +b\_m(y)x^m$$
The resultant is defined in the following way:
$$Res(f,g)(y)=det\begin{bmatrix}
a\_0(y) & a\_1(y) & \dots & a\_n(y) & 0 & 0 & \dots & 0 \\
0 & a\_0(y) & \dots & a\_{n-1}(y) & a\_n(y) & 0 & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\
0 & 0 & a\_0(y) & \dots & \dots & \dots & \dots & a\_n(y) \\
b\_0(y) & b\_1(y) & b\_2(y) & \dots & b\_m(y) & 0 & \dots & 0 \\
0 & b\_0(y) & b\_1(y) & \dots & b\_m(y) & \dots & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & b\_0(y) & \dots & \dots & \dots & b\_m(y)
\end{bmatrix}$$
I haven't understood how the resultant is defined.
For example when we have $f(x, y)=y^2+x^2$ and $g(x, y)=y+x$, we have that $a\_0(y)=y^2, a\_1(y)=0, a\_2(y)=1, b\_0(y)=y, b\_1(y)=1$.
How do we create the matrix? | 2015/01/21 | [
"https://math.stackexchange.com/questions/1113332",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | In your case the matrix is given by:
$$\begin{pmatrix}y^2 & 0 & 1 \\
y & 1 & 0 \\
0 & y & 1
\end{pmatrix} $$
In general, note that you have $m$ lines of $a$'s and $n$ lines of $b$'s and most importantly that the final result need to be and $(n+m) \times (n+m)$ matrix. Put differently, to the first line of $a$'s pad $m-1$ entries of $0$, and to the first line of $b$' pad $n-1$.
This matrix is called ["Sylvester matrix"](http://en.wikipedia.org/wiki/Sylvester_matrix) which should lead you to further examples. | The resultant is
$$\begin{bmatrix}
y^2 & 0 & 1\\
y & 1 & 0\\
0 & y & 1
\end{bmatrix}$$
Since we need $m=1$ row of coefficients of $f$ and $n=2$ rows of coefficients of $g$. |
23,538,025 | I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
...but it throws an error:
```
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */
```
in Heidi SQL. I am using MySQL database.
When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23538025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583647/"
] | I just ran your query:
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
and got the same error. I then ran:
```
ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT
```
and it worked. Pretty sure you need to change " to `
Fail with double qoutes:

Success with backticks:
 | use backticks for columnname
change
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
TO
```
ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT
```
[SQL FIDDLE](http://sqlfiddle.com/#!2/d248b/1)
============================================== |
23,538,025 | I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
...but it throws an error:
```
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */
```
in Heidi SQL. I am using MySQL database.
When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23538025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583647/"
] | I just ran your query:
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
and got the same error. I then ran:
```
ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT
```
and it worked. Pretty sure you need to change " to `
Fail with double qoutes:

Success with backticks:
 | i dont really know what you are trying to achive here pal.
instead of:
```
00:18:e7:f9:65:a6
```
to
```
00_18_e7_f9_65_a6
```
then adjust your code to replace ":" to "\_" in php or mysql.
**in sql:**
```
Replace(table_name, ':', '_');
```
**in PHP:**
```
srt_replace(':','_',$query);
``` |
23,538,025 | I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
...but it throws an error:
```
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */
```
in Heidi SQL. I am using MySQL database.
When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23538025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583647/"
] | I just ran your query:
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
and got the same error. I then ran:
```
ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT
```
and it worked. Pretty sure you need to change " to `
Fail with double qoutes:

Success with backticks:
 | To add something to the story, when querying multiple tables, you have to use following expression:
```
`tablename`.`columnname`
```
(NOT `tablename.columnname` )
I took me some time to figure it out, so I hope it helps someone :)
Example:
```
SELECT *
FROM tb_product p
JOIN tb_brand b ON ( `p`.`tb_brand:IDbrand` = `b`.`IDbrand` )
WHERE IDfamily = 2
``` |
23,538,025 | I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
...but it throws an error:
```
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */
```
in Heidi SQL. I am using MySQL database.
When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23538025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583647/"
] | use backticks for columnname
change
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
TO
```
ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT
```
[SQL FIDDLE](http://sqlfiddle.com/#!2/d248b/1)
============================================== | i dont really know what you are trying to achive here pal.
instead of:
```
00:18:e7:f9:65:a6
```
to
```
00_18_e7_f9_65_a6
```
then adjust your code to replace ":" to "\_" in php or mysql.
**in sql:**
```
Replace(table_name, ':', '_');
```
**in PHP:**
```
srt_replace(':','_',$query);
``` |
23,538,025 | I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
...but it throws an error:
```
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */
```
in Heidi SQL. I am using MySQL database.
When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23538025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583647/"
] | use backticks for columnname
change
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
TO
```
ALTER IGNORE TABLE tblwifi_information ADD `00:18:e7:f9:65:a6` INT
```
[SQL FIDDLE](http://sqlfiddle.com/#!2/d248b/1)
============================================== | To add something to the story, when querying multiple tables, you have to use following expression:
```
`tablename`.`columnname`
```
(NOT `tablename.columnname` )
I took me some time to figure it out, so I hope it helps someone :)
Example:
```
SELECT *
FROM tb_product p
JOIN tb_brand b ON ( `p`.`tb_brand:IDbrand` = `b`.`IDbrand` )
WHERE IDfamily = 2
``` |
23,538,025 | I am trying to insert a column with column name 00:18:e7:f9:65:a6 with the statement
```
ALTER IGNORE TABLE tblwifi_information ADD "00:18:e7:f9:65:a6" INT
```
...but it throws an error:
```
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"00:18:e7:f9:65:a6" INT' at line 1 */
```
in Heidi SQL. I am using MySQL database.
When I try to add the column manually b going to the structure of the table it works and does not give any error but when I run this statement it does not allow me. How can I solve this? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23538025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583647/"
] | To add something to the story, when querying multiple tables, you have to use following expression:
```
`tablename`.`columnname`
```
(NOT `tablename.columnname` )
I took me some time to figure it out, so I hope it helps someone :)
Example:
```
SELECT *
FROM tb_product p
JOIN tb_brand b ON ( `p`.`tb_brand:IDbrand` = `b`.`IDbrand` )
WHERE IDfamily = 2
``` | i dont really know what you are trying to achive here pal.
instead of:
```
00:18:e7:f9:65:a6
```
to
```
00_18_e7_f9_65_a6
```
then adjust your code to replace ":" to "\_" in php or mysql.
**in sql:**
```
Replace(table_name, ':', '_');
```
**in PHP:**
```
srt_replace(':','_',$query);
``` |
21,029,709 | I am aware of the image resizing technic of changing image proportions based on width:
```
img{
max-width: 100%;
height: auto;
}
```
I need to do the same thing only based on the height of the parent, not the width. I have tried the following with no effect:
```
img{
width: auto;
max-height: 100%;
}
```
I hope I explaining this well enough.
Please help :) | 2014/01/09 | [
"https://Stackoverflow.com/questions/21029709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857030/"
] | `max-height` will only restrict the height to be less than the given value.
If you want it to be the same as its parent.. give it as `height: 100%`
hence this should work:
CSS:
```
img{
height: 100%; // changed max-height to height here
width: auto; // this is optional
}
``` | You cannot effectively base it on the height using standard css techniques, but you can make the `height` relate directly to the `width` of the image for a more flexible layout. Try this:
```
img {
position: relative;
width: 50%; /* desired width */
}
img:before{
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
``` |
21,029,709 | I am aware of the image resizing technic of changing image proportions based on width:
```
img{
max-width: 100%;
height: auto;
}
```
I need to do the same thing only based on the height of the parent, not the width. I have tried the following with no effect:
```
img{
width: auto;
max-height: 100%;
}
```
I hope I explaining this well enough.
Please help :) | 2014/01/09 | [
"https://Stackoverflow.com/questions/21029709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857030/"
] | `max-height` will only restrict the height to be less than the given value.
If you want it to be the same as its parent.. give it as `height: 100%`
hence this should work:
CSS:
```
img{
height: 100%; // changed max-height to height here
width: auto; // this is optional
}
``` | i have tried this and it worked .
```
<div class="parent">
<img src="http://searchengineland.com/figz/wp-content/seloads/2014/07/google-logo-sign-1920-600x337.jpg" alt="..." />
</div>
.parent {
width: 100%;
height: 180px;
overflow: hidden;
}
```
see it here
<https://jsfiddle.net/shuhad/vaduvrno/> |
21,029,709 | I am aware of the image resizing technic of changing image proportions based on width:
```
img{
max-width: 100%;
height: auto;
}
```
I need to do the same thing only based on the height of the parent, not the width. I have tried the following with no effect:
```
img{
width: auto;
max-height: 100%;
}
```
I hope I explaining this well enough.
Please help :) | 2014/01/09 | [
"https://Stackoverflow.com/questions/21029709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857030/"
] | You cannot effectively base it on the height using standard css techniques, but you can make the `height` relate directly to the `width` of the image for a more flexible layout. Try this:
```
img {
position: relative;
width: 50%; /* desired width */
}
img:before{
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
``` | i have tried this and it worked .
```
<div class="parent">
<img src="http://searchengineland.com/figz/wp-content/seloads/2014/07/google-logo-sign-1920-600x337.jpg" alt="..." />
</div>
.parent {
width: 100%;
height: 180px;
overflow: hidden;
}
```
see it here
<https://jsfiddle.net/shuhad/vaduvrno/> |
53,203,970 | The following code can be fixed easily, but quite annoying.
```cpp
#include <functional>
#include <boost/bind.hpp>
void foo() {
using namespace std::placeholders;
std::bind(_1, _2, _3); // ambiguous
}
```
There's a macro `BOOST_BIND_NO_PLACEHOLDERS`, but using this macro will also bring some drawbacks like causing `boost::placeholders` disappear from the compile unit included `<boost/bind.hpp>` but not included `<boost/bind/placeholders.hpp>`.
The name conflicts also comes with other libs like `boost::mpl`, I don't think the maintainers don't know the problem, but I want to know why they insist on not deprecating and deleting `using namespace boost::placeholders` in `<boost/bind.hpp>`. | 2018/11/08 | [
"https://Stackoverflow.com/questions/53203970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2709407/"
] | Looks like it has been fixed in newer versions of boost.
When including `boost/bind.hpp` we get this message:
`#pragma message: The practice of declaring the Bind placeholders (_1, _2, ...) in the global namespace is deprecated. Please use <boost/bind/bind.hpp> + using namespace boost::placeholders, or define BOOST_BIND_GLOBAL_PLACEHOLDERS to retain the current behavior.`
The solution is described in <https://www.boost.org/doc/libs/1_73_0/boost/bind.hpp>
So the "good practice" fix is to instead of
`#include <boost/bind.hpp>`
which puts the boost::placeholders in global namespace
do
`#include <boost/bind/bind.hpp>`
which does not put the boost:: placeholders in global namespace.
Then use the qualified names like `boost::placeholders::_1` directly, or locally do `using namespace boost::placeholders` | You can use
```
#define BOOST_BIND_NO_PLACEHOLDERS
```
before including other Boost headers.
I don't know when this was introduced, only that it works in 1.67. Feel free to edit with more accurate information. |
53,203,970 | The following code can be fixed easily, but quite annoying.
```cpp
#include <functional>
#include <boost/bind.hpp>
void foo() {
using namespace std::placeholders;
std::bind(_1, _2, _3); // ambiguous
}
```
There's a macro `BOOST_BIND_NO_PLACEHOLDERS`, but using this macro will also bring some drawbacks like causing `boost::placeholders` disappear from the compile unit included `<boost/bind.hpp>` but not included `<boost/bind/placeholders.hpp>`.
The name conflicts also comes with other libs like `boost::mpl`, I don't think the maintainers don't know the problem, but I want to know why they insist on not deprecating and deleting `using namespace boost::placeholders` in `<boost/bind.hpp>`. | 2018/11/08 | [
"https://Stackoverflow.com/questions/53203970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2709407/"
] | You can use
```
#define BOOST_BIND_NO_PLACEHOLDERS
```
before including other Boost headers.
I don't know when this was introduced, only that it works in 1.67. Feel free to edit with more accurate information. | Either add:
```
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
```
before you import boost headers.
Or just add to your CMakeLists:
```
add_definitions(-DBOOST_BIND_GLOBAL_PLACEHOLDERS)
```
when you configure Boost. |
53,203,970 | The following code can be fixed easily, but quite annoying.
```cpp
#include <functional>
#include <boost/bind.hpp>
void foo() {
using namespace std::placeholders;
std::bind(_1, _2, _3); // ambiguous
}
```
There's a macro `BOOST_BIND_NO_PLACEHOLDERS`, but using this macro will also bring some drawbacks like causing `boost::placeholders` disappear from the compile unit included `<boost/bind.hpp>` but not included `<boost/bind/placeholders.hpp>`.
The name conflicts also comes with other libs like `boost::mpl`, I don't think the maintainers don't know the problem, but I want to know why they insist on not deprecating and deleting `using namespace boost::placeholders` in `<boost/bind.hpp>`. | 2018/11/08 | [
"https://Stackoverflow.com/questions/53203970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2709407/"
] | Looks like it has been fixed in newer versions of boost.
When including `boost/bind.hpp` we get this message:
`#pragma message: The practice of declaring the Bind placeholders (_1, _2, ...) in the global namespace is deprecated. Please use <boost/bind/bind.hpp> + using namespace boost::placeholders, or define BOOST_BIND_GLOBAL_PLACEHOLDERS to retain the current behavior.`
The solution is described in <https://www.boost.org/doc/libs/1_73_0/boost/bind.hpp>
So the "good practice" fix is to instead of
`#include <boost/bind.hpp>`
which puts the boost::placeholders in global namespace
do
`#include <boost/bind/bind.hpp>`
which does not put the boost:: placeholders in global namespace.
Then use the qualified names like `boost::placeholders::_1` directly, or locally do `using namespace boost::placeholders` | Either add:
```
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
```
before you import boost headers.
Or just add to your CMakeLists:
```
add_definitions(-DBOOST_BIND_GLOBAL_PLACEHOLDERS)
```
when you configure Boost. |
237,698 | I'm trying to understand the Bayes Classifier. I don't really understand its purpose or how to apply it, but I think I understand the parts of the formula:
$$P(Y = j \mid X = x\_{0})$$
If I'm correct, it's asking for the largest probability, depending on one of two conditions. If $Y$ is equal to some class $j$, or if $X$ is some data point $x\_{0}$.
How would I compute this with a data set $(x, y)$ where $x$ is just a number between 1 and 100, and $y$ is one of two classes ("blue" or "orange"), e.g. (5, "blue"), (51, "orange")? Does this data set even work to apply the classifier or should I consider making a new data set?
Sorry if it's a silly question, I'm out of touch with my statistics. Some pseudocode would be terrific, but I'll be applying this in R. I'm not interested in the R function to complete this. Some regular guidance with good ol' math would be great as well.
Thank you for any help! | 2016/09/30 | [
"https://stats.stackexchange.com/questions/237698",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/132937/"
] | The Bayes classifier is the one that classifies according to the most likely category given the predictor $x$, i.e.,
$$
\text{arg max}\_j P(Y = j \mid X = x) .
$$
Since these "true" probabilities are essentially never known, the Bayes classifier is more a theoretical concept and not something that you can actually use in practice. However, it's a helpful idea when doing simulation studies where you generate the data yourself and therefore know the probabilities. This allows you to compare a given classification rule to the Bayes classifier which has the lowest error rate among all classifiers. | Interpret the formula as follows: What is the probability of Y being equal to j, when we know X = x0. So in your dataset, the bayes classifier is effectively computing probabilities of achieving blue or orange when you define the value of x. If in your data, when x is greater than 75, if 90% of the balls are orange, then the classifier will choose orange whenever this happens.
This is a very "non-technical" explanation and I hope it helps you understand the basic idea.
So when someone chooses to use a Bayes classifier (or any other classifier for that matter) you use it to predict categorical outcomes based on one or more input variables that may be continuous or categorical. |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for `$logged`.
It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User `id` or some other unique information in the Cookie as well.
You may also want to keep a timestamp of when the `$logged` was put in the DB, so that you can run cleaning queries where they are older than `x` days/weeks. | The first step is a bit overkill, as this is what `$_SESSION['foo']` basically does client-side for the lifetime of the session. I'd just store a salted and hashed password for each user to begin with, salting with the date or other pseudo-random factors.
Setting the cookie might prove useless if the user clears their cookies, or the session expires. This will leave the user logged in (according to your database) when in reality they're not.
I'd stick to just `$_SESSION['foo']` and cookies and leave the database out of the login process. |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | The first step is a bit overkill, as this is what `$_SESSION['foo']` basically does client-side for the lifetime of the session. I'd just store a salted and hashed password for each user to begin with, salting with the date or other pseudo-random factors.
Setting the cookie might prove useless if the user clears their cookies, or the session expires. This will leave the user logged in (according to your database) when in reality they're not.
I'd stick to just `$_SESSION['foo']` and cookies and leave the database out of the login process. | In first point you have mentioned It create random SALT string when user logged in and clear it when user log out.
1. Main problem is you have to check SALT string is exist or not in each redirection of page. So it create heavy traffic in Database server.
2. Yes this is very useful for checkout user already logged in or not.
3. But in case of power failure in client machine after log in when Salt string remain in database after long time.
In second point to user authentication in cookie it is not secure. Client can easily show authentication cookie in browser
In third point to store authentication in session it means create session variable on server side and store it in file on server side. It is very secure then store it in cookie.
The best way to authentication is combine point number 1 and 3 which you mention.
1. You can check user already logged in form other pc or not?
2. You can easily clear SALT string if session is not exist.
3. You can easily manage Login in case of pc power failure |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | The first step is a bit overkill, as this is what `$_SESSION['foo']` basically does client-side for the lifetime of the session. I'd just store a salted and hashed password for each user to begin with, salting with the date or other pseudo-random factors.
Setting the cookie might prove useless if the user clears their cookies, or the session expires. This will leave the user logged in (according to your database) when in reality they're not.
I'd stick to just `$_SESSION['foo']` and cookies and leave the database out of the login process. | One problem I can see - your solution sounds annoying for people who load your site in multiple browsers at the same time. |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for `$logged`.
It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User `id` or some other unique information in the Cookie as well.
You may also want to keep a timestamp of when the `$logged` was put in the DB, so that you can run cleaning queries where they are older than `x` days/weeks. | In first point you have mentioned It create random SALT string when user logged in and clear it when user log out.
1. Main problem is you have to check SALT string is exist or not in each redirection of page. So it create heavy traffic in Database server.
2. Yes this is very useful for checkout user already logged in or not.
3. But in case of power failure in client machine after log in when Salt string remain in database after long time.
In second point to user authentication in cookie it is not secure. Client can easily show authentication cookie in browser
In third point to store authentication in session it means create session variable on server side and store it in file on server side. It is very secure then store it in cookie.
The best way to authentication is combine point number 1 and 3 which you mention.
1. You can check user already logged in form other pc or not?
2. You can easily clear SALT string if session is not exist.
3. You can easily manage Login in case of pc power failure |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for `$logged`.
It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User `id` or some other unique information in the Cookie as well.
You may also want to keep a timestamp of when the `$logged` was put in the DB, so that you can run cleaning queries where they are older than `x` days/weeks. | First No need of doing
```
Store $logged into a cookie (If user checked "remember me")
```
Starting the session should be the first thing you should do place `session_start()` on top of your index.php (file which gets executed) . This way a cookie name "phpsessid" gets created on user browser by default independent of weather user is logged in or not . value of this cookie is unique by which you can identify the user after he logs in. So you dont need to create any other cookie for this purpose. |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for `$logged`.
It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User `id` or some other unique information in the Cookie as well.
You may also want to keep a timestamp of when the `$logged` was put in the DB, so that you can run cleaning queries where they are older than `x` days/weeks. | One problem I can see - your solution sounds annoying for people who load your site in multiple browsers at the same time. |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | First No need of doing
```
Store $logged into a cookie (If user checked "remember me")
```
Starting the session should be the first thing you should do place `session_start()` on top of your index.php (file which gets executed) . This way a cookie name "phpsessid" gets created on user browser by default independent of weather user is logged in or not . value of this cookie is unique by which you can identify the user after he logs in. So you dont need to create any other cookie for this purpose. | In first point you have mentioned It create random SALT string when user logged in and clear it when user log out.
1. Main problem is you have to check SALT string is exist or not in each redirection of page. So it create heavy traffic in Database server.
2. Yes this is very useful for checkout user already logged in or not.
3. But in case of power failure in client machine after log in when Salt string remain in database after long time.
In second point to user authentication in cookie it is not secure. Client can easily show authentication cookie in browser
In third point to store authentication in session it means create session variable on server side and store it in file on server side. It is very secure then store it in cookie.
The best way to authentication is combine point number 1 and 3 which you mention.
1. You can check user already logged in form other pc or not?
2. You can easily clear SALT string if session is not exist.
3. You can easily manage Login in case of pc power failure |
5,294,957 | What is the best way to securely authenticate a user ?
So far I was thinking of:
* Generate a random `$SALT` for each successful login and store `$logged = md5($hashed_password.$SALT)` into database; delete on logout.
* Store `$logged` into a cookie (If user checked "remember me"). Set `$_SESSION['user'] = $logged;`
* On a visit: Check if `$_SESSION['user']` is set; if not, check for cookie, if data doesn't match, redirect to `login` page.
What are the risks ? | 2011/03/14 | [
"https://Stackoverflow.com/questions/5294957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348358/"
] | First No need of doing
```
Store $logged into a cookie (If user checked "remember me")
```
Starting the session should be the first thing you should do place `session_start()` on top of your index.php (file which gets executed) . This way a cookie name "phpsessid" gets created on user browser by default independent of weather user is logged in or not . value of this cookie is unique by which you can identify the user after he logs in. So you dont need to create any other cookie for this purpose. | One problem I can see - your solution sounds annoying for people who load your site in multiple browsers at the same time. |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You should look at [`getchar()`](https://linux.die.net/man/3/getchar)
```
#include <stdio.h>
int main()
{
int c1;
while ((c1=getchar())!=EOF && c1!='*'){
printf("c1: %c \n", c1);
}
return 0;
}
```
EDIT: and this way, there is no undefined behavior, because `c1` is always initialized (see @Blaze answer) :) | You could switch the `scanf` and `printf` statements and put an initial `scanf` before the loop:
```
int main()
{
char c1 = '\0';
do {
printf("c1: %c \n", c1);
if (scanf(" %c", &c1) != 1)
return -1;
} while (c1 != '*');
return 0;
}
```
Also note that as your program currently is, there's not just the issue with printing the `*`, but it's undefined behavior because `c1` is uninitialized in the first run of `c1 != '*'`. |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You could switch the `scanf` and `printf` statements and put an initial `scanf` before the loop:
```
int main()
{
char c1 = '\0';
do {
printf("c1: %c \n", c1);
if (scanf(" %c", &c1) != 1)
return -1;
} while (c1 != '*');
return 0;
}
```
Also note that as your program currently is, there's not just the issue with printing the `*`, but it's undefined behavior because `c1` is uninitialized in the first run of `c1 != '*'`. | Using `scanf()` *and* doing complete error checking and logging:
```
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
{
int r;
{
char c1 = 0;
while (EOF != (r = fscanf(stdin, " %c", &c1)) && c1 != '*')
{
if (1 != r)
{
fputs("Invalid input. Retrying ...", stderr);
}
else
{
printf("c1: %c \n", c1);
}
}
}
{
int errno_save = errno;
if ((EOF == r) && ferror(stdin))
{
errno = errno_save;
perror("scanf() failed");
result = EXIT_FAILURE;
}
}
}
return result;
}
``` |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You could switch the `scanf` and `printf` statements and put an initial `scanf` before the loop:
```
int main()
{
char c1 = '\0';
do {
printf("c1: %c \n", c1);
if (scanf(" %c", &c1) != 1)
return -1;
} while (c1 != '*');
return 0;
}
```
Also note that as your program currently is, there's not just the issue with printing the `*`, but it's undefined behavior because `c1` is uninitialized in the first run of `c1 != '*'`. | Use while or for when you want to check the condition at the start of the loop, do ... until if you want to check at the end. If you want to check in the middle, I prefer an infinite loop ("while(TRUE)" or "for(;;)") and using if/break in the middle. Taking your loop, that would be:
```
while (TRUE){
scanf("%c", &c1);
if (c1=='*') {
break;
}
printf("c1: %c \n", c1);
}
```
Some people don't like that, an alternative is to make that a function, using return instead of break:
```
boolean get_and_print_if_not_end() {
scanf("%c", &c1);
if (c1=='*') {
return true;
}
printf("c1: %c \n", c1);
return false;
}
```
You'd call that in a basic while loop:
```
while (!get_and_print_if_not_end()) {
// Nothing to do here.
}
``` |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You could switch the `scanf` and `printf` statements and put an initial `scanf` before the loop:
```
int main()
{
char c1 = '\0';
do {
printf("c1: %c \n", c1);
if (scanf(" %c", &c1) != 1)
return -1;
} while (c1 != '*');
return 0;
}
```
Also note that as your program currently is, there's not just the issue with printing the `*`, but it's undefined behavior because `c1` is uninitialized in the first run of `c1 != '*'`. | ```
#include<stdio.h>
#include<ctype.h>
int main()
{
char string;
do
{
printf("String is :%c\n",string);
if(scanf("%c",&string)!=1)
{
return 0;
}
}while(string!='*');
return 0
}
```
Here:
---
First, it will get the string character and compare it to \* character if the character is no found it will print the character. else it finds it will return 0 and the program will be eliminated.
--- |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You should look at [`getchar()`](https://linux.die.net/man/3/getchar)
```
#include <stdio.h>
int main()
{
int c1;
while ((c1=getchar())!=EOF && c1!='*'){
printf("c1: %c \n", c1);
}
return 0;
}
```
EDIT: and this way, there is no undefined behavior, because `c1` is always initialized (see @Blaze answer) :) | Using `scanf()` *and* doing complete error checking and logging:
```
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
{
int r;
{
char c1 = 0;
while (EOF != (r = fscanf(stdin, " %c", &c1)) && c1 != '*')
{
if (1 != r)
{
fputs("Invalid input. Retrying ...", stderr);
}
else
{
printf("c1: %c \n", c1);
}
}
}
{
int errno_save = errno;
if ((EOF == r) && ferror(stdin))
{
errno = errno_save;
perror("scanf() failed");
result = EXIT_FAILURE;
}
}
}
return result;
}
``` |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You should look at [`getchar()`](https://linux.die.net/man/3/getchar)
```
#include <stdio.h>
int main()
{
int c1;
while ((c1=getchar())!=EOF && c1!='*'){
printf("c1: %c \n", c1);
}
return 0;
}
```
EDIT: and this way, there is no undefined behavior, because `c1` is always initialized (see @Blaze answer) :) | Use while or for when you want to check the condition at the start of the loop, do ... until if you want to check at the end. If you want to check in the middle, I prefer an infinite loop ("while(TRUE)" or "for(;;)") and using if/break in the middle. Taking your loop, that would be:
```
while (TRUE){
scanf("%c", &c1);
if (c1=='*') {
break;
}
printf("c1: %c \n", c1);
}
```
Some people don't like that, an alternative is to make that a function, using return instead of break:
```
boolean get_and_print_if_not_end() {
scanf("%c", &c1);
if (c1=='*') {
return true;
}
printf("c1: %c \n", c1);
return false;
}
```
You'd call that in a basic while loop:
```
while (!get_and_print_if_not_end()) {
// Nothing to do here.
}
``` |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | You should look at [`getchar()`](https://linux.die.net/man/3/getchar)
```
#include <stdio.h>
int main()
{
int c1;
while ((c1=getchar())!=EOF && c1!='*'){
printf("c1: %c \n", c1);
}
return 0;
}
```
EDIT: and this way, there is no undefined behavior, because `c1` is always initialized (see @Blaze answer) :) | ```
#include<stdio.h>
#include<ctype.h>
int main()
{
char string;
do
{
printf("String is :%c\n",string);
if(scanf("%c",&string)!=1)
{
return 0;
}
}while(string!='*');
return 0
}
```
Here:
---
First, it will get the string character and compare it to \* character if the character is no found it will print the character. else it finds it will return 0 and the program will be eliminated.
--- |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | Using `scanf()` *and* doing complete error checking and logging:
```
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
{
int r;
{
char c1 = 0;
while (EOF != (r = fscanf(stdin, " %c", &c1)) && c1 != '*')
{
if (1 != r)
{
fputs("Invalid input. Retrying ...", stderr);
}
else
{
printf("c1: %c \n", c1);
}
}
}
{
int errno_save = errno;
if ((EOF == r) && ferror(stdin))
{
errno = errno_save;
perror("scanf() failed");
result = EXIT_FAILURE;
}
}
}
return result;
}
``` | Use while or for when you want to check the condition at the start of the loop, do ... until if you want to check at the end. If you want to check in the middle, I prefer an infinite loop ("while(TRUE)" or "for(;;)") and using if/break in the middle. Taking your loop, that would be:
```
while (TRUE){
scanf("%c", &c1);
if (c1=='*') {
break;
}
printf("c1: %c \n", c1);
}
```
Some people don't like that, an alternative is to make that a function, using return instead of break:
```
boolean get_and_print_if_not_end() {
scanf("%c", &c1);
if (c1=='*') {
return true;
}
printf("c1: %c \n", c1);
return false;
}
```
You'd call that in a basic while loop:
```
while (!get_and_print_if_not_end()) {
// Nothing to do here.
}
``` |
58,646,186 | I have a problem where I'm having two arrays. Whenever I'm changing a value in one array with the code shown below, the other array do also get the same change which is not intended. If i copy and paste the code below in the javascript console in my browser I get the problem that originalArray is changed after I called ConvertDataArrayToLocationArray(dataArray)
```js
let originalArray = [
{
"date": "2018-11-16",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-16",
"type": "Food",
"location": "Oslo",
"amount": 170
},
{
"date": "2018-11-17",
"type": "Food",
"location": "Fredrikstad",
"amount": 99
},
{
"date": "2018-11-18",
"type": "Food",
"location": "Halden",
"amount": 29
},
{
"date": "2018-11-19",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-11-20",
"type": "Entertainment",
"location": "Oslo",
"amount": 15
},
{
"date": "2018-11-20",
"type": "Food",
"location": "Fredrikstad",
"amount": 80
},
{
"date": "2018-11-23",
"type": "Transportation",
"location": "Stavanger",
"amount": 95
},
{
"date": "2018-11-28",
"type": "Entertainment",
"location": "Oslo",
"amount": 1024
},
{
"date": "2018-11-29",
"type": "Food",
"location": "Oslo",
"amount": 117.39
},
{
"date": "2018-11-30",
"type": "Transportation",
"location": "Fredrikstad",
"amount": 29
},
{
"date": "2018-12-2",
"type": "Transportation",
"location": "Stavanger",
"amount": 184
},
{
"date": "2018-12-3",
"type": "Entertainment",
"location": "Oslo",
"amount": 34
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Oslo",
"amount": 162
},
{
"date": "2018-12-4",
"type": "Food",
"location": "Fredrikstad",
"amount": 231
}
];
function ConvertDataArrayToLocationArray(dataArray) {
let newArray = [];
console.log("First dataArray[0].amount is the correct value. ");
console.log(dataArray[0].amount);
for(let i = 0; i < dataArray.length; i++) {
let existed = false;
for(let j = 0; j < newArray.length; j++) {
if(dataArray[i].location === newArray[j].location) {
newArray[j].amount = (newArray[j].amount + dataArray[i].amount);
existed = true;
}
}
if(!existed) {
newArray.push(dataArray[i]);
}
}
console.log("Why is this dataArray[0].amount suddenly different?");
console.log(dataArray[0].amount);
return newArray;
}
let a = ConvertDataArrayToLocationArray(originalArray);
```
My excepted outcome is that the variable called originalArray stays unchanged and I get a new array from the return value of ConvertDataArrayToLocationArray(dataArray). | 2019/10/31 | [
"https://Stackoverflow.com/questions/58646186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7425546/"
] | Using `scanf()` *and* doing complete error checking and logging:
```
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
{
int r;
{
char c1 = 0;
while (EOF != (r = fscanf(stdin, " %c", &c1)) && c1 != '*')
{
if (1 != r)
{
fputs("Invalid input. Retrying ...", stderr);
}
else
{
printf("c1: %c \n", c1);
}
}
}
{
int errno_save = errno;
if ((EOF == r) && ferror(stdin))
{
errno = errno_save;
perror("scanf() failed");
result = EXIT_FAILURE;
}
}
}
return result;
}
``` | ```
#include<stdio.h>
#include<ctype.h>
int main()
{
char string;
do
{
printf("String is :%c\n",string);
if(scanf("%c",&string)!=1)
{
return 0;
}
}while(string!='*');
return 0
}
```
Here:
---
First, it will get the string character and compare it to \* character if the character is no found it will print the character. else it finds it will return 0 and the program will be eliminated.
--- |
4,028,536 | What's the best way to make a select in this case, and output it without using nested queries in php? I would prefer to make it with a single query.
My tables look like this:
```
table1
id | items |
---|-------|
1 | item1 |
2 | item2 |
3 | item3 |
.. | .. |
table2
id | itemid | comment |
---|--------|----------|
1 | 1 | comment1 |
2 | 1 | comment2 |
3 | 2 | comment3 |
4 | 3 | comment4 |
5 | 3 | comment5 |
6 | 3 | comment6 |
.. | .. | .. |
```
This is the output i'm looking for.
```
item1
comment1
comment2
item2
comment3
item3
comment4
comment5
comment6
```
Thanks in advance | 2010/10/26 | [
"https://Stackoverflow.com/questions/4028536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488174/"
] | Checkout this JSON framework for Objective-C on [code.google.com](http://code.google.com/p/json-framework/) or on [Github](http://stig.github.com/json-framework/).
It is pretty straightforward to use. You instantiate your SBJSON object then call *objectWithString* with your buffer:
```
SBJSON * parser = [[SBJSON alloc] init];
NSString * buffer = @"{"name":"WFNX"}";
NSError* error = NULL;
// the type of json will depend on the JSON data in buffer, in this case, it will be
// and NSDictionary with one key/value pair "name"->"WFNX"
id json = [parser objectWithString:buffer error:&error];
``` | There are a few out there, see:
<http://code.google.com/p/json-framework/>
<http://github.com/schwa/TouchJSON>
for a big list:
<http://www.json.org/>
is a great reference site for JSON |
4,028,536 | What's the best way to make a select in this case, and output it without using nested queries in php? I would prefer to make it with a single query.
My tables look like this:
```
table1
id | items |
---|-------|
1 | item1 |
2 | item2 |
3 | item3 |
.. | .. |
table2
id | itemid | comment |
---|--------|----------|
1 | 1 | comment1 |
2 | 1 | comment2 |
3 | 2 | comment3 |
4 | 3 | comment4 |
5 | 3 | comment5 |
6 | 3 | comment6 |
.. | .. | .. |
```
This is the output i'm looking for.
```
item1
comment1
comment2
item2
comment3
item3
comment4
comment5
comment6
```
Thanks in advance | 2010/10/26 | [
"https://Stackoverflow.com/questions/4028536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488174/"
] | There are a few out there, see:
<http://code.google.com/p/json-framework/>
<http://github.com/schwa/TouchJSON>
for a big list:
<http://www.json.org/>
is a great reference site for JSON | I'm using YAJLiOS parser,not bad and compatable with ARC, here's documentation
<http://gabriel.github.com/yajl-objc/>
and parser itself on github
<https://github.com/gabriel/yajl-objc>
ex.
```
NSData *JSONData = [NSData dataWithContentsOfFile:@"someJson.json"];
NSDictionary *JSONDictionary = [tempContainer yajl_JSON];
```
and getting objects by objectForKey method or valueFoKey method if you need an array |
4,028,536 | What's the best way to make a select in this case, and output it without using nested queries in php? I would prefer to make it with a single query.
My tables look like this:
```
table1
id | items |
---|-------|
1 | item1 |
2 | item2 |
3 | item3 |
.. | .. |
table2
id | itemid | comment |
---|--------|----------|
1 | 1 | comment1 |
2 | 1 | comment2 |
3 | 2 | comment3 |
4 | 3 | comment4 |
5 | 3 | comment5 |
6 | 3 | comment6 |
.. | .. | .. |
```
This is the output i'm looking for.
```
item1
comment1
comment2
item2
comment3
item3
comment4
comment5
comment6
```
Thanks in advance | 2010/10/26 | [
"https://Stackoverflow.com/questions/4028536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488174/"
] | Checkout this JSON framework for Objective-C on [code.google.com](http://code.google.com/p/json-framework/) or on [Github](http://stig.github.com/json-framework/).
It is pretty straightforward to use. You instantiate your SBJSON object then call *objectWithString* with your buffer:
```
SBJSON * parser = [[SBJSON alloc] init];
NSString * buffer = @"{"name":"WFNX"}";
NSError* error = NULL;
// the type of json will depend on the JSON data in buffer, in this case, it will be
// and NSDictionary with one key/value pair "name"->"WFNX"
id json = [parser objectWithString:buffer error:&error];
``` | I'm using YAJLiOS parser,not bad and compatable with ARC, here's documentation
<http://gabriel.github.com/yajl-objc/>
and parser itself on github
<https://github.com/gabriel/yajl-objc>
ex.
```
NSData *JSONData = [NSData dataWithContentsOfFile:@"someJson.json"];
NSDictionary *JSONDictionary = [tempContainer yajl_JSON];
```
and getting objects by objectForKey method or valueFoKey method if you need an array |
32,353,300 | I need to search trough my data that is stored in my `UITableView`. I need one left bar button item and when the user clicked that, it should show like a search bar. How to do that?.
Thanks in advance!
**edited:**
ok based on solution you provide.Here i have done some thing with search bar (bar button item). but still i am missing some thing . And also my **filter content for search box** also , having some problem. really i don't now what to do for this?
```
#import "ViewController.h"
#import "AddNoteViewController.h"
#import <CoreData/CoreData.h>
#import "TableViewCell.h"
@interface ViewController ()
{
NSArray *searchResults;
}
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UISearchDisplayController *searchController;
@property (nonatomic) BOOL *isChecked;
@property (strong) NSMutableArray *notes;
//@property (strong, nonatomic) NSArray *_lastIndexPath;
@end
@implementation ViewController
@synthesize tableView;
@synthesize addButton;
//@synthesize _lastIndexPath;
@synthesize managedObjectContext;
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = @"My Notes";
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
// place search bar coordinates where the navbar is position - offset by statusbar
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
//self.searchResults = [[NSArray alloc] init];
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch)];
self.navigationItem.rightBarButtonItem = searchButton;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Notes"];
NSError *error = nil;
self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"mod_time" ascending:NO];
[self.notes sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]]
;
NSLog(@"Your Error - %@",error.description);
[tableView reloadData];
}
#pragma mark - Search controller
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
}
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
// [self.searchBar removeFromSuperview];
}
- (void)toggleSearch
{
[self.view addSubview:self.searchBar];
[self.searchController setActive:YES animated:YES];
[self.searchBar becomeFirstResponder];
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Notes" inManagedObjectContext:_notes];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"notes.title contains[c] %@", searchText];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray* searchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
// return searchResults.count;
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return self.notes.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = (TableViewCell*)[aTableView dequeueReusableCellWithIdentifier:@"MycellIdentifier"];
if(cell == nil)
{
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MycellIdentifier"];
}
_notes = [_notes objectAtIndex:indexPath.row];
// Configure the cell...
NSManagedObject *note = [self.notes objectAtIndex:indexPath.row];
NSDate *date = [note valueForKey:@"mod_time"];
cell.textLabel.text = [note valueForKey:@"title"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (IBAction)addButtonPressed:(id)sender {
AddNoteViewController *addNoteVC = [AddNoteViewController new];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)cTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[self.notes objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.notes removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
@end
``` | 2015/09/02 | [
"https://Stackoverflow.com/questions/32353300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5203412/"
] | I had a similar problem. To fix it, I created an SSIS "Composant Script" in which I created a "guid" output. The script VS C# code was the following :
```
Row.guid = Guid.NewGuid();
```
Finally, I routed the output as a derived column into my database "OLE DB Destination" to generate a guid for every new entry. | Simply do it in an Execute SQL Task.
* Open the task
* Under General -> SQL Statement, enter your query `Select NewID() MyID` in the "SQLStatement" field
* Under General -> Result Set, choose "Single row"
* Under Parameter Mapping, Enter your User::myID in Variable Name, "Input" as direction, 0 as Parameter Name, and -1 as Parameter Size
* Under Result Set, enter "MyID" for your Result Name and type the variable in Variable Name
-Click OK
Done. Note that "MyID" is a value you can choose. EDIT: "User::myID" corresponds to the SSIS variable that you create. |
23,697,956 | I am developing a Windows Phone 8.0 App in VS2010
and in some point , i decided to make 2 classes (Player,Game)
**Game.cs**
```
public class Game
{
public string Name { get; set; }
public bool[] LevelsUnlocked { get; set; }
public bool firstTimePlaying { get; set; }
public Game(int numOfLevels)
{
this.firstTimePlaying = true;
this.LevelsUnlocked = new bool[numOfLevels];
}
}
```
**Player.cs**
```
public class Player
{
public int ID { get; set; }
public string FirstName{ get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int Rank { get; set; }
public int Points { get; set; }
public string RankDescreption { get; set; }
public Uri Avatar { get; set; }
public List<Game> Games;
public Player()
{
Game HourGlass = new Game(6);
Game CommonNumbers = new Game(11);
Games.Add(HourGlass);
Games.Add(CommonNumbers);
}
}
```
When i debug , the app crashes at the Line : `Games.Add(HourGlass);`
because of `AccessViolationException`, i don't see what is the problem of adding the item to the list .
so what is it ? | 2014/05/16 | [
"https://Stackoverflow.com/questions/23697956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3264464/"
] | You must initialize a list before using it.
This:
```
public List<Game> Games;
```
..needs to be this:
```
public List<Game> Games = new List<Game>();
```
I am surprised you are getting an `AccessViolationException`.. I would have expected a `NullReferenceException`. | You haven't set your Games to a new list.
```
public List<Game> Games = new List<Game>();
public Player()
{
Game HourGlass = new Game(6);
Game CommonNumbers = new Game(11);
Games.Add(HourGlass);
Games.Add(CommonNumbers);
}
``` |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | "**Confirming the hypothesis**" always sounds good in a technical paper. Or "**as hypothesized**".
If you are noting agreement with previous results, you can say "**validating/confirming results from...**". | **Paralleled**
>
> a person or thing that is similar or analogous to another.
>
>
>
The experimental results **paralleled** the theoretically expected results outlined in Paper/Report/Experiment x/y/z
Alternatively:
* Corresponded
* Analogous
The correct word choice would also depend on the way the information is presented to the reader. |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | Consider [synonyms](http://thesaurus.com/browse/consistent) of *[consistent](http://en.wiktionary.org/wiki/consistent#Adjective)*, such as *[compatible](http://en.wiktionary.org/wiki/compatible#Adjective)* and *[congruent](http://en.wiktionary.org/wiki/congruent#Adjective)*; eg, “Results of experiment B were consistent / compatible / congruent with those of experiment A.” Also consider *[in accord with](http://en.wiktionary.org/wiki/accord#Noun)*; eg, “In accord with predictions based on experiment A, experiment B showed that...” | If the results of your second experiment were predicted by the first experiment then there was no need to carry the former. Maybe you deduced from the first experiment's results that the second experiment might give certain results, or you had doubts about the reasons for the results of the first experiment. In this case, maybe, *as predicted* is the wrong expression.
>
> What about *as indicated*?
>
>
> |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | "**Confirming the hypothesis**" always sounds good in a technical paper. Or "**as hypothesized**".
If you are noting agreement with previous results, you can say "**validating/confirming results from...**". | If the results of your second experiment were predicted by the first experiment then there was no need to carry the former. Maybe you deduced from the first experiment's results that the second experiment might give certain results, or you had doubts about the reasons for the results of the first experiment. In this case, maybe, *as predicted* is the wrong expression.
>
> What about *as indicated*?
>
>
> |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | Consider [synonyms](http://thesaurus.com/browse/consistent) of *[consistent](http://en.wiktionary.org/wiki/consistent#Adjective)*, such as *[compatible](http://en.wiktionary.org/wiki/compatible#Adjective)* and *[congruent](http://en.wiktionary.org/wiki/congruent#Adjective)*; eg, “Results of experiment B were consistent / compatible / congruent with those of experiment A.” Also consider *[in accord with](http://en.wiktionary.org/wiki/accord#Noun)*; eg, “In accord with predictions based on experiment A, experiment B showed that...” | The primary question asks for a **linking phrase** for a discussion of "***expected***" results from a secondary experiment. You could say the results of the second experiment were "***anticipated***".
>
> The results of the second experiment were "**anticipated in support
> of**" deductions made during the first experiment.
>
>
>
The second experiment was thus also **anticipated to affirm** the working deduction of the primary experiment. It could be referred to as **confirmatory** as well.
<https://www.thefreedictionary.com/affirm>
<https://www.thefreedictionary.com/confirm> |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | I think the word you are looking for is **corroborate**:
>
> [**corroborate**](http://www.merriam-webster.com/dictionary/corroborate): to
> support or help prove (a statement, theory, etc.) by providing information or evidence
>
>
>
So, you performed a first experiment resulting in "x". The result "x" supports your hypothesis. You then perform a second experiment that, if the results of your first experiment are correct, will support the results of your first experiment. If that turns out to be the case, you would say that the results of your second experiment **corroborate** the results of your first experiment, and, thereby, strengthen the evidence in support of your hypothesis. | If the results of your second experiment were predicted by the first experiment then there was no need to carry the former. Maybe you deduced from the first experiment's results that the second experiment might give certain results, or you had doubts about the reasons for the results of the first experiment. In this case, maybe, *as predicted* is the wrong expression.
>
> What about *as indicated*?
>
>
> |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | "Corollary" is the usual technical/scientific term to describe the consequent or expected sets of derivative results or conclusions of a main theory, hypothesis or experiment.
>
> [cor·ol·lar·y](http://www.thefreedictionary.com/corollary) (kôr-lr, kr-)
> n. pl. cor·ol·lar·ies
>
>
>
> 1. A proposition that follows with little or no proof required from one already proven.
> 2. A deduction or an inference.
> 3. A natural consequence or effect; a result.
>
>
> adj.
> Consequent; resultant.
>
>
>
For example,
>
> I have thus concluded the 1st and 2nd experiments. The results of the 2nd experiment have demonstrated to be corollaries to those of the 1st.
>
>
> | "Therefore it proves that" also passes off in a technical paper. |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | How about: clearly, apparently, obviously, evidently, patently?
The word obviously can sometimes affect readers adversely, "well, it wasn't so obvious to me." | [Ergo](http://www.merriam-webster.com/dictionary/ergo)
>
> : therefore, hence
>
>
>
(definition from m-w.com) |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | Consider [synonyms](http://thesaurus.com/browse/consistent) of *[consistent](http://en.wiktionary.org/wiki/consistent#Adjective)*, such as *[compatible](http://en.wiktionary.org/wiki/compatible#Adjective)* and *[congruent](http://en.wiktionary.org/wiki/congruent#Adjective)*; eg, “Results of experiment B were consistent / compatible / congruent with those of experiment A.” Also consider *[in accord with](http://en.wiktionary.org/wiki/accord#Noun)*; eg, “In accord with predictions based on experiment A, experiment B showed that...” | "Corollary" is the usual technical/scientific term to describe the consequent or expected sets of derivative results or conclusions of a main theory, hypothesis or experiment.
>
> [cor·ol·lar·y](http://www.thefreedictionary.com/corollary) (kôr-lr, kr-)
> n. pl. cor·ol·lar·ies
>
>
>
> 1. A proposition that follows with little or no proof required from one already proven.
> 2. A deduction or an inference.
> 3. A natural consequence or effect; a result.
>
>
> adj.
> Consequent; resultant.
>
>
>
For example,
>
> I have thus concluded the 1st and 2nd experiments. The results of the 2nd experiment have demonstrated to be corollaries to those of the 1st.
>
>
> |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | The primary question asks for a **linking phrase** for a discussion of "***expected***" results from a secondary experiment. You could say the results of the second experiment were "***anticipated***".
>
> The results of the second experiment were "**anticipated in support
> of**" deductions made during the first experiment.
>
>
>
The second experiment was thus also **anticipated to affirm** the working deduction of the primary experiment. It could be referred to as **confirmatory** as well.
<https://www.thefreedictionary.com/affirm>
<https://www.thefreedictionary.com/confirm> | "Therefore it proves that" also passes off in a technical paper. |
106,477 | I am writing a technical paper where I have described an experiment resulting in "x". Then I go on to describe the result of a second experiment whose result was expected since the reason was deduced in the previous experiment (x). I'm looking for a phrase to tie the two sentences together but I did not want to use "as expected" or "it would follow".
I know there is another phrase out there that suits better but I can't seem to come up with it right now so I need your help. Thanks. | 2013/03/07 | [
"https://english.stackexchange.com/questions/106477",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/38999/"
] | "**Confirming the hypothesis**" always sounds good in a technical paper. Or "**as hypothesized**".
If you are noting agreement with previous results, you can say "**validating/confirming results from...**". | "Corollary" is the usual technical/scientific term to describe the consequent or expected sets of derivative results or conclusions of a main theory, hypothesis or experiment.
>
> [cor·ol·lar·y](http://www.thefreedictionary.com/corollary) (kôr-lr, kr-)
> n. pl. cor·ol·lar·ies
>
>
>
> 1. A proposition that follows with little or no proof required from one already proven.
> 2. A deduction or an inference.
> 3. A natural consequence or effect; a result.
>
>
> adj.
> Consequent; resultant.
>
>
>
For example,
>
> I have thus concluded the 1st and 2nd experiments. The results of the 2nd experiment have demonstrated to be corollaries to those of the 1st.
>
>
> |
39,131,812 | if I want to express something like [just a simple example]:
```
int a = 0;
for (int x = 0; x < n; x += 1)
a = 1 - a;
```
what should I do in Haskell, *since it doesn't have variable concept?* (maybe wrong, see: [Does Haskell have variables?](https://stackoverflow.com/questions/993124/does-haskell-have-variables)) | 2016/08/24 | [
"https://Stackoverflow.com/questions/39131812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4280916/"
] | Often, repetition that you would perform with a loop in a procedural language is accomplished with [recursion](http://learnyouahaskell.com/recursion) in Haskell. In this case, you should think about what the result of the loop is. It appears to alternate between 0 and 1. There are several ways to do this in Haskell. One way is
```
alternatingList n = take n alternating0and1
alternating0and1 = 0 : alternating1and0
alternating1and0 = 1 : alternating0and1
``` | In Haskell instead of using loops, you combine standard library functions and/or your own recursive function to achieve the desired effect.
In your example code you seem to be setting `a` to either 0 or 1 depending on whether or not `n` is even (in a rather confusing fashion if I'm honest). To achieve the same in Haskell, you'd write:
```
a =
if even n
then 0
else 1
``` |
39,131,812 | if I want to express something like [just a simple example]:
```
int a = 0;
for (int x = 0; x < n; x += 1)
a = 1 - a;
```
what should I do in Haskell, *since it doesn't have variable concept?* (maybe wrong, see: [Does Haskell have variables?](https://stackoverflow.com/questions/993124/does-haskell-have-variables)) | 2016/08/24 | [
"https://Stackoverflow.com/questions/39131812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4280916/"
] | There are a few options. First, you can rewrite the problem with naive recursion:
```
loop :: Int -> Int
loop n = loop' n 0
where loop' 0 a = a
loop' n a = loop' (n - 1) (1 - a)
```
Next, you can restate recursion as a fold:
```
loop :: Int -> Int
loop n = foldr (\a _ -> 1 - a) 0 [0..n]
```
Or you can use `State` to simulate a for loop:
```
import Control.Monad
import Control.Monad.State
loop :: Int -> Int
loop n = execState (forM_ [0..n]
(\_ -> modify (\a -> 1 - a))) 0
``` | In Haskell instead of using loops, you combine standard library functions and/or your own recursive function to achieve the desired effect.
In your example code you seem to be setting `a` to either 0 or 1 depending on whether or not `n` is even (in a rather confusing fashion if I'm honest). To achieve the same in Haskell, you'd write:
```
a =
if even n
then 0
else 1
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.